code
stringlengths
1
25.8M
language
stringclasses
18 values
source
stringclasses
4 values
repo
stringclasses
78 values
path
stringlengths
0
268
#!/usr/bin/python # (c) 2016, NetApp, Inc # 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: netapp_e_amg_sync short_description: NetApp E-Series conduct synchronization actions on asynchronous mirror groups. description: - Allows for the initialization, suspension and resumption of an asynchronous mirror group's synchronization for NetApp E-series storage arrays. version_added: '2.2' author: Kevin Hulquest (@hulquest) options: api_username: required: true description: - The username to authenticate with the SANtricity WebServices Proxy or embedded REST API. api_password: required: true description: - The password to authenticate with the SANtricity WebServices Proxy or embedded REST API. api_url: required: true description: - The url to the SANtricity WebServices Proxy or embedded REST API. validate_certs: required: false default: true description: - Should https certificates be validated? type: bool ssid: description: - The ID of the storage array containing the AMG you wish to target name: description: - The name of the async mirror group you wish to target required: yes state: description: - The synchronization action you'd like to take. - If C(running) then it will begin syncing if there is no active sync or will resume a suspended sync. If there is already a sync in progress, it will return with an OK status. - If C(suspended) it will suspend any ongoing sync action, but return OK if there is no active sync or if the sync is already suspended choices: - running - suspended required: yes delete_recovery_point: description: - Indicates whether the failures point can be deleted on the secondary if necessary to achieve the synchronization. - If true, and if the amount of unsynchronized data exceeds the CoW repository capacity on the secondary for any member volume, the last failures point will be deleted and synchronization will continue. - If false, the synchronization will be suspended if the amount of unsynchronized data exceeds the CoW Repository capacity on the secondary and the failures point will be preserved. - "NOTE: This only has impact for newly launched syncs." type: bool default: no """ EXAMPLES = """ - name: start AMG async netapp_e_amg_sync: name: "{{ amg_sync_name }}" state: running ssid: "{{ ssid }}" api_url: "{{ netapp_api_url }}" api_username: "{{ netapp_api_username }}" api_password: "{{ netapp_api_password }}" """ RETURN = """ json: description: The object attributes of the AMG. returned: success type: str example: { "changed": false, "connectionType": "fc", "groupRef": "3700000060080E5000299C24000006EF57ACAC70", "groupState": "optimal", "id": "3700000060080E5000299C24000006EF57ACAC70", "label": "made_with_ansible", "localRole": "primary", "mirrorChannelRemoteTarget": "9000000060080E5000299C24005B06E557AC7EEC", "orphanGroup": false, "recoveryPointAgeAlertThresholdMinutes": 20, "remoteRole": "secondary", "remoteTarget": { "nodeName": { "ioInterfaceType": "fc", "iscsiNodeName": null, "remoteNodeWWN": "20040080E5299F1C" }, "remoteRef": "9000000060080E5000299C24005B06E557AC7EEC", "scsiinitiatorTargetBaseProperties": { "ioInterfaceType": "fc", "iscsiinitiatorTargetBaseParameters": null } }, "remoteTargetId": "ansible2", "remoteTargetName": "Ansible2", "remoteTargetWwn": "60080E5000299F880000000056A25D56", "repositoryUtilizationWarnThreshold": 80, "roleChangeProgress": "none", "syncActivity": "idle", "syncCompletionTimeAlertThresholdMinutes": 10, "syncIntervalMinutes": 10, "worldWideName": "60080E5000299C24000006EF57ACAC70" } """ import json from ansible.module_utils.api import basic_auth_argument_spec from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six.moves.urllib.error import HTTPError from ansible.module_utils.urls import open_url def request(url, data=None, headers=None, method='GET', use_proxy=True, force=False, last_mod_time=None, timeout=10, validate_certs=True, url_username=None, url_password=None, http_agent=None, force_basic_auth=True, ignore_errors=False): try: r = open_url(url=url, data=data, headers=headers, method=method, use_proxy=use_proxy, force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs, url_username=url_username, url_password=url_password, http_agent=http_agent, force_basic_auth=force_basic_auth) except HTTPError as e: r = e.fp try: raw_data = r.read() if raw_data: data = json.loads(raw_data) else: raw_data = None except Exception: if ignore_errors: pass else: raise Exception(raw_data) resp_code = r.getcode() if resp_code >= 400 and not ignore_errors: raise Exception(resp_code, data) else: return resp_code, data class AMGsync(object): def __init__(self): argument_spec = basic_auth_argument_spec() argument_spec.update(dict( api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), name=dict(required=True, type='str'), ssid=dict(required=True, type='str'), state=dict(required=True, type='str', choices=['running', 'suspended']), delete_recovery_point=dict(required=False, type='bool', default=False) )) self.module = AnsibleModule(argument_spec=argument_spec) args = self.module.params self.name = args['name'] self.ssid = args['ssid'] self.state = args['state'] self.delete_recovery_point = args['delete_recovery_point'] try: self.user = args['api_username'] self.pwd = args['api_password'] self.url = args['api_url'] except KeyError: self.module.fail_json(msg="You must pass in api_username" "and api_password and api_url to the module.") self.certs = args['validate_certs'] self.post_headers = { "Accept": "application/json", "Content-Type": "application/json" } self.amg_id, self.amg_obj = self.get_amg() def get_amg(self): endpoint = self.url + '/storage-systems/%s/async-mirrors' % self.ssid (rc, amg_objs) = request(endpoint, url_username=self.user, url_password=self.pwd, validate_certs=self.certs, headers=self.post_headers) try: amg_id = filter(lambda d: d['label'] == self.name, amg_objs)[0]['id'] amg_obj = filter(lambda d: d['label'] == self.name, amg_objs)[0] except IndexError: self.module.fail_json( msg="There is no async mirror group %s associated with storage array %s" % (self.name, self.ssid)) return amg_id, amg_obj @property def current_state(self): amg_id, amg_obj = self.get_amg() return amg_obj['syncActivity'] def run_sync_action(self): # If we get to this point we know that the states differ, and there is no 'err' state, # so no need to revalidate post_body = dict() if self.state == 'running': if self.current_state == 'idle': if self.delete_recovery_point: post_body.update(dict(deleteRecoveryPointIfNecessary=self.delete_recovery_point)) suffix = 'sync' else: # In a suspended state suffix = 'resume' else: suffix = 'suspend' endpoint = self.url + "/storage-systems/%s/async-mirrors/%s/%s" % (self.ssid, self.amg_id, suffix) (rc, resp) = request(endpoint, method='POST', url_username=self.user, url_password=self.pwd, validate_certs=self.certs, data=json.dumps(post_body), headers=self.post_headers, ignore_errors=True) if not str(rc).startswith('2'): self.module.fail_json(msg=str(resp['errorMessage'])) return resp def apply(self): state_map = dict( running=['active'], suspended=['userSuspended', 'internallySuspended', 'paused'], err=['unkown', '_UNDEFINED']) if self.current_state not in state_map[self.state]: if self.current_state in state_map['err']: self.module.fail_json( msg="The sync is a state of '%s', this requires manual intervention. " + "Please investigate and try again" % self.current_state) else: self.amg_obj = self.run_sync_action() (ret, amg) = self.get_amg() self.module.exit_json(changed=False, **amg) def main(): sync = AMGsync() sync.apply() if __name__ == '__main__': main()
unknown
codeparrot/codeparrot-clean
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import tempfile from ansible.module_utils import basic from units.compat import unittest from ansible.module_utils._text import to_bytes from ansible.module_utils.basic import AnsibleModule from ansible.modules.known_hosts import compute_diff, sanity_check class KnownHostsDiffTestCase(unittest.TestCase): def _create_file(self, content): tmp_file = tempfile.NamedTemporaryFile(prefix='ansible-test-', suffix='-known_hosts', delete=False) tmp_file.write(to_bytes(content)) tmp_file.close() self.addCleanup(os.unlink, tmp_file.name) return tmp_file.name def test_no_existing_file(self): path = "/tmp/this_file_does_not_exists_known_hosts" key = 'example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=None, replace_or_add=False, state='present', key=key) self.assertEqual(diff, { 'before_header': '/dev/null', 'after_header': path, 'before': '', 'after': 'example.com ssh-rsa AAAAetc\n', }) def test_key_addition(self): path = self._create_file( 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=None, replace_or_add=False, state='present', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'two.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\none.example.com ssh-rsa AAAAetc\n', }) def test_no_change(self): path = self._create_file( 'one.example.com ssh-rsa AAAAetc\n' 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=1, replace_or_add=False, state='present', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'one.example.com ssh-rsa AAAAetc\ntwo.example.com ssh-rsa BBBBetc\n', 'after': 'one.example.com ssh-rsa AAAAetc\ntwo.example.com ssh-rsa BBBBetc\n', }) def test_key_change(self): path = self._create_file( 'one.example.com ssh-rsa AAAaetc\n' 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=1, replace_or_add=True, state='present', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'one.example.com ssh-rsa AAAaetc\ntwo.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\none.example.com ssh-rsa AAAAetc\n', }) def test_key_removal(self): path = self._create_file( 'one.example.com ssh-rsa AAAAetc\n' 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=1, replace_or_add=False, state='absent', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'one.example.com ssh-rsa AAAAetc\ntwo.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\n', }) def test_key_removal_no_change(self): path = self._create_file( 'two.example.com ssh-rsa BBBBetc\n' ) key = 'one.example.com ssh-rsa AAAAetc\n' diff = compute_diff(path, found_line=None, replace_or_add=False, state='absent', key=key) self.assertEqual(diff, { 'before_header': path, 'after_header': path, 'before': 'two.example.com ssh-rsa BBBBetc\n', 'after': 'two.example.com ssh-rsa BBBBetc\n', }) def test_sanity_check(self): basic._load_params = lambda: {} # Module used internally to execute ssh-keygen system executable module = AnsibleModule(argument_spec={}) host = '10.0.0.1' key = '%s ssh-rsa ASDF foo@bar' % (host,) keygen = module.get_bin_path('ssh-keygen') sanity_check(module, host, key, keygen)
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that the implicit rpath is added only when needed. """ import TestGyp import re import subprocess import sys if sys.platform.startswith('linux'): test = TestGyp.TestGyp(formats=['ninja', 'make']) CHDIR = 'implicit-rpath' test.run_gyp('test.gyp', chdir=CHDIR) test.build('test.gyp', test.ALL, chdir=CHDIR) def GetRpaths(p): p = test.built_file_path(p, chdir=CHDIR) r = re.compile(r'Library rpath: \[([^\]]+)\]') proc = subprocess.Popen(['readelf', '-d', p], stdout=subprocess.PIPE) o = proc.communicate()[0] assert not proc.returncode return r.findall(o) if test.format == 'ninja': expect = '$ORIGIN/lib/' elif test.format == 'make': expect = '$ORIGIN/lib.target/' else: test.fail_test() if GetRpaths('shared_executable') != [expect]: test.fail_test() if GetRpaths('shared_executable_no_so_suffix') != [expect]: test.fail_test() if GetRpaths('static_executable'): test.fail_test() test.pass_test()
unknown
codeparrot/codeparrot-clean
# ext/hybrid.py # Copyright (C) 2005-2014 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 """Define attributes on ORM-mapped classes that have "hybrid" behavior. "hybrid" means the attribute has distinct behaviors defined at the class level and at the instance level. The :mod:`~sqlalchemy.ext.hybrid` extension provides a special form of method decorator, is around 50 lines of code and has almost no dependencies on the rest of SQLAlchemy. It can, in theory, work with any descriptor-based expression system. Consider a mapping ``Interval``, representing integer ``start`` and ``end`` values. We can define higher level functions on mapped classes that produce SQL expressions at the class level, and Python expression evaluation at the instance level. Below, each function decorated with :class:`.hybrid_method` or :class:`.hybrid_property` may receive ``self`` as an instance of the class, or as the class itself:: from sqlalchemy import Column, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Session, aliased from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method Base = declarative_base() class Interval(Base): __tablename__ = 'interval' id = Column(Integer, primary_key=True) start = Column(Integer, nullable=False) end = Column(Integer, nullable=False) def __init__(self, start, end): self.start = start self.end = end @hybrid_property def length(self): return self.end - self.start @hybrid_method def contains(self,point): return (self.start <= point) & (point < self.end) @hybrid_method def intersects(self, other): return self.contains(other.start) | self.contains(other.end) Above, the ``length`` property returns the difference between the ``end`` and ``start`` attributes. With an instance of ``Interval``, this subtraction occurs in Python, using normal Python descriptor mechanics:: >>> i1 = Interval(5, 10) >>> i1.length 5 When dealing with the ``Interval`` class itself, the :class:`.hybrid_property` descriptor evaluates the function body given the ``Interval`` class as the argument, which when evaluated with SQLAlchemy expression mechanics returns a new SQL expression:: >>> print Interval.length interval."end" - interval.start >>> print Session().query(Interval).filter(Interval.length > 10) SELECT interval.id AS interval_id, interval.start AS interval_start, interval."end" AS interval_end FROM interval WHERE interval."end" - interval.start > :param_1 ORM methods such as :meth:`~.Query.filter_by` generally use ``getattr()`` to locate attributes, so can also be used with hybrid attributes:: >>> print Session().query(Interval).filter_by(length=5) SELECT interval.id AS interval_id, interval.start AS interval_start, interval."end" AS interval_end FROM interval WHERE interval."end" - interval.start = :param_1 The ``Interval`` class example also illustrates two methods, ``contains()`` and ``intersects()``, decorated with :class:`.hybrid_method`. This decorator applies the same idea to methods that :class:`.hybrid_property` applies to attributes. The methods return boolean values, and take advantage of the Python ``|`` and ``&`` bitwise operators to produce equivalent instance-level and SQL expression-level boolean behavior:: >>> i1.contains(6) True >>> i1.contains(15) False >>> i1.intersects(Interval(7, 18)) True >>> i1.intersects(Interval(25, 29)) False >>> print Session().query(Interval).filter(Interval.contains(15)) SELECT interval.id AS interval_id, interval.start AS interval_start, interval."end" AS interval_end FROM interval WHERE interval.start <= :start_1 AND interval."end" > :end_1 >>> ia = aliased(Interval) >>> print Session().query(Interval, ia).filter(Interval.intersects(ia)) SELECT interval.id AS interval_id, interval.start AS interval_start, interval."end" AS interval_end, interval_1.id AS interval_1_id, interval_1.start AS interval_1_start, interval_1."end" AS interval_1_end FROM interval, interval AS interval_1 WHERE interval.start <= interval_1.start AND interval."end" > interval_1.start OR interval.start <= interval_1."end" AND interval."end" > interval_1."end" Defining Expression Behavior Distinct from Attribute Behavior -------------------------------------------------------------- Our usage of the ``&`` and ``|`` bitwise operators above was fortunate, considering our functions operated on two boolean values to return a new one. In many cases, the construction of an in-Python function and a SQLAlchemy SQL expression have enough differences that two separate Python expressions should be defined. The :mod:`~sqlalchemy.ext.hybrid` decorators define the :meth:`.hybrid_property.expression` modifier for this purpose. As an example we'll define the radius of the interval, which requires the usage of the absolute value function:: from sqlalchemy import func class Interval(object): # ... @hybrid_property def radius(self): return abs(self.length) / 2 @radius.expression def radius(cls): return func.abs(cls.length) / 2 Above the Python function ``abs()`` is used for instance-level operations, the SQL function ``ABS()`` is used via the :attr:`.func` object for class-level expressions:: >>> i1.radius 2 >>> print Session().query(Interval).filter(Interval.radius > 5) SELECT interval.id AS interval_id, interval.start AS interval_start, interval."end" AS interval_end FROM interval WHERE abs(interval."end" - interval.start) / :abs_1 > :param_1 Defining Setters ---------------- Hybrid properties can also define setter methods. If we wanted ``length`` above, when set, to modify the endpoint value:: class Interval(object): # ... @hybrid_property def length(self): return self.end - self.start @length.setter def length(self, value): self.end = self.start + value The ``length(self, value)`` method is now called upon set:: >>> i1 = Interval(5, 10) >>> i1.length 5 >>> i1.length = 12 >>> i1.end 17 Working with Relationships -------------------------- There's no essential difference when creating hybrids that work with related objects as opposed to column-based data. The need for distinct expressions tends to be greater. Two variants of we'll illustrate are the "join-dependent" hybrid, and the "correlated subquery" hybrid. Join-Dependent Relationship Hybrid ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Consider the following declarative mapping which relates a ``User`` to a ``SavingsAccount``:: from sqlalchemy import Column, Integer, ForeignKey, Numeric, String from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.hybrid import hybrid_property Base = declarative_base() class SavingsAccount(Base): __tablename__ = 'account' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('user.id'), nullable=False) balance = Column(Numeric(15, 5)) class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) name = Column(String(100), nullable=False) accounts = relationship("SavingsAccount", backref="owner") @hybrid_property def balance(self): if self.accounts: return self.accounts[0].balance else: return None @balance.setter def balance(self, value): if not self.accounts: account = Account(owner=self) else: account = self.accounts[0] account.balance = value @balance.expression def balance(cls): return SavingsAccount.balance The above hybrid property ``balance`` works with the first ``SavingsAccount`` entry in the list of accounts for this user. The in-Python getter/setter methods can treat ``accounts`` as a Python list available on ``self``. However, at the expression level, it's expected that the ``User`` class will be used in an appropriate context such that an appropriate join to ``SavingsAccount`` will be present:: >>> print Session().query(User, User.balance).\\ ... join(User.accounts).filter(User.balance > 5000) SELECT "user".id AS user_id, "user".name AS user_name, account.balance AS account_balance FROM "user" JOIN account ON "user".id = account.user_id WHERE account.balance > :balance_1 Note however, that while the instance level accessors need to worry about whether ``self.accounts`` is even present, this issue expresses itself differently at the SQL expression level, where we basically would use an outer join:: >>> from sqlalchemy import or_ >>> print (Session().query(User, User.balance).outerjoin(User.accounts). ... filter(or_(User.balance < 5000, User.balance == None))) SELECT "user".id AS user_id, "user".name AS user_name, account.balance AS account_balance FROM "user" LEFT OUTER JOIN account ON "user".id = account.user_id WHERE account.balance < :balance_1 OR account.balance IS NULL Correlated Subquery Relationship Hybrid ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ We can, of course, forego being dependent on the enclosing query's usage of joins in favor of the correlated subquery, which can portably be packed into a single column expression. A correlated subquery is more portable, but often performs more poorly at the SQL level. Using the same technique illustrated at :ref:`mapper_column_property_sql_expressions`, we can adjust our ``SavingsAccount`` example to aggregate the balances for *all* accounts, and use a correlated subquery for the column expression:: from sqlalchemy import Column, Integer, ForeignKey, Numeric, String from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy import select, func Base = declarative_base() class SavingsAccount(Base): __tablename__ = 'account' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('user.id'), nullable=False) balance = Column(Numeric(15, 5)) class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) name = Column(String(100), nullable=False) accounts = relationship("SavingsAccount", backref="owner") @hybrid_property def balance(self): return sum(acc.balance for acc in self.accounts) @balance.expression def balance(cls): return select([func.sum(SavingsAccount.balance)]).\\ where(SavingsAccount.user_id==cls.id).\\ label('total_balance') The above recipe will give us the ``balance`` column which renders a correlated SELECT:: >>> print s.query(User).filter(User.balance > 400) SELECT "user".id AS user_id, "user".name AS user_name FROM "user" WHERE (SELECT sum(account.balance) AS sum_1 FROM account WHERE account.user_id = "user".id) > :param_1 .. _hybrid_custom_comparators: Building Custom Comparators --------------------------- The hybrid property also includes a helper that allows construction of custom comparators. A comparator object allows one to customize the behavior of each SQLAlchemy expression operator individually. They are useful when creating custom types that have some highly idiosyncratic behavior on the SQL side. The example class below allows case-insensitive comparisons on the attribute named ``word_insensitive``:: from sqlalchemy.ext.hybrid import Comparator, hybrid_property from sqlalchemy import func, Column, Integer, String from sqlalchemy.orm import Session from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class CaseInsensitiveComparator(Comparator): def __eq__(self, other): return func.lower(self.__clause_element__()) == func.lower(other) class SearchWord(Base): __tablename__ = 'searchword' id = Column(Integer, primary_key=True) word = Column(String(255), nullable=False) @hybrid_property def word_insensitive(self): return self.word.lower() @word_insensitive.comparator def word_insensitive(cls): return CaseInsensitiveComparator(cls.word) Above, SQL expressions against ``word_insensitive`` will apply the ``LOWER()`` SQL function to both sides:: >>> print Session().query(SearchWord).filter_by(word_insensitive="Trucks") SELECT searchword.id AS searchword_id, searchword.word AS searchword_word FROM searchword WHERE lower(searchword.word) = lower(:lower_1) The ``CaseInsensitiveComparator`` above implements part of the :class:`.ColumnOperators` interface. A "coercion" operation like lowercasing can be applied to all comparison operations (i.e. ``eq``, ``lt``, ``gt``, etc.) using :meth:`.Operators.operate`:: class CaseInsensitiveComparator(Comparator): def operate(self, op, other): return op(func.lower(self.__clause_element__()), func.lower(other)) Hybrid Value Objects -------------------- Note in our previous example, if we were to compare the ``word_insensitive`` attribute of a ``SearchWord`` instance to a plain Python string, the plain Python string would not be coerced to lower case - the ``CaseInsensitiveComparator`` we built, being returned by ``@word_insensitive.comparator``, only applies to the SQL side. A more comprehensive form of the custom comparator is to construct a *Hybrid Value Object*. This technique applies the target value or expression to a value object which is then returned by the accessor in all cases. The value object allows control of all operations upon the value as well as how compared values are treated, both on the SQL expression side as well as the Python value side. Replacing the previous ``CaseInsensitiveComparator`` class with a new ``CaseInsensitiveWord`` class:: class CaseInsensitiveWord(Comparator): "Hybrid value representing a lower case representation of a word." def __init__(self, word): if isinstance(word, basestring): self.word = word.lower() elif isinstance(word, CaseInsensitiveWord): self.word = word.word else: self.word = func.lower(word) def operate(self, op, other): if not isinstance(other, CaseInsensitiveWord): other = CaseInsensitiveWord(other) return op(self.word, other.word) def __clause_element__(self): return self.word def __str__(self): return self.word key = 'word' "Label to apply to Query tuple results" Above, the ``CaseInsensitiveWord`` object represents ``self.word``, which may be a SQL function, or may be a Python native. By overriding ``operate()`` and ``__clause_element__()`` to work in terms of ``self.word``, all comparison operations will work against the "converted" form of ``word``, whether it be SQL side or Python side. Our ``SearchWord`` class can now deliver the ``CaseInsensitiveWord`` object unconditionally from a single hybrid call:: class SearchWord(Base): __tablename__ = 'searchword' id = Column(Integer, primary_key=True) word = Column(String(255), nullable=False) @hybrid_property def word_insensitive(self): return CaseInsensitiveWord(self.word) The ``word_insensitive`` attribute now has case-insensitive comparison behavior universally, including SQL expression vs. Python expression (note the Python value is converted to lower case on the Python side here):: >>> print Session().query(SearchWord).filter_by(word_insensitive="Trucks") SELECT searchword.id AS searchword_id, searchword.word AS searchword_word FROM searchword WHERE lower(searchword.word) = :lower_1 SQL expression versus SQL expression:: >>> sw1 = aliased(SearchWord) >>> sw2 = aliased(SearchWord) >>> print Session().query( ... sw1.word_insensitive, ... sw2.word_insensitive).\\ ... filter( ... sw1.word_insensitive > sw2.word_insensitive ... ) SELECT lower(searchword_1.word) AS lower_1, lower(searchword_2.word) AS lower_2 FROM searchword AS searchword_1, searchword AS searchword_2 WHERE lower(searchword_1.word) > lower(searchword_2.word) Python only expression:: >>> ws1 = SearchWord(word="SomeWord") >>> ws1.word_insensitive == "sOmEwOrD" True >>> ws1.word_insensitive == "XOmEwOrX" False >>> print ws1.word_insensitive someword The Hybrid Value pattern is very useful for any kind of value that may have multiple representations, such as timestamps, time deltas, units of measurement, currencies and encrypted passwords. .. seealso:: `Hybrids and Value Agnostic Types <http://techspot.zzzeek.org/2011/10/21/hybrids-and-value-agnostic-types/>`_ - on the techspot.zzzeek.org blog `Value Agnostic Types, Part II <http://techspot.zzzeek.org/2011/10/29/value-agnostic-types-part-ii/>`_ - on the techspot.zzzeek.org blog .. _hybrid_transformers: Building Transformers ---------------------- A *transformer* is an object which can receive a :class:`.Query` object and return a new one. The :class:`.Query` object includes a method :meth:`.with_transformation` that returns a new :class:`.Query` transformed by the given function. We can combine this with the :class:`.Comparator` class to produce one type of recipe which can both set up the FROM clause of a query as well as assign filtering criterion. Consider a mapped class ``Node``, which assembles using adjacency list into a hierarchical tree pattern:: from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Node(Base): __tablename__ = 'node' id =Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('node.id')) parent = relationship("Node", remote_side=id) Suppose we wanted to add an accessor ``grandparent``. This would return the ``parent`` of ``Node.parent``. When we have an instance of ``Node``, this is simple:: from sqlalchemy.ext.hybrid import hybrid_property class Node(Base): # ... @hybrid_property def grandparent(self): return self.parent.parent For the expression, things are not so clear. We'd need to construct a :class:`.Query` where we :meth:`~.Query.join` twice along ``Node.parent`` to get to the ``grandparent``. We can instead return a transforming callable that we'll combine with the :class:`.Comparator` class to receive any :class:`.Query` object, and return a new one that's joined to the ``Node.parent`` attribute and filtered based on the given criterion:: from sqlalchemy.ext.hybrid import Comparator class GrandparentTransformer(Comparator): def operate(self, op, other): def transform(q): cls = self.__clause_element__() parent_alias = aliased(cls) return q.join(parent_alias, cls.parent).\\ filter(op(parent_alias.parent, other)) return transform Base = declarative_base() class Node(Base): __tablename__ = 'node' id =Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('node.id')) parent = relationship("Node", remote_side=id) @hybrid_property def grandparent(self): return self.parent.parent @grandparent.comparator def grandparent(cls): return GrandparentTransformer(cls) The ``GrandparentTransformer`` overrides the core :meth:`.Operators.operate` method at the base of the :class:`.Comparator` hierarchy to return a query-transforming callable, which then runs the given comparison operation in a particular context. Such as, in the example above, the ``operate`` method is called, given the :attr:`.Operators.eq` callable as well as the right side of the comparison ``Node(id=5)``. A function ``transform`` is then returned which will transform a :class:`.Query` first to join to ``Node.parent``, then to compare ``parent_alias`` using :attr:`.Operators.eq` against the left and right sides, passing into :class:`.Query.filter`: .. sourcecode:: pycon+sql >>> from sqlalchemy.orm import Session >>> session = Session() {sql}>>> session.query(Node).\\ ... with_transformation(Node.grandparent==Node(id=5)).\\ ... all() SELECT node.id AS node_id, node.parent_id AS node_parent_id FROM node JOIN node AS node_1 ON node_1.id = node.parent_id WHERE :param_1 = node_1.parent_id {stop} We can modify the pattern to be more verbose but flexible by separating the "join" step from the "filter" step. The tricky part here is ensuring that successive instances of ``GrandparentTransformer`` use the same :class:`.AliasedClass` object against ``Node``. Below we use a simple memoizing approach that associates a ``GrandparentTransformer`` with each class:: class Node(Base): # ... @grandparent.comparator def grandparent(cls): # memoize a GrandparentTransformer # per class if '_gp' not in cls.__dict__: cls._gp = GrandparentTransformer(cls) return cls._gp class GrandparentTransformer(Comparator): def __init__(self, cls): self.parent_alias = aliased(cls) @property def join(self): def go(q): return q.join(self.parent_alias, Node.parent) return go def operate(self, op, other): return op(self.parent_alias.parent, other) .. sourcecode:: pycon+sql {sql}>>> session.query(Node).\\ ... with_transformation(Node.grandparent.join).\\ ... filter(Node.grandparent==Node(id=5)) SELECT node.id AS node_id, node.parent_id AS node_parent_id FROM node JOIN node AS node_1 ON node_1.id = node.parent_id WHERE :param_1 = node_1.parent_id {stop} The "transformer" pattern is an experimental pattern that starts to make usage of some functional programming paradigms. While it's only recommended for advanced and/or patient developers, there's probably a whole lot of amazing things it can be used for. """ from .. import util from ..orm import attributes, interfaces HYBRID_METHOD = util.symbol('HYBRID_METHOD') """Symbol indicating an :class:`_InspectionAttr` that's of type :class:`.hybrid_method`. Is assigned to the :attr:`._InspectionAttr.extension_type` attibute. .. seealso:: :attr:`.Mapper.all_orm_attributes` """ HYBRID_PROPERTY = util.symbol('HYBRID_PROPERTY') """Symbol indicating an :class:`_InspectionAttr` that's of type :class:`.hybrid_method`. Is assigned to the :attr:`._InspectionAttr.extension_type` attibute. .. seealso:: :attr:`.Mapper.all_orm_attributes` """ class hybrid_method(interfaces._InspectionAttr): """A decorator which allows definition of a Python object method with both instance-level and class-level behavior. """ is_attribute = True extension_type = HYBRID_METHOD def __init__(self, func, expr=None): """Create a new :class:`.hybrid_method`. Usage is typically via decorator:: from sqlalchemy.ext.hybrid import hybrid_method class SomeClass(object): @hybrid_method def value(self, x, y): return self._value + x + y @value.expression def value(self, x, y): return func.some_function(self._value, x, y) """ self.func = func self.expr = expr or func def __get__(self, instance, owner): if instance is None: return self.expr.__get__(owner, owner.__class__) else: return self.func.__get__(instance, owner) def expression(self, expr): """Provide a modifying decorator that defines a SQL-expression producing method.""" self.expr = expr return self class hybrid_property(interfaces._InspectionAttr): """A decorator which allows definition of a Python descriptor with both instance-level and class-level behavior. """ is_attribute = True extension_type = HYBRID_PROPERTY def __init__(self, fget, fset=None, fdel=None, expr=None): """Create a new :class:`.hybrid_property`. Usage is typically via decorator:: from sqlalchemy.ext.hybrid import hybrid_property class SomeClass(object): @hybrid_property def value(self): return self._value @value.setter def value(self, value): self._value = value """ self.fget = fget self.fset = fset self.fdel = fdel self.expr = expr or fget util.update_wrapper(self, fget) def __get__(self, instance, owner): if instance is None: return self.expr(owner) else: return self.fget(instance) def __set__(self, instance, value): if self.fset is None: raise AttributeError("can't set attribute") self.fset(instance, value) def __delete__(self, instance): if self.fdel is None: raise AttributeError("can't delete attribute") self.fdel(instance) def setter(self, fset): """Provide a modifying decorator that defines a value-setter method.""" self.fset = fset return self def deleter(self, fdel): """Provide a modifying decorator that defines a value-deletion method.""" self.fdel = fdel return self def expression(self, expr): """Provide a modifying decorator that defines a SQL-expression producing method.""" self.expr = expr return self def comparator(self, comparator): """Provide a modifying decorator that defines a custom comparator producing method. The return value of the decorated method should be an instance of :class:`~.hybrid.Comparator`. """ proxy_attr = attributes.\ create_proxied_attribute(self) def expr(owner): return proxy_attr(owner, self.__name__, self, comparator(owner)) self.expr = expr return self class Comparator(interfaces.PropComparator): """A helper class that allows easy construction of custom :class:`~.orm.interfaces.PropComparator` classes for usage with hybrids.""" property = None def __init__(self, expression): self.expression = expression def __clause_element__(self): expr = self.expression while hasattr(expr, '__clause_element__'): expr = expr.__clause_element__() return expr def adapt_to_entity(self, adapt_to_entity): # interesting.... return self
unknown
codeparrot/codeparrot-clean
from django import forms from basicviz.models import Experiment, BVFeatureSet from decomposition.models import MotifSet from motifdb.models import MDBMotifSet from basicviz.constants import EXPERIMENT_DECOMPOSITION_SOURCE from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ class CreateExperimentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CreateExperimentForm, self).__init__(*args, **kwargs) # self.fields['decompose_from'] = forms.ModelChoiceField( # queryset=MotifSet.objects.all(), # label='Decompose using Mass2Motifs in' # ) self.fields['featureset'] = forms.ModelChoiceField( queryset=BVFeatureSet.objects.filter(name__startswith='binned'), label='Choose width of ms2 bins (to enable comparison with characterised motifs, we strongly recommend default value of 0.005 Da)', initial=BVFeatureSet.objects.get(name='binned_005') ) self.fields['ms2_file'].required = True # self.fields['decompose_from'].required = False self.fields['include_motifset'] = forms.MultipleChoiceField( choices = [(m.id,str(m)) for m in MDBMotifSet.objects.all()], label='Select zero or more motifsets for initial model population', widget=forms.SelectMultiple(attrs={'size': 10}) ) self.fields['include_motifset'].required = False def is_valid(self): valid = super(CreateExperimentForm, self).is_valid() if not valid: return valid ms2_format = self.cleaned_data['experiment_ms2_format'] ms2_file_name = self.cleaned_data['ms2_file'].name.lower() if ms2_format == '0': if not ms2_file_name.endswith('.mzml'): self.add_error('ms2_file', ValidationError(_('Error: Extension should be in .mzML format'), code='invalid')) return False elif ms2_format == '1': if not ms2_file_name.endswith('.msp'): self.add_error('ms2_file', ValidationError(_('Error: Extension should be in .msp format'), code='invalid')) return False elif ms2_format == '2': if not ms2_file_name.endswith('.mgf'): self.add_error('ms2_file', ValidationError(_('Error: Extension should be in .mgf format'), code='invalid')) return False return True class Meta: model = Experiment widgets = { 'name': forms.TextInput(attrs={'style': 'width:300px'}), 'description': forms.Textarea(attrs={'rows': 3, 'cols': 56}), 'csv_file': forms.ClearableFileInput(), 'ms2_file': forms.ClearableFileInput(), } labels = { 'name': '(Required) Experiment name. Note that this must be unique in the system', 'description': '(Required) Experiment description.', 'csv_file': 'MS1 file (CSV) [see above for formatting instructions]', 'csv_mz_column': 'Column name for mz in csv file. If blank, reverts to mz', # 'csv_rt_column': 'Column name for rt in csv file. If blank, reverts to rt', 'csv_rt_units': 'Units for time column (minutes or seconds)', 'csv_id_column': 'ID column in csv file to match to the ms2 file', 'ms2_id_field': 'ID field in ms2 file to link to ID column in csv', 'ms2_file': '(Required) MS2 file (mzML, msp, or mgf)', 'ms2_name_field': 'The field to use in the molecular metadata to use as a name. Must be unique.', 'isolation_window': 'Fragmentation isolation window. Used to match fragment spectra with MS1 peaks.', 'mz_tol': 'Mass tolerance when linking peaks from the peaklist to those found in MS2 file (ppm)', 'rt_tol': 'Retention time tolerance when linking peaks from the peaklist to those found in MS2 file (seconds)', 'min_ms1_rt': 'Minimum retention time of MS1 peaks to store (seconds)', 'max_ms1_rt': 'Maximum retention time of MS1 peaks to store (seconds)', 'min_ms1_intensity': 'Minimum intensity of MS1 peaks to store', 'min_ms2_intensity': 'Minimum intensity of MS2 peaks to store', 'featureset': 'Width of the MS2 bins', 'filter_duplicates': 'Attempt to filter out duplicate MS1 peaks. If Set to True, the code merges peaks within duplicate_filter_mz_tol and duplicate_filter_rt_tol.', 'duplicate_filter_mz_tol': 'mz tol (ppm) for duplicate filtering', 'duplicate_filter_rt_tol': 'rt tol (seconds) for duplicate filtering', 'K': 'Number of Mass2Motifs', # 'decomposition_source': 'Use for decomposition in the future?', 'n_its': 'Number of iterations (for LDA).', # 'experiment_type': '(Required) LDA, or decomposition,' } fields = [ 'name', 'description', # 'experiment_type', 'experiment_ms2_format', 'ms2_file', 'csv_file', 'csv_mz_column', # 'csv_rt_column', 'csv_rt_units', 'csv_id_column', 'ms2_id_field', 'ms2_name_field', 'isolation_window', 'mz_tol', 'rt_tol', 'min_ms1_rt', 'max_ms1_rt', 'min_ms1_intensity', 'min_ms2_intensity', 'featureset', 'filter_duplicates', 'duplicate_filter_mz_tol', 'duplicate_filter_rt_tol', 'K', 'n_its','include_motifset', ] exclude = ('status',) class UploadExperimentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UploadExperimentForm, self).__init__(*args, **kwargs) self.fields['featureset'] = forms.ModelChoiceField( queryset=BVFeatureSet.objects.filter(name__startswith='binned'), label='Choose width of ms2 bins (to enable comparison with characterised motifs, we strongly recommend default value of 0.005 Da)', initial=BVFeatureSet.objects.get(name='binned_005') ) self.fields['ms2_file'].required = True class Meta: model = Experiment widgets = { 'name': forms.TextInput(attrs={'style': 'width:300px'}), 'description': forms.Textarea(attrs={'rows': 3, 'cols': 56}), 'ms2_file': forms.ClearableFileInput(), } labels = { 'name': '(Required) Experiment name. Note that this must be unique in the system', 'description': '(Required) Experiment description.', 'ms2_file': 'LDA output file', } fields = [ 'name', 'description', 'ms2_file', 'featureset' ] exclude = ('status', 'experiment_type') class UploadGensimExperimentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UploadGensimExperimentForm, self).__init__(*args, **kwargs) self.fields['featureset'] = forms.ModelChoiceField( queryset=BVFeatureSet.objects.filter(name__startswith='binned'), label='Choose width of ms2 bins (to enable comparison with characterised motifs, we strongly recommend default value of 0.005 Da)', initial=BVFeatureSet.objects.get(name='binned_005') ) self.fields['ms2_file'].required = True self.fields['csv_file'].required = True class Meta: model = Experiment widgets = { 'name': forms.TextInput(attrs={'style': 'width:300px'}), 'description': forms.Textarea(attrs={'rows': 3, 'cols': 56}), 'ms2_file': forms.ClearableFileInput(), 'csv_file': forms.ClearableFileInput(), } labels = { 'name': '(Required) Experiment name. Note that this must be unique in the system', 'description': '(Required) Experiment description.', 'ms2_file': 'Corpus json file', 'csv_file': 'Gensim LDA output archive file (a big gensim lda model is stored in seperate files, ms2lda website requires a tarball file with all those files)', } fields = [ 'name', 'description', 'ms2_file', 'csv_file', 'featureset' ] exclude = ('status', 'experiment_type')
unknown
codeparrot/codeparrot-clean
package kotlinx.coroutines.rx3 import io.reactivex.rxjava3.core.* import kotlinx.coroutines.flow.* import org.junit.* import org.reactivestreams.* import org.reactivestreams.tck.* class IterableFlowAsFlowableTckTest : PublisherVerification<Long>(TestEnvironment()) { private fun generate(num: Long): Array<Long> { return Array(if (num >= Integer.MAX_VALUE) 1000000 else num.toInt()) { it.toLong() } } override fun createPublisher(elements: Long): Flowable<Long> { return generate(elements).asIterable().asFlow().asFlowable() } override fun createFailedPublisher(): Publisher<Long>? = null @Ignore override fun required_spec309_requestZeroMustSignalIllegalArgumentException() { } @Ignore override fun required_spec309_requestNegativeNumberMustSignalIllegalArgumentException() { } @Ignore override fun required_spec312_cancelMustMakeThePublisherToEventuallyStopSignaling() { // } }
kotlin
github
https://github.com/Kotlin/kotlinx.coroutines
reactive/kotlinx-coroutines-rx3/test/IterableFlowAsFlowableTckTest.kt
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the "Elastic License * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side * Public License v 1"; you may not use this file except in compliance with, at * your election, the "Elastic License 2.0", the "GNU Affero General Public * License v3.0 only", or the "Server Side Public License, v 1". */ package org.elasticsearch.gradle.internal.test; import org.gradle.api.internal.tasks.testing.logging.FullExceptionFormatter; import org.gradle.api.internal.tasks.testing.logging.TestExceptionFormatter; import org.gradle.api.logging.Logger; import org.gradle.api.tasks.testing.Test; import org.gradle.api.tasks.testing.TestDescriptor; import org.gradle.api.tasks.testing.TestListener; import org.gradle.api.tasks.testing.TestOutputEvent; import org.gradle.api.tasks.testing.TestOutputListener; import org.gradle.api.tasks.testing.TestResult; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.UncheckedIOException; import java.io.Writer; import java.util.Deque; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public class ErrorReportingTestListener implements TestOutputListener, TestListener { private static final String REPRODUCE_WITH_PREFIX = "REPRODUCE WITH"; private final TestExceptionFormatter formatter; private final File outputDirectory; private final Logger taskLogger; private Map<Descriptor, EventWriter> eventWriters = new ConcurrentHashMap<>(); private Map<Descriptor, Deque<String>> reproductionLines = new ConcurrentHashMap<>(); private Set<Descriptor> failedTests = new LinkedHashSet<>(); private boolean dumpOutputOnFailure = true; public ErrorReportingTestListener(Test testTask, File outputDirectory) { this.formatter = new FullExceptionFormatter(testTask.getTestLogging()); this.taskLogger = testTask.getLogger(); this.outputDirectory = outputDirectory; } public void setDumpOutputOnFailure(boolean dumpOutputOnFailure) { this.dumpOutputOnFailure = dumpOutputOnFailure; } @Override public void onOutput(TestDescriptor testDescriptor, TestOutputEvent outputEvent) { TestDescriptor suite = testDescriptor.getParent(); // Check if this is output from the test suite itself (e.g. afterTest or beforeTest) if (testDescriptor.isComposite()) { suite = testDescriptor; } // Hold on to any repro messages so we can report them immediately on test case failure if (outputEvent.getMessage().startsWith(REPRODUCE_WITH_PREFIX)) { Deque<String> lines = reproductionLines.computeIfAbsent(Descriptor.of(suite), d -> new LinkedList<>()); lines.add(outputEvent.getMessage()); } EventWriter eventWriter = eventWriters.computeIfAbsent(Descriptor.of(suite), EventWriter::new); eventWriter.write(outputEvent); } @Override public void beforeSuite(TestDescriptor suite) { } @Override public void afterSuite(final TestDescriptor suite, TestResult result) { Descriptor descriptor = Descriptor.of(suite); try { if (dumpOutputOnFailure) { // if the test suite failed, report all captured output if (result.getResultType().equals(TestResult.ResultType.FAILURE)) { EventWriter eventWriter = eventWriters.get(descriptor); if (eventWriter != null) { // It's not explicit what the threading guarantees are for TestListener method execution so we'll // be explicitly safe here to avoid interleaving output from multiple test suites synchronized (this) { // make sure we've flushed everything to disk before reading eventWriter.flush(); System.err.println("\n\nSuite: " + suite); try (BufferedReader reader = eventWriter.reader()) { PrintStream out = System.out; for (String message = reader.readLine(); message != null; message = reader.readLine()) { if (message.startsWith(" 1> ")) { out = System.out; } else if (message.startsWith(" 2> ")) { out = System.err; } out.println(message); } } } } } } if (suite.getParent() == null) { // per test task top level gradle test run suite finished if (getFailedTests().size() > 0) { taskLogger.lifecycle("\nTests with failures:"); for (ErrorReportingTestListener.Descriptor failure : getFailedTests()) { taskLogger.lifecycle(" - " + failure.getFullName()); } } } } catch (IOException e) { throw new UncheckedIOException("Error reading test suite output", e); } finally { reproductionLines.remove(descriptor); EventWriter writer = eventWriters.remove(descriptor); if (writer != null) { try { writer.close(); } catch (IOException e) { taskLogger.error("Failed to close test suite output stream", e); } } } } @Override public void beforeTest(TestDescriptor testDescriptor) { } @Override public void afterTest(TestDescriptor testDescriptor, TestResult result) { if (result.getResultType() == TestResult.ResultType.FAILURE) { failedTests.add(Descriptor.of(testDescriptor)); if (testDescriptor.getParent() != null) { // go back and fetch the reproduction line for this test failure Deque<String> lines = reproductionLines.get(Descriptor.of(testDescriptor.getParent())); if (lines != null) { String line = lines.getLast(); if (line != null) { System.err.print('\n' + line); } } // include test failure exception stacktraces in test suite output log if (result.getExceptions().size() > 0) { String message = formatter.format(testDescriptor, result.getExceptions()).substring(4); EventWriter eventWriter = eventWriters.computeIfAbsent(Descriptor.of(testDescriptor.getParent()), EventWriter::new); eventWriter.write(new TestOutputEvent() { @Override public Destination getDestination() { return Destination.StdErr; } @Override public long getLogTime() { return result.getEndTime(); } @Override public String getMessage() { return message; } }); } } } } public Set<Descriptor> getFailedTests() { return failedTests; } /** * Class for identifying test output sources. We use this rather than Gradle's {@link TestDescriptor} as we want * to avoid any nasty memory leak issues that come from keeping Gradle implementation types in memory. Since we * use this a the key for our HashMap, it's best to control the implementation as there's no guarantee that Gradle's * various {@link TestDescriptor} implementations reliably implement equals and hashCode. */ public record Descriptor(String name, String className, String parent) { public static Descriptor of(TestDescriptor d) { return new Descriptor(d.getName(), d.getClassName(), d.getParent() == null ? null : d.getParent().toString()); } public String getFullName() { return className + "." + name; } } private class EventWriter implements Closeable { private final File outputFile; private final Writer writer; EventWriter(Descriptor descriptor) { this.outputFile = new File(outputDirectory, descriptor.className() + ".out"); FileOutputStream fos; try { fos = new FileOutputStream(this.outputFile); } catch (IOException e) { throw new UncheckedIOException("Unable to create test suite output file", e); } this.writer = new PrintWriter(new BufferedOutputStream(fos)); } public void write(TestOutputEvent event) { String prefix; if (event.getDestination() == TestOutputEvent.Destination.StdOut) { prefix = " 1> "; } else { prefix = " 2> "; } try { if (event.getMessage().equals("\n")) { writer.write(event.getMessage()); } else { writer.write(prefix + event.getMessage()); } } catch (IOException e) { throw new UncheckedIOException("Unable to write test suite output", e); } } public void flush() throws IOException { writer.flush(); } public BufferedReader reader() { try { return new BufferedReader(new FileReader(outputFile)); } catch (IOException e) { throw new UncheckedIOException("Unable to read test suite output file", e); } } @Override public void close() throws IOException { writer.close(); // there's no need to keep this stuff on disk after suite execution outputFile.delete(); } } }
java
github
https://github.com/elastic/elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/ErrorReportingTestListener.java
from django.conf.urls import url from django.contrib.auth.decorators import login_required from django.views import generic from oscar.core.application import Application from oscar.core.loading import get_class class CustomerApplication(Application): name = 'customer' summary_view = get_class('customer.views', 'AccountSummaryView') order_history_view = get_class('customer.views', 'OrderHistoryView') order_detail_view = get_class('customer.views', 'OrderDetailView') anon_order_detail_view = get_class('customer.views', 'AnonymousOrderDetailView') order_line_view = get_class('customer.views', 'OrderLineView') address_list_view = get_class('customer.views', 'AddressListView') address_create_view = get_class('customer.views', 'AddressCreateView') address_update_view = get_class('customer.views', 'AddressUpdateView') address_delete_view = get_class('customer.views', 'AddressDeleteView') address_change_status_view = get_class('customer.views', 'AddressChangeStatusView') email_list_view = get_class('customer.views', 'EmailHistoryView') email_detail_view = get_class('customer.views', 'EmailDetailView') login_view = get_class('customer.views', 'AccountAuthView') logout_view = get_class('customer.views', 'LogoutView') register_view = get_class('customer.views', 'AccountRegistrationView') profile_view = get_class('customer.views', 'ProfileView') profile_update_view = get_class('customer.views', 'ProfileUpdateView') profile_delete_view = get_class('customer.views', 'ProfileDeleteView') change_password_view = get_class('customer.views', 'ChangePasswordView') notification_inbox_view = get_class('customer.notifications.views', 'InboxView') notification_archive_view = get_class('customer.notifications.views', 'ArchiveView') notification_update_view = get_class('customer.notifications.views', 'UpdateView') notification_detail_view = get_class('customer.notifications.views', 'DetailView') alert_list_view = get_class('customer.alerts.views', 'ProductAlertListView') alert_create_view = get_class('customer.alerts.views', 'ProductAlertCreateView') alert_confirm_view = get_class('customer.alerts.views', 'ProductAlertConfirmView') alert_cancel_view = get_class('customer.alerts.views', 'ProductAlertCancelView') wishlists_add_product_view = get_class('customer.wishlists.views', 'WishListAddProduct') wishlists_list_view = get_class('customer.wishlists.views', 'WishListListView') wishlists_detail_view = get_class('customer.wishlists.views', 'WishListDetailView') wishlists_create_view = get_class('customer.wishlists.views', 'WishListCreateView') wishlists_create_with_product_view = get_class('customer.wishlists.views', 'WishListCreateView') wishlists_update_view = get_class('customer.wishlists.views', 'WishListUpdateView') wishlists_delete_view = get_class('customer.wishlists.views', 'WishListDeleteView') wishlists_remove_product_view = get_class('customer.wishlists.views', 'WishListRemoveProduct') wishlists_move_product_to_another_view = get_class( 'customer.wishlists.views', 'WishListMoveProductToAnotherWishList') def get_urls(self): urls = [ # Login, logout and register doesn't require login url(r'^login/$', self.login_view.as_view(), name='login'), url(r'^logout/$', self.logout_view.as_view(), name='logout'), url(r'^register/$', self.register_view.as_view(), name='register'), url(r'^$', login_required(self.summary_view.as_view()), name='summary'), url(r'^change-password/$', login_required(self.change_password_view.as_view()), name='change-password'), # Profile url(r'^profile/$', login_required(self.profile_view.as_view()), name='profile-view'), url(r'^profile/edit/$', login_required(self.profile_update_view.as_view()), name='profile-update'), url(r'^profile/delete/$', login_required(self.profile_delete_view.as_view()), name='profile-delete'), # Order history url(r'^orders/$', login_required(self.order_history_view.as_view()), name='order-list'), url(r'^order-status/(?P<order_number>[\w-]*)/(?P<hash>\w+)/$', self.anon_order_detail_view.as_view(), name='anon-order'), url(r'^orders/(?P<order_number>[\w-]*)/$', login_required(self.order_detail_view.as_view()), name='order'), url(r'^orders/(?P<order_number>[\w-]*)/(?P<line_id>\d+)$', login_required(self.order_line_view.as_view()), name='order-line'), # Address book url(r'^addresses/$', login_required(self.address_list_view.as_view()), name='address-list'), url(r'^addresses/add/$', login_required(self.address_create_view.as_view()), name='address-create'), url(r'^addresses/(?P<pk>\d+)/$', login_required(self.address_update_view.as_view()), name='address-detail'), url(r'^addresses/(?P<pk>\d+)/delete/$', login_required(self.address_delete_view.as_view()), name='address-delete'), url(r'^addresses/(?P<pk>\d+)/' r'(?P<action>default_for_(billing|shipping))/$', login_required(self.address_change_status_view.as_view()), name='address-change-status'), # Email history url(r'^emails/$', login_required(self.email_list_view.as_view()), name='email-list'), url(r'^emails/(?P<email_id>\d+)/$', login_required(self.email_detail_view.as_view()), name='email-detail'), # Notifications # Redirect to notification inbox url(r'^notifications/$', generic.RedirectView.as_view( url='/accounts/notifications/inbox/')), url(r'^notifications/inbox/$', login_required(self.notification_inbox_view.as_view()), name='notifications-inbox'), url(r'^notifications/archive/$', login_required(self.notification_archive_view.as_view()), name='notifications-archive'), url(r'^notifications/update/$', login_required(self.notification_update_view.as_view()), name='notifications-update'), url(r'^notifications/(?P<pk>\d+)/$', login_required(self.notification_detail_view.as_view()), name='notifications-detail'), # Alerts # Alerts can be setup by anonymous users: some views do not # require login url(r'^alerts/$', login_required(self.alert_list_view.as_view()), name='alerts-list'), url(r'^alerts/create/(?P<pk>\d+)/$', self.alert_create_view.as_view(), name='alert-create'), url(r'^alerts/confirm/(?P<key>[a-z0-9]+)/$', self.alert_confirm_view.as_view(), name='alerts-confirm'), url(r'^alerts/cancel/key/(?P<key>[a-z0-9]+)/$', self.alert_cancel_view.as_view(), name='alerts-cancel-by-key'), url(r'^alerts/cancel/(?P<pk>[a-z0-9]+)/$', login_required(self.alert_cancel_view.as_view()), name='alerts-cancel-by-pk'), # Wishlists url(r'wishlists/$', login_required(self.wishlists_list_view.as_view()), name='wishlists-list'), url(r'wishlists/add/(?P<product_pk>\d+)/$', login_required(self.wishlists_add_product_view.as_view()), name='wishlists-add-product'), url(r'wishlists/(?P<key>[a-z0-9]+)/add/(?P<product_pk>\d+)/', login_required(self.wishlists_add_product_view.as_view()), name='wishlists-add-product'), url(r'wishlists/create/$', login_required(self.wishlists_create_view.as_view()), name='wishlists-create'), url(r'wishlists/create/with-product/(?P<product_pk>\d+)/$', login_required(self.wishlists_create_view.as_view()), name='wishlists-create-with-product'), # Wishlists can be publicly shared, no login required url(r'wishlists/(?P<key>[a-z0-9]+)/$', self.wishlists_detail_view.as_view(), name='wishlists-detail'), url(r'wishlists/(?P<key>[a-z0-9]+)/update/$', login_required(self.wishlists_update_view.as_view()), name='wishlists-update'), url(r'wishlists/(?P<key>[a-z0-9]+)/delete/$', login_required(self.wishlists_delete_view.as_view()), name='wishlists-delete'), url(r'wishlists/(?P<key>[a-z0-9]+)/lines/(?P<line_pk>\d+)/delete/', login_required(self.wishlists_remove_product_view.as_view()), name='wishlists-remove-product'), url(r'wishlists/(?P<key>[a-z0-9]+)/products/(?P<product_pk>\d+)/' r'delete/', login_required(self.wishlists_remove_product_view.as_view()), name='wishlists-remove-product'), url(r'wishlists/(?P<key>[a-z0-9]+)/lines/(?P<line_pk>\d+)/move-to/' r'(?P<to_key>[a-z0-9]+)/$', login_required(self.wishlists_move_product_to_another_view .as_view()), name='wishlists-move-product-to-another')] return self.post_process_urls(urls) application = CustomerApplication()
unknown
codeparrot/codeparrot-clean
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2014, Blue Box Group, Inc. # Copyright 2014, Craig Tracey <craigtracey@gmail.com> # # 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 os import traceback def main(): module = AnsibleModule( argument_spec=dict( service=dict(default=None, required=True), short_service_name=dict(required=False), warn_over=dict(default=15, required=False), crit_over=dict(default=30, required=False), interval=dict(default=30, required=False), occurrences=dict(default=2, required=False), plugin_dir=dict(default='/etc/sensu/plugins', required=False), check_dir=dict(default='/etc/sensu/conf.d/checks', required=False), state=dict(default='present', required=False, choices=['present','absent']) ) ) if module.params['state'] == 'present': try: changed = False if not module.params['short_service_name']: short_service_name = os.path.basename(module.params['service']) check_path = "%s/%s-service.json" % ( module.params['check_dir'], short_service_name) command = "%s/check-procs.rb -p %s -w %s -c %s -W 1 -C 1" % (module.params['plugin_dir'], module.params['service'], module.params['warn_over'], module.params['crit_over'] ) notification = "unexpected number of %s processes" % ( module.params['service'] ) check=dict({ 'checks': { short_service_name: { 'command': command, 'standalone': True, 'handlers': [ 'default' ], 'interval': int(module.params['interval']), 'notification': notification, 'occurrences': int(module.params['occurrences']) } } }) if os.path.isfile(check_path): with open(check_path) as fh: if json.load(fh) == check: module.exit_json(changed=False, result="ok") else: with open(check_path, "w") as fh: fh.write(json.dumps(check, indent=4)) module.exit_json(changed=True, result="changed") else: with open(check_path, "w") as fh: fh.write(json.dumps(check, indent=4)) module.exit_json(changed=True, result="created") except Exception as e: formatted_lines = traceback.format_exc() module.fail_json(msg="creating the check failed: %s %s" % (e,formatted_lines)) else: try: changed = False if not module.params['short_service_name']: short_service_name = os.path.basename(module.params['service']) check_path = '%s/%s-service.json' % (module.params['check_dir'], short_service_name) if os.path.isfile(check_path): os.remove(check_path) module.exit_json(changed=True, result="changed") else: module.exit_json(changed=False, result="ok") except Exception as e: formatted_lines = traceback.format_exc() module.fail_json(msg="removing the check failed: %s %s" % (e,formatted_lines)) # this is magic, see lib/ansible/module_common.py from ansible.module_utils.basic import * main()
unknown
codeparrot/codeparrot-clean
# postgresql/pypostgresql.py # Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Support for the PostgreSQL database via py-postgresql. Connecting ---------- URLs are of the form ``postgresql+pypostgresql://user:password@host:port/dbname[?key=value&key=value...]``. """ from sqlalchemy import util from sqlalchemy import types as sqltypes from sqlalchemy.dialects.postgresql.base import PGDialect, PGExecutionContext from sqlalchemy import processors class PGNumeric(sqltypes.Numeric): def bind_processor(self, dialect): return processors.to_str def result_processor(self, dialect, coltype): if self.asdecimal: return None else: return processors.to_float class PGExecutionContext_pypostgresql(PGExecutionContext): pass class PGDialect_pypostgresql(PGDialect): driver = 'pypostgresql' supports_unicode_statements = True supports_unicode_binds = True description_encoding = None default_paramstyle = 'pyformat' # requires trunk version to support sane rowcounts # TODO: use dbapi version information to set this flag appropriately supports_sane_rowcount = True supports_sane_multi_rowcount = False execution_ctx_cls = PGExecutionContext_pypostgresql colspecs = util.update_copy( PGDialect.colspecs, { sqltypes.Numeric : PGNumeric, sqltypes.Float: sqltypes.Float, # prevents PGNumeric from being used } ) @classmethod def dbapi(cls): from postgresql.driver import dbapi20 return dbapi20 def create_connect_args(self, url): opts = url.translate_connect_args(username='user') if 'port' in opts: opts['port'] = int(opts['port']) else: opts['port'] = 5432 opts.update(url.query) return ([], opts) def is_disconnect(self, e, connection, cursor): return "connection is closed" in str(e) dialect = PGDialect_pypostgresql
unknown
codeparrot/codeparrot-clean
--- c: Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. SPDX-License-Identifier: curl Long: ssl-allow-beast Help: Allow security flaw to improve interop Protocols: TLS Added: 7.25.0 Category: tls Multi: boolean See-also: - proxy-ssl-allow-beast - insecure Example: - --ssl-allow-beast $URL --- # `--ssl-allow-beast` Do not work around a security flaw in the TLS1.0 protocol known as BEAST. If this option is not used, the TLS layer may use workarounds known to cause interoperability problems with some older server implementations. This option only changes how curl does TLS 1.0 and has no effect on later TLS versions. **WARNING**: this option loosens the TLS security, and by using this flag you ask for exactly that.
unknown
github
https://github.com/curl/curl
docs/cmdline-opts/ssl-allow-beast.md
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the "Elastic License * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side * Public License v 1"; you may not use this file except in compliance with, at * your election, the "Elastic License 2.0", the "GNU Affero General Public * License v3.0 only", or the "Server Side Public License, v 1". */ package org.elasticsearch.gradle.internal.test.rest.transform; import com.fasterxml.jackson.databind.node.ObjectNode; import javax.annotation.Nullable; /** * A type of {@link RestTestTransform} that transformations or adds a global "setup" section. */ public interface RestTestTransformGlobalSetup { /** * @param setupNodeParent The parent of an existing "setup" ObjectNode, null otherwise. If null implementations may create choose to * create the section. */ ObjectNode transformSetup(@Nullable ObjectNode setupNodeParent); }
java
github
https://github.com/elastic/elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/RestTestTransformGlobalSetup.java
#!/usr/bin/env python import os from icalendar import Calendar def get_ics(filename): return filename.endswith('ics') def check_if_correct_parse(ics_file): fh = open(ics_file, 'rb') try: # some calendars, such as Austrian ones have multiple # vCalendar entries - we probably don't want them to fail # parse. So we set multiple=True below cal_entries = Calendar.from_ical(fh.read(), multiple=True) if cal_entries is None: raise ValueError finally: fh.close() def run(*args): calendars_dir = os.path.join('media','caldata') ics_files = map(lambda x: os.path.join(calendars_dir, x), filter(get_ics, os.listdir(calendars_dir))) format_str = "Failed to parse the icalendar file: {}. {}" check_failed = False for f in ics_files: try: check_if_correct_parse(f) except ValueError as ve: check_failed = True print format_str.format(f, ve.message) if check_failed: # Returning a positive error code, since we have nothing to do # with these errors. They simply have to be reported back to # caldata maintainers. Also, we have to return something # other than zero - for travis to fail build over invalid files. # Please see: http://docs.travis-ci.com/user/build-lifecycle/ # """ # When any of the steps in the script stage fails with a non-zero # exit code, the build will be marked as failed. # """ exit(1) # vim: ts=4 sw=4 et ai
unknown
codeparrot/codeparrot-clean
import queue from random import choice from typing import Dict, List import random import json from bptc.data.event import Event, Parents from bptc.data.hashgraph import Hashgraph from bptc.data.transaction import MoneyTransaction, PublishNameTransaction from bptc.data.db import DB from bptc.protocols.push_protocol import PushClientFactory import time from datetime import datetime import threading from functools import partial from twisted.internet import reactor, threads from twisted.internet.address import IPv4Address import bptc from bptc.data.member import Member from bptc.protocols.push_protocol import PushServerFactory from bptc.protocols.pull_protocol import PullServerFactory class Network: """Provides the functionality needed for a member to interact with other members""" def __init__(self, hashgraph: Hashgraph, create_initial_event: bool = True): # The current hashgraph self.hashgraph = hashgraph # the thread that frequently pushes self.background_push_client_thread = None # the thread that processes the pushes from other members self.background_push_server_thread = PushingServerThread(self) self.background_push_server_thread.daemon = True self.background_push_server_thread.start() # Statistics self.last_push_sent = None self.last_push_received = None # Create first own event if create_initial_event: self.hashgraph.add_own_event(Event(self.hashgraph.me.verify_key, None, Parents(None, None)), True) @property def me(self): return self.hashgraph.me def reset(self): """Delete the hashgraph and create a new one.""" DB.reset() new_me = Member.create() new_me.address = IPv4Address("TCP", bptc.ip, bptc.port) new_hashgraph = Hashgraph(new_me) self.hashgraph = new_hashgraph self.hashgraph.add_own_event(Event(self.hashgraph.me.verify_key, None, Parents(None, None)), True) self.last_push_sent = None self.last_push_received = None def push_to(self, ip, port) -> None: """Push to the specified network address.""" with self.hashgraph.lock: data_string = self.generate_data_string(self.hashgraph.me, self.hashgraph.lookup_table, filter_members_with_address(self.hashgraph.known_members.values())) factory = PushClientFactory(data_string, network=self) def push(): reactor.connectTCP(ip, port, factory) threads.blockingCallFromThread(reactor, push) @staticmethod def generate_data_string(me, events, members): """Generates a string out of events and members for transferring it over the network.""" serialized_events = {} if events is not None: for event_id, event in events.items(): serialized_events[event_id] = event.to_dict() serialized_members = [] if members is not None: for member in members: if member.id is not me.verify_key: serialized_members.append(member.to_dict()) data_to_send = { 'from': { 'verify_key': me.verify_key, 'listening_port': me.address.port }, 'events': serialized_events, 'members': serialized_members } return json.dumps(data_to_send).encode('UTF-8') def push_to_member(self, member: Member, ignore_for_statistics=False) -> None: """Push to the specified member.""" bptc.logger.debug('Push to {}... ({}, {})'.format(member.verify_key[:6], member.address.host, member.address.port)) with self.hashgraph.lock: data_string = self.generate_data_string(self.hashgraph.me, self.hashgraph.get_unknown_events_of(member), filter_members_with_address(self.hashgraph.known_members.values())) if not ignore_for_statistics: factory = PushClientFactory(data_string, network=self, receiver=member) else: factory = PushClientFactory(data_string, network=None, receiver=member) def push(): if member.address is not None: reactor.connectTCP(member.address.host, member.address.port, factory) threads.blockingCallFromThread(reactor, push) def push_to_random(self) -> None: """ Pushes to a random, known member :return: None """ with self.hashgraph.lock: filtered_known_members = [m for key, m in self.hashgraph.known_members.items() if key != self.hashgraph.me.verify_key and m.address is not None and key not in self.hashgraph.fork_blacklist] if filtered_known_members: member = choice(filtered_known_members) self.push_to_member(member) else: bptc.logger.debug("I don't know any other members!") def send_transaction(self, amount: int, comment: str, receiver: Member) -> Event: """ Create a new event with a transaction :param amount: The amount of BBTC to send :param comment: The comment to be included in the transaction :param receiver: The receiver of the transaction :return: """ transaction = MoneyTransaction(receiver.to_verifykey_string(), amount, comment) with self.hashgraph.lock: event = Event(self.hashgraph.me.verify_key, [transaction], Parents(self.hashgraph.me.head, None)) self.hashgraph.add_own_event(event, True) return event def publish_name(self, name: str): """ Publishes a user's name on the hashgraph :param name: The user's name :return: """ transaction = PublishNameTransaction(name) with self.hashgraph.lock: event = Event(self.hashgraph.me.verify_key, [transaction], Parents(self.hashgraph.me.head, None)) self.hashgraph.add_own_event(event, True) return event def receive_data_string_callback(self, data_string, peer): """Turn a received data string over to the responsible thread.""" try: self.background_push_server_thread.q.put((data_string, peer), block=False) except: pass def process_data_string(self, data_string, peer): """Process a received data string.""" # Decode received JSON data try: received_data = json.loads(data_string) except: bptc.logger.warn("Could not parse JSON message") return # Ignore pushes from yourself (should only happen once after the client is started) if received_data['from']['verify_key'] == self.me.verify_key: return # Log self.last_push_received = datetime.now().isoformat() # Generate Member object from_member_id = received_data['from']['verify_key'] from_member_listening_port = int(received_data['from']['listening_port']) from_member = Member(from_member_id, None) from_member.address = peer from_member.address.port = from_member_listening_port # Check if the sender sent any events s_events = received_data['events'] if len(s_events) > 0: events = {} for event_id, dict_event in s_events.items(): events[event_id] = Event.from_dict(dict_event) bptc.logger.debug('- Received {} events'.format(len(events.items()))) self.process_events(from_member, events) # Check if the sender sent any members s_members = received_data['members'] if len(s_members) > 0: members = [Member.from_dict(m) for m in s_members] bptc.logger.debug('- Received {} members'.format(len(members))) self.receive_members_callback(members) def process_events(self, from_member: Member, events: Dict[str, Event]) -> None: """ Used as a callback when events are received from the outside :param from_member: The member from which the events were received :param events: The list of events :return: None """ # Store/Update member with self.hashgraph.lock: if from_member.id in self.hashgraph.known_members: self.hashgraph.known_members[from_member.id].address = from_member.address from_member = self.hashgraph.known_members[from_member.id] else: self.hashgraph.known_members[from_member.id] = from_member # Let the hashgraph process the events self.hashgraph.process_events(from_member, events) def receive_members_callback(self, members: List[Member]) -> None: """ Used as a callback when member are received from the outside :param members: The ist of members :return: None """ with self.hashgraph.lock: for member in members: if member.id not in self.hashgraph.known_members: self.hashgraph.known_members[member.id] = member elif self.hashgraph.known_members[member.id].address is None: self.hashgraph.known_members[member.id].address = member.address def start_push_thread(self) -> None: """Start the thread responsible for frequent pushing.""" self.background_push_client_thread = PushingClientThread(self) self.background_push_client_thread.daemon = True self.background_push_client_thread.start() def stop_push_thread(self) -> None: """Stop the thread responsible for frequent pushing.""" self.background_push_client_thread.stop() class PushingClientThread(threading.Thread): """Thread responsible for frequent pushing to random members.""" def __init__(self, network): super(PushingClientThread, self).__init__() self.network = network self._stop_event = threading.Event() def run(self): while not self.stopped(): self.network.push_to_random() time.sleep(max(random.normalvariate(bptc.push_waiting_time_mu, bptc.push_waiting_time_sigma), 0)) def stop(self): self._stop_event.set() def stopped(self): return self._stop_event.is_set() class PushingServerThread(threading.Thread): """Thread responsible for processing the received pushes.""" def __init__(self, network): super(PushingServerThread, self).__init__() self.network = network self._stop_event = threading.Event() self.q = queue.Queue(maxsize=1) def run(self): while not self.stopped(): (data_string, peer) = self.q.get() self.network.process_data_string(data_string, peer) self.q.task_done() def stop(self): self._stop_event.set() def stopped(self): return self._stop_event.is_set() class BootstrapPushThread(threading.Thread): """Thread used for initial pushing to a specified network address until someone pushes back and other members are known.""" def __init__(self, ip, port, network): threading.Thread.__init__(self) self.ip = ip self.port = port self.network = network def run(self): while len(self.network.hashgraph.known_members) == 1: self.network.push_to(self.ip, int(self.port)) time.sleep(2) def filter_members_with_address(members: List[Member]) -> List[Member]: """ Filters a list of members, only returning those who have a known network address :param members: The list of members to be filtered :return: The filtered lise """ return [m for m in members if m.address is not None] def start_reactor_thread(): """Start twisted's reactor in a separate thread.""" thread = threading.Thread(target=partial(reactor.run, installSignalHandlers=0)) thread.daemon = True thread.start() def stop_reactor_thread(): """Stop twisted's reactor.""" reactor.callFromThread(reactor.stop) def start_listening(network, listening_ip, listening_port, allow_reset_signal): """Makes twisted's reactor listen for pushes and pulls""" bptc.logger.info("Push server listens on port {}".format(listening_port)) push_server_factory = PushServerFactory(network.receive_data_string_callback, allow_reset_signal, network) reactor.listenTCP(interface=listening_ip, port=int(listening_port), factory=push_server_factory) bptc.logger.info("[Pull server (for viz tool) listens on port {}]".format(int(listening_port) + 1)) pull_server_factory = PullServerFactory(network.hashgraph.me.id, network.hashgraph) reactor.listenTCP(interface=listening_ip, port=int(listening_port) + 1, factory=pull_server_factory) # Push to yourself (is ignored when received) # This is a workaround for bug on some systems where the reactor ignores incoming connections until it # had at least one outgoing connection network.push_to_member(network.hashgraph.me, True)
unknown
codeparrot/codeparrot-clean
""" Helper functions for mapping model fields to a dictionary of default keyword arguments that should be used for their equivelent serializer fields. """ import inspect from django.core import validators from django.db import models from django.utils.text import capfirst from rest_framework.compat import clean_manytomany_helptext from rest_framework.validators import UniqueValidator NUMERIC_FIELD_TYPES = ( models.IntegerField, models.FloatField, models.DecimalField ) class ClassLookupDict(object): """ Takes a dictionary with classes as keys. Lookups against this object will traverses the object's inheritance hierarchy in method resolution order, and returns the first matching value from the dictionary or raises a KeyError if nothing matches. """ def __init__(self, mapping): self.mapping = mapping def __getitem__(self, key): if hasattr(key, '_proxy_class'): # Deal with proxy classes. Ie. BoundField behaves as if it # is a Field instance when using ClassLookupDict. base_class = key._proxy_class else: base_class = key.__class__ for cls in inspect.getmro(base_class): if cls in self.mapping: return self.mapping[cls] raise KeyError('Class %s not found in lookup.' % base_class.__name__) def __setitem__(self, key, value): self.mapping[key] = value def needs_label(model_field, field_name): """ Returns `True` if the label based on the model's verbose name is not equal to the default label it would have based on it's field name. """ default_label = field_name.replace('_', ' ').capitalize() return capfirst(model_field.verbose_name) != default_label def get_detail_view_name(model): """ Given a model class, return the view name to use for URL relationships that refer to instances of the model. """ return '%(model_name)s-detail' % { 'app_label': model._meta.app_label, 'model_name': model._meta.object_name.lower() } def get_field_kwargs(field_name, model_field): """ Creates a default instance of a basic non-relational field. """ kwargs = {} validator_kwarg = list(model_field.validators) # The following will only be used by ModelField classes. # Gets removed for everything else. kwargs['model_field'] = model_field if model_field.verbose_name and needs_label(model_field, field_name): kwargs['label'] = capfirst(model_field.verbose_name) if model_field.help_text: kwargs['help_text'] = model_field.help_text max_digits = getattr(model_field, 'max_digits', None) if max_digits is not None: kwargs['max_digits'] = max_digits decimal_places = getattr(model_field, 'decimal_places', None) if decimal_places is not None: kwargs['decimal_places'] = decimal_places if isinstance(model_field, models.TextField): kwargs['style'] = {'base_template': 'textarea.html'} if isinstance(model_field, models.AutoField) or not model_field.editable: # If this field is read-only, then return early. # Further keyword arguments are not valid. kwargs['read_only'] = True return kwargs if model_field.has_default() or model_field.blank or model_field.null: kwargs['required'] = False if model_field.null and not isinstance(model_field, models.NullBooleanField): kwargs['allow_null'] = True if model_field.blank and (isinstance(model_field, models.CharField) or isinstance(model_field, models.TextField)): kwargs['allow_blank'] = True if model_field.choices: # If this model field contains choices, then return early. # Further keyword arguments are not valid. kwargs['choices'] = model_field.choices return kwargs # Ensure that max_length is passed explicitly as a keyword arg, # rather than as a validator. max_length = getattr(model_field, 'max_length', None) if max_length is not None and isinstance(model_field, models.CharField): kwargs['max_length'] = max_length validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.MaxLengthValidator) ] # Ensure that min_length is passed explicitly as a keyword arg, # rather than as a validator. min_length = next(( validator.limit_value for validator in validator_kwarg if isinstance(validator, validators.MinLengthValidator) ), None) if min_length is not None and isinstance(model_field, models.CharField): kwargs['min_length'] = min_length validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.MinLengthValidator) ] # Ensure that max_value is passed explicitly as a keyword arg, # rather than as a validator. max_value = next(( validator.limit_value for validator in validator_kwarg if isinstance(validator, validators.MaxValueValidator) ), None) if max_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES): kwargs['max_value'] = max_value validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.MaxValueValidator) ] # Ensure that max_value is passed explicitly as a keyword arg, # rather than as a validator. min_value = next(( validator.limit_value for validator in validator_kwarg if isinstance(validator, validators.MinValueValidator) ), None) if min_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES): kwargs['min_value'] = min_value validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.MinValueValidator) ] # URLField does not need to include the URLValidator argument, # as it is explicitly added in. if isinstance(model_field, models.URLField): validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.URLValidator) ] # EmailField does not need to include the validate_email argument, # as it is explicitly added in. if isinstance(model_field, models.EmailField): validator_kwarg = [ validator for validator in validator_kwarg if validator is not validators.validate_email ] # SlugField do not need to include the 'validate_slug' argument, if isinstance(model_field, models.SlugField): validator_kwarg = [ validator for validator in validator_kwarg if validator is not validators.validate_slug ] # IPAddressField do not need to include the 'validate_ipv46_address' argument, if isinstance(model_field, models.GenericIPAddressField): validator_kwarg = [ validator for validator in validator_kwarg if validator is not validators.validate_ipv46_address ] if getattr(model_field, 'unique', False): validator = UniqueValidator(queryset=model_field.model._default_manager) validator_kwarg.append(validator) if validator_kwarg: kwargs['validators'] = validator_kwarg return kwargs def get_relation_kwargs(field_name, relation_info): """ Creates a default instance of a flat relational field. """ model_field, related_model, to_many, has_through_model = relation_info kwargs = { 'queryset': related_model._default_manager, 'view_name': get_detail_view_name(related_model) } if to_many: kwargs['many'] = True if has_through_model: kwargs['read_only'] = True kwargs.pop('queryset', None) if model_field: if model_field.verbose_name and needs_label(model_field, field_name): kwargs['label'] = capfirst(model_field.verbose_name) help_text = clean_manytomany_helptext(model_field.help_text) if help_text: kwargs['help_text'] = help_text if not model_field.editable: kwargs['read_only'] = True kwargs.pop('queryset', None) if kwargs.get('read_only', False): # If this field is read-only, then return early. # No further keyword arguments are valid. return kwargs if model_field.has_default() or model_field.blank or model_field.null: kwargs['required'] = False if model_field.null: kwargs['allow_null'] = True if model_field.validators: kwargs['validators'] = model_field.validators if getattr(model_field, 'unique', False): validator = UniqueValidator(queryset=model_field.model._default_manager) kwargs['validators'] = kwargs.get('validators', []) + [validator] if to_many and not model_field.blank: kwargs['allow_empty'] = False return kwargs def get_nested_relation_kwargs(relation_info): kwargs = {'read_only': True} if relation_info.to_many: kwargs['many'] = True return kwargs def get_url_kwargs(model_field): return { 'view_name': get_detail_view_name(model_field) }
unknown
codeparrot/codeparrot-clean
# encoding: utf-8 """ server.py Created by Thomas Mangin on 2011-11-30. Copyright (c) 2011-2013 Exa Networks. All rights reserved. """ # http://code.google.com/speed/articles/web-metrics.html # http://itamarst.org/writings/pycon05/fast.html from .functions import listen from .functions import listen_intercept import socket from exaproxy.util.log.logger import Logger from exaproxy.configuration import load configuration = load() class Server(object): _listen = staticmethod(listen) def __init__(self, name, poller, read_name, config): self.socks = {} self.name = name self.poller = poller self.read_name = read_name self.max_clients = config.connections self.client_count = 0 self.saturated = False # we are receiving more connections than we can handle self.binding = set() self.log = Logger('server', configuration.log.server) self.serving = config.enable # We are currenrly listening if self.serving: self.log.info('server [%s] accepting up to %d clients' % (name, self.max_clients)) def accepting (self): if self.serving: return True for ip, port, timeout, backlog in self.binding: try: self.log.critical('re-listening on %s:%d' % (ip,port)) self.listen(ip,port,timeout,backlog) except socket.error,e: self.log.critical('could not re-listen on %s:%d : %s' % (ip,port,str(e))) return False self.serving = True return True def rejecting (self): if self.serving: for sock,(ip,port) in self.socks.items(): self.log.critical('stop listening on %s:%d' % (ip,port)) self.poller.removeReadSocket(self.read_name,sock) sock.close() self.socks = {} self.serving = False def saturation (self): if not self.saturated: return self.saturated = False self.log.error('we received more %s connections that we could handle' % self.name) self.log.error('we current have %s client(s) out of a maximum of %s' % (self.client_count, self.max_clients)) def listen(self, ip, port, timeout, backlog): s = self._listen(ip, port,timeout,backlog) if s: self.binding.add((ip,port,timeout,backlog)) self.socks[s] = (ip,port) # register the socket with the poller if self.client_count < self.max_clients: self.poller.addReadSocket(self.read_name, s) return s def accept(self, sock): try: # should we check to make sure it's a socket we provided s, (ip,port) = sock.accept() s.setblocking(0) # NOTE: we really should try to handle the entire queue at once yield s, ip except socket.error, e: # It doesn't really matter if accept fails temporarily. We will # try again next loop self.log.debug('%s could not accept a new connection %s' % (self.name,str(e))) else: self.client_count += 1 finally: if self.client_count >= self.max_clients: self.saturated = True for listening_sock in self.socks: self.poller.removeReadSocket(self.read_name, listening_sock) def notifyClose (self, client, count=1): paused = self.client_count >= self.max_clients self.client_count -= count if paused and self.client_count < self.max_clients: for listening_sock in self.socks: self.poller.addReadSocket(self.read_name, listening_sock) def stop(self): for sock in self.socks: try: sock.close() except socket.error: pass self.socks = {} self.poller.clearRead(self.read_name) class InterceptServer (Server): _listen = staticmethod(listen_intercept)
unknown
codeparrot/codeparrot-clean
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {Result} from '../Utils/Result'; import {CompilerDiagnostic, CompilerError, Effect} from '..'; import {ErrorCategory} from '../CompilerError'; import { BlockId, FunctionExpression, HIRFunction, IdentifierId, isSetStateType, isUseEffectHookType, Place, CallExpression, Instruction, isUseStateType, BasicBlock, isUseRefType, SourceLocation, ArrayExpression, } from '../HIR'; import {eachInstructionLValue, eachInstructionOperand} from '../HIR/visitors'; import {isMutable} from '../ReactiveScopes/InferReactiveScopeVariables'; import {assertExhaustive} from '../Utils/utils'; type TypeOfValue = 'ignored' | 'fromProps' | 'fromState' | 'fromPropsAndState'; type DerivationMetadata = { typeOfValue: TypeOfValue; place: Place; sourcesIds: Set<IdentifierId>; isStateSource: boolean; }; type EffectMetadata = { effect: HIRFunction; dependencies: ArrayExpression; }; type ValidationContext = { readonly functions: Map<IdentifierId, FunctionExpression>; readonly candidateDependencies: Map<IdentifierId, ArrayExpression>; readonly errors: CompilerError; readonly derivationCache: DerivationCache; readonly effectsCache: Map<IdentifierId, EffectMetadata>; readonly setStateLoads: Map<IdentifierId, IdentifierId | null>; readonly setStateUsages: Map<IdentifierId, Set<SourceLocation>>; }; const MAX_FIXPOINT_ITERATIONS = 100; class DerivationCache { hasChanges: boolean = false; cache: Map<IdentifierId, DerivationMetadata> = new Map(); private previousCache: Map<IdentifierId, DerivationMetadata> | null = null; takeSnapshot(): void { this.previousCache = new Map(); for (const [key, value] of this.cache.entries()) { this.previousCache.set(key, { place: value.place, sourcesIds: new Set(value.sourcesIds), typeOfValue: value.typeOfValue, isStateSource: value.isStateSource, }); } } checkForChanges(): void { if (this.previousCache === null) { this.hasChanges = true; return; } for (const [key, value] of this.cache.entries()) { const previousValue = this.previousCache.get(key); if ( previousValue === undefined || !this.isDerivationEqual(previousValue, value) ) { this.hasChanges = true; return; } } if (this.cache.size !== this.previousCache.size) { this.hasChanges = true; return; } this.hasChanges = false; } snapshot(): boolean { const hasChanges = this.hasChanges; this.hasChanges = false; return hasChanges; } addDerivationEntry( derivedVar: Place, sourcesIds: Set<IdentifierId>, typeOfValue: TypeOfValue, isStateSource: boolean, ): void { let finalIsSource = isStateSource; if (!finalIsSource) { for (const sourceId of sourcesIds) { const sourceMetadata = this.cache.get(sourceId); if ( sourceMetadata?.isStateSource && sourceMetadata.place.identifier.name?.kind !== 'named' ) { finalIsSource = true; break; } } } this.cache.set(derivedVar.identifier.id, { place: derivedVar, sourcesIds: sourcesIds, typeOfValue: typeOfValue ?? 'ignored', isStateSource: finalIsSource, }); } private isDerivationEqual( a: DerivationMetadata, b: DerivationMetadata, ): boolean { if (a.typeOfValue !== b.typeOfValue) { return false; } if (a.sourcesIds.size !== b.sourcesIds.size) { return false; } for (const id of a.sourcesIds) { if (!b.sourcesIds.has(id)) { return false; } } return true; } } function isNamedIdentifier(place: Place): place is Place & { identifier: {name: NonNullable<Place['identifier']['name']>}; } { return ( place.identifier.name !== null && place.identifier.name.kind === 'named' ); } /** * Validates that useEffect is not used for derived computations which could/should * be performed in render. * * See https://react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state * * Example: * * ``` * // 🔴 Avoid: redundant state and unnecessary Effect * const [fullName, setFullName] = useState(''); * useEffect(() => { * setFullName(firstName + ' ' + lastName); * }, [firstName, lastName]); * ``` * * Instead use: * * ``` * // ✅ Good: calculated during rendering * const fullName = firstName + ' ' + lastName; * ``` */ export function validateNoDerivedComputationsInEffects_exp( fn: HIRFunction, ): Result<void, CompilerError> { const functions: Map<IdentifierId, FunctionExpression> = new Map(); const candidateDependencies: Map<IdentifierId, ArrayExpression> = new Map(); const derivationCache = new DerivationCache(); const errors = new CompilerError(); const effectsCache: Map<IdentifierId, EffectMetadata> = new Map(); const setStateLoads: Map<IdentifierId, IdentifierId> = new Map(); const setStateUsages: Map<IdentifierId, Set<SourceLocation>> = new Map(); const context: ValidationContext = { functions, candidateDependencies, errors, derivationCache, effectsCache, setStateLoads, setStateUsages, }; if (fn.fnType === 'Hook') { for (const param of fn.params) { if (param.kind === 'Identifier') { context.derivationCache.cache.set(param.identifier.id, { place: param, sourcesIds: new Set(), typeOfValue: 'fromProps', isStateSource: true, }); } } } else if (fn.fnType === 'Component') { const props = fn.params[0]; if (props != null && props.kind === 'Identifier') { context.derivationCache.cache.set(props.identifier.id, { place: props, sourcesIds: new Set(), typeOfValue: 'fromProps', isStateSource: true, }); } } let isFirstPass = true; let iterationCount = 0; do { context.derivationCache.takeSnapshot(); for (const block of fn.body.blocks.values()) { recordPhiDerivations(block, context); for (const instr of block.instructions) { recordInstructionDerivations(instr, context, isFirstPass); } } context.derivationCache.checkForChanges(); isFirstPass = false; iterationCount++; CompilerError.invariant(iterationCount < MAX_FIXPOINT_ITERATIONS, { reason: '[ValidateNoDerivedComputationsInEffects] Fixpoint iteration failed to converge.', description: `Fixpoint iteration exceeded ${MAX_FIXPOINT_ITERATIONS} iterations while tracking derivations. This suggests a cyclic dependency in the derivation cache.`, loc: fn.loc, }); } while (context.derivationCache.snapshot()); for (const [, effect] of effectsCache) { validateEffect(effect.effect, effect.dependencies, context); } return errors.asResult(); } function recordPhiDerivations( block: BasicBlock, context: ValidationContext, ): void { for (const phi of block.phis) { let typeOfValue: TypeOfValue = 'ignored'; let sourcesIds: Set<IdentifierId> = new Set(); for (const operand of phi.operands.values()) { const operandMetadata = context.derivationCache.cache.get( operand.identifier.id, ); if (operandMetadata === undefined) { continue; } typeOfValue = joinValue(typeOfValue, operandMetadata.typeOfValue); sourcesIds.add(operand.identifier.id); } if (typeOfValue !== 'ignored') { context.derivationCache.addDerivationEntry( phi.place, sourcesIds, typeOfValue, false, ); } } } function joinValue( lvalueType: TypeOfValue, valueType: TypeOfValue, ): TypeOfValue { if (lvalueType === 'ignored') return valueType; if (valueType === 'ignored') return lvalueType; if (lvalueType === valueType) return lvalueType; return 'fromPropsAndState'; } function getRootSetState( key: IdentifierId, loads: Map<IdentifierId, IdentifierId | null>, visited: Set<IdentifierId> = new Set(), ): IdentifierId | null { if (visited.has(key)) { return null; } visited.add(key); const parentId = loads.get(key); if (parentId === undefined) { return null; } if (parentId === null) { return key; } return getRootSetState(parentId, loads, visited); } function maybeRecordSetState( instr: Instruction, loads: Map<IdentifierId, IdentifierId | null>, usages: Map<IdentifierId, Set<SourceLocation>>, ): void { for (const operand of eachInstructionLValue(instr)) { if ( instr.value.kind === 'LoadLocal' && loads.has(instr.value.place.identifier.id) ) { loads.set(operand.identifier.id, instr.value.place.identifier.id); } else { if (isSetStateType(operand.identifier)) { // this is a root setState loads.set(operand.identifier.id, null); } } const rootSetState = getRootSetState(operand.identifier.id, loads); if (rootSetState !== null && usages.get(rootSetState) === undefined) { usages.set(rootSetState, new Set([operand.loc])); } } } function recordInstructionDerivations( instr: Instruction, context: ValidationContext, isFirstPass: boolean, ): void { maybeRecordSetState(instr, context.setStateLoads, context.setStateUsages); let typeOfValue: TypeOfValue = 'ignored'; let isSource: boolean = false; const sources: Set<IdentifierId> = new Set(); const {lvalue, value} = instr; if (value.kind === 'FunctionExpression') { context.functions.set(lvalue.identifier.id, value); for (const [, block] of value.loweredFunc.func.body.blocks) { recordPhiDerivations(block, context); for (const instr of block.instructions) { recordInstructionDerivations(instr, context, isFirstPass); } } } else if (value.kind === 'CallExpression' || value.kind === 'MethodCall') { const callee = value.kind === 'CallExpression' ? value.callee : value.property; if ( isUseEffectHookType(callee.identifier) && value.args.length === 2 && value.args[0].kind === 'Identifier' && value.args[1].kind === 'Identifier' ) { const effectFunction = context.functions.get(value.args[0].identifier.id); const deps = context.candidateDependencies.get( value.args[1].identifier.id, ); if (effectFunction != null && deps != null) { context.effectsCache.set(value.args[0].identifier.id, { effect: effectFunction.loweredFunc.func, dependencies: deps, }); } } else if (isUseStateType(lvalue.identifier)) { typeOfValue = 'fromState'; context.derivationCache.addDerivationEntry( lvalue, new Set(), typeOfValue, true, ); return; } } else if (value.kind === 'ArrayExpression') { context.candidateDependencies.set(lvalue.identifier.id, value); } for (const operand of eachInstructionOperand(instr)) { if (context.setStateLoads.has(operand.identifier.id)) { const rootSetStateId = getRootSetState( operand.identifier.id, context.setStateLoads, ); if (rootSetStateId !== null) { context.setStateUsages.get(rootSetStateId)?.add(operand.loc); } } const operandMetadata = context.derivationCache.cache.get( operand.identifier.id, ); if (operandMetadata === undefined) { continue; } typeOfValue = joinValue(typeOfValue, operandMetadata.typeOfValue); sources.add(operand.identifier.id); } if (typeOfValue === 'ignored') { return; } for (const lvalue of eachInstructionLValue(instr)) { context.derivationCache.addDerivationEntry( lvalue, sources, typeOfValue, isSource, ); } if (value.kind === 'FunctionExpression') { /* * We don't want to record effect mutations of FunctionExpressions the mutations will happen in the * function body and we will record them there. */ return; } for (const operand of eachInstructionOperand(instr)) { switch (operand.effect) { case Effect.Capture: case Effect.Store: case Effect.ConditionallyMutate: case Effect.ConditionallyMutateIterator: case Effect.Mutate: { if (isMutable(instr, operand)) { if (context.derivationCache.cache.has(operand.identifier.id)) { const operandMetadata = context.derivationCache.cache.get( operand.identifier.id, ); if (operandMetadata !== undefined) { operandMetadata.typeOfValue = joinValue( typeOfValue, operandMetadata.typeOfValue, ); } } else { context.derivationCache.addDerivationEntry( operand, sources, typeOfValue, false, ); } } break; } case Effect.Freeze: case Effect.Read: { // no-op break; } case Effect.Unknown: { CompilerError.invariant(false, { reason: 'Unexpected unknown effect', loc: operand.loc, }); } default: { assertExhaustive( operand.effect, `Unexpected effect kind \`${operand.effect}\``, ); } } } } type TreeNode = { name: string; typeOfValue: TypeOfValue; isSource: boolean; children: Array<TreeNode>; }; function buildTreeNode( sourceId: IdentifierId, context: ValidationContext, visited: Set<string> = new Set(), ): Array<TreeNode> { const sourceMetadata = context.derivationCache.cache.get(sourceId); if (!sourceMetadata) { return []; } if (sourceMetadata.isStateSource && isNamedIdentifier(sourceMetadata.place)) { return [ { name: sourceMetadata.place.identifier.name.value, typeOfValue: sourceMetadata.typeOfValue, isSource: sourceMetadata.isStateSource, children: [], }, ]; } const children: Array<TreeNode> = []; const namedSiblings: Set<string> = new Set(); for (const childId of sourceMetadata.sourcesIds) { CompilerError.invariant(childId !== sourceId, { reason: 'Unexpected self-reference: a value should not have itself as a source', loc: sourceMetadata.place.loc, }); const childNodes = buildTreeNode( childId, context, new Set([ ...visited, ...(isNamedIdentifier(sourceMetadata.place) ? [sourceMetadata.place.identifier.name.value] : []), ]), ); if (childNodes) { for (const childNode of childNodes) { if (!namedSiblings.has(childNode.name)) { children.push(childNode); namedSiblings.add(childNode.name); } } } } if ( isNamedIdentifier(sourceMetadata.place) && !visited.has(sourceMetadata.place.identifier.name.value) ) { return [ { name: sourceMetadata.place.identifier.name.value, typeOfValue: sourceMetadata.typeOfValue, isSource: sourceMetadata.isStateSource, children: children, }, ]; } return children; } function renderTree( node: TreeNode, indent: string = '', isLast: boolean = true, propsSet: Set<string>, stateSet: Set<string>, ): string { const prefix = indent + (isLast ? '└── ' : '├── '); const childIndent = indent + (isLast ? ' ' : '│ '); let result = `${prefix}${node.name}`; if (node.isSource) { let typeLabel: string; if (node.typeOfValue === 'fromProps') { propsSet.add(node.name); typeLabel = 'Prop'; } else if (node.typeOfValue === 'fromState') { stateSet.add(node.name); typeLabel = 'State'; } else { propsSet.add(node.name); stateSet.add(node.name); typeLabel = 'Prop and State'; } result += ` (${typeLabel})`; } if (node.children.length > 0) { result += '\n'; node.children.forEach((child, index) => { const isLastChild = index === node.children.length - 1; result += renderTree(child, childIndent, isLastChild, propsSet, stateSet); if (index < node.children.length - 1) { result += '\n'; } }); } return result; } function getFnLocalDeps( fn: FunctionExpression | undefined, ): Set<IdentifierId> | undefined { if (!fn) { return undefined; } const deps: Set<IdentifierId> = new Set(); for (const [, block] of fn.loweredFunc.func.body.blocks) { for (const instr of block.instructions) { if (instr.value.kind === 'LoadLocal') { deps.add(instr.value.place.identifier.id); } } } return deps; } function validateEffect( effectFunction: HIRFunction, dependencies: ArrayExpression, context: ValidationContext, ): void { const seenBlocks: Set<BlockId> = new Set(); const effectDerivedSetStateCalls: Array<{ value: CallExpression; id: IdentifierId; sourceIds: Set<IdentifierId>; typeOfValue: TypeOfValue; }> = []; const effectSetStateUsages: Map< IdentifierId, Set<SourceLocation> > = new Map(); // Consider setStates in the effect's dependency array as being part of effectSetStateUsages for (const dep of dependencies.elements) { if (dep.kind === 'Identifier') { const root = getRootSetState(dep.identifier.id, context.setStateLoads); if (root !== null) { effectSetStateUsages.set(root, new Set([dep.loc])); } } } let cleanUpFunctionDeps: Set<IdentifierId> | undefined; const globals: Set<IdentifierId> = new Set(); for (const block of effectFunction.body.blocks.values()) { /* * if the block is in an effect and is of type return then its an effect's cleanup function * if the cleanup function depends on a value from which effect-set state is derived then * we can't validate */ if ( block.terminal.kind === 'return' && block.terminal.returnVariant === 'Explicit' ) { cleanUpFunctionDeps = getFnLocalDeps( context.functions.get(block.terminal.value.identifier.id), ); } for (const pred of block.preds) { if (!seenBlocks.has(pred)) { // skip if block has a back edge return; } } for (const instr of block.instructions) { // Early return if any instruction is deriving a value from a ref if (isUseRefType(instr.lvalue.identifier)) { return; } maybeRecordSetState(instr, context.setStateLoads, effectSetStateUsages); for (const operand of eachInstructionOperand(instr)) { if (context.setStateLoads.has(operand.identifier.id)) { const rootSetStateId = getRootSetState( operand.identifier.id, context.setStateLoads, ); if (rootSetStateId !== null) { effectSetStateUsages.get(rootSetStateId)?.add(operand.loc); } } } if ( instr.value.kind === 'CallExpression' && isSetStateType(instr.value.callee.identifier) && instr.value.args.length === 1 && instr.value.args[0].kind === 'Identifier' ) { const calleeMetadata = context.derivationCache.cache.get( instr.value.callee.identifier.id, ); /* * If the setState comes from a source other than local state skip * since the fix is not to calculate in render */ if (calleeMetadata?.typeOfValue != 'fromState') { continue; } const argMetadata = context.derivationCache.cache.get( instr.value.args[0].identifier.id, ); if (argMetadata !== undefined) { effectDerivedSetStateCalls.push({ value: instr.value, id: instr.value.callee.identifier.id, sourceIds: argMetadata.sourcesIds, typeOfValue: argMetadata.typeOfValue, }); } } else if (instr.value.kind === 'CallExpression') { const calleeMetadata = context.derivationCache.cache.get( instr.value.callee.identifier.id, ); if ( calleeMetadata !== undefined && (calleeMetadata.typeOfValue === 'fromProps' || calleeMetadata.typeOfValue === 'fromPropsAndState') ) { // If the callee is a prop we can't confidently say that it should be derived in render return; } if (globals.has(instr.value.callee.identifier.id)) { // If the callee is a global we can't confidently say that it should be derived in render return; } } else if (instr.value.kind === 'LoadGlobal') { globals.add(instr.lvalue.identifier.id); for (const operand of eachInstructionOperand(instr)) { globals.add(operand.identifier.id); } } } seenBlocks.add(block.id); } for (const derivedSetStateCall of effectDerivedSetStateCalls) { const rootSetStateCall = getRootSetState( derivedSetStateCall.id, context.setStateLoads, ); if ( rootSetStateCall !== null && effectSetStateUsages.has(rootSetStateCall) && context.setStateUsages.has(rootSetStateCall) && effectSetStateUsages.get(rootSetStateCall)!.size === context.setStateUsages.get(rootSetStateCall)!.size - 1 ) { const propsSet = new Set<string>(); const stateSet = new Set<string>(); const rootNodesMap = new Map<string, TreeNode>(); for (const id of derivedSetStateCall.sourceIds) { const nodes = buildTreeNode(id, context); for (const node of nodes) { if (!rootNodesMap.has(node.name)) { rootNodesMap.set(node.name, node); } } } const rootNodes = Array.from(rootNodesMap.values()); const trees = rootNodes.map((node, index) => renderTree( node, '', index === rootNodes.length - 1, propsSet, stateSet, ), ); for (const dep of derivedSetStateCall.sourceIds) { if (cleanUpFunctionDeps !== undefined && cleanUpFunctionDeps.has(dep)) { return; } } const propsArr = Array.from(propsSet); const stateArr = Array.from(stateSet); let rootSources = ''; if (propsArr.length > 0) { rootSources += `Props: [${propsArr.join(', ')}]`; } if (stateArr.length > 0) { if (rootSources) rootSources += '\n'; rootSources += `State: [${stateArr.join(', ')}]`; } const description = `Using an effect triggers an additional render which can hurt performance and user experience, potentially briefly showing stale values to the user This setState call is setting a derived value that depends on the following reactive sources: ${rootSources} Data Flow Tree: ${trees.join('\n')} See: https://react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state`; context.errors.pushDiagnostic( CompilerDiagnostic.create({ description: description, category: ErrorCategory.EffectDerivationsOfState, reason: 'You might not need an effect. Derive values in render, not effects.', }).withDetails({ kind: 'error', loc: derivedSetStateCall.value.callee.loc, message: 'This should be computed during render, not in an effect', }), ); } } }
typescript
github
https://github.com/facebook/react
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateNoDerivedComputationsInEffects_exp.ts
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright 2019-2020 ARM Limited or its affiliates # # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------- import collections import binascii import cbor2 as cbor import json import copy import uuid from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from collections import OrderedDict import logging LOG = logging.getLogger(__name__) TreeBranch = [] ManifestKey = collections.namedtuple( 'ManifestKey', [ 'json_key', 'suit_key', 'obj' ] ) def to_bytes(s): if isinstance(s,bytes): return s try: return binascii.a2b_hex(s) except: try: return binascii.a2b_base64(s) except: if isinstance(s,str): return s.encode('utf-8') else: return str(s).encode('utf-8') class SUITException(Exception): def __init__(self, m, data, tree_branch): super().__init__(m) self.data = data self.tree_branch = tree_branch class SUITCommonInformation: def __init__(self): self.component_ids = [] self.dependencies = [] self.current_index = 0 self.indent_size = 4 def component_id_to_index(self, cid): id = -1 for i, c in enumerate(self.component_ids): if c == cid and i >= 0: id = componentIndex(i) for i, d in enumerate(self.dependencies): if d.digest == cid and i >= 0: id = dependencyIndex(i) return id suitCommonInfo = SUITCommonInformation() one_indent = ' ' class SUITInt: def from_json(self, v): self.v = int(v) return self def to_json(self): return self.v def from_suit(self, v): TreeBranch.append(type(self)) self.v = int(v) TreeBranch.pop() return self def to_suit(self): return self.v def to_debug(self, indent): return str(self.v) class SUITPosInt(SUITInt): def from_json(self, v): TreeBranch.append(type(self)) _v = int(v) # print (_v) if _v < 0: raise Exception('Positive Integers must be >= 0') self.v = _v TreeBranch.pop() return self def from_suit(self, v): return self.from_json(v) class SUITManifestDict: def mkfields(d): # rd = OderedDict() return {k: ManifestKey(*v) for k,v in d.items()} def __init__(self): pass def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False for f, info in self.fields: if hasattr(self, f) != hasattr(rhs, f): return False if hasattr(self, f) and hasattr(rhs, f) and getattr(self, f) != getattr(rhs, f): return False for a,b in zip(self.items, rhs.items): if not a == b: return False return True def from_json(self, data): for k, f in self.fields.items(): v = data.get(f.json_key, None) setattr(self, k, f.obj().from_json(v) if v is not None else None) return self def to_json(self): j = OrderedDict() for k, f in self.fields.items(): v = getattr(self, k) if v: j[f.json_key] = v.to_json() return j def from_suit(self, data): TreeBranch.append(type(self)) for k, f in self.fields.items(): TreeBranch.append(k) v = data.get(f.suit_key, None) d = f.obj().from_suit(v) if v is not None else None setattr(self, k, d) TreeBranch.pop() TreeBranch.pop() return self def to_suit(self): sd = OrderedDict() for k, f in self.fields.items(): v = getattr(self, k) if v: sd[f.suit_key] = v.to_suit() return sd def to_debug(self, indent): s = '{' newindent = indent + one_indent for k, f in self.fields.items(): v = getattr(self, k) if v: s += '\n{ind}/ {jk} / {sk}:'.format(ind=newindent, jk=f.json_key, sk=f.suit_key) s += v.to_debug(newindent) + ',' s += '\n' + indent + '}' return s class SUITManifestNamedList(SUITManifestDict): def from_suit(self, data): TreeBranch.append(type(self)) for k, f in self.fields.items(): TreeBranch.append(k) setattr(self, k, f.obj().from_suit(data[f.suit_key])) TreeBranch.pop() TreeBranch.pop() return self def to_suit(self): sd = [None] * (max([f.suit_key for k, f in self.fields.items()]) + 1) for k, f in self.fields.items(): v = getattr(self, k) if v: sd[f.suit_key] = v.to_suit() return sd def to_debug(self, indent): newindent = indent + one_indent items = [] for k, f in self.fields.items(): v = getattr(self, k) if v: items.append('/ ' + f.json_key + ' / ' + v.to_debug(newindent)) s = '[\n{newindent}{items}\n{indent}]'.format( newindent=newindent, indent=indent, items=',\n{newindent}'.format(newindent=newindent).join(items) ) return s class SUITKeyMap: def mkKeyMaps(m): return {v:k for k,v in m.items()}, m def to_json(self): return self.rkeymap[self.v] def from_json(self, d): self.v = self.keymap[d] return self def to_suit(self): return self.v def from_suit(self, d): TreeBranch.append(type(self)) self.v = self.keymap[self.rkeymap[d]] TreeBranch.pop() return self def to_debug(self, indent): s = str(self.v) + ' / ' + json.dumps(self.to_json(),sort_keys = True) + ' /' return s def SUITBWrapField(c): class SUITBWrapper: def to_suit(self): return cbor.dumps(self.v.to_suit(), canonical=True) def from_suit(self, d): TreeBranch.append(type(self)) try: self.v = c().from_suit(cbor.loads(d)) except SUITException as e: raise e except Exception as e: LOG.debug('At {}: failed to load "{}" as CBOR'.format(type(self),binascii.b2a_hex(d).decode('utf-8'))) LOG.debug('Path: {}'.format(TreeBranch)) # LOG.debug('At {}: failed to load "{}" as CBOR'.format(type(self),binascii.b2a_hex(d).decode('utf-8'))) raise SUITException( m = 'At {}: failed to load "{}" as CBOR'.format(type(self),binascii.b2a_hex(d).decode('utf-8')), data = d, tree_branch = TreeBranch ) TreeBranch.pop() return self def to_json(self): return self.v.to_json() def from_json(self, d): self.v = c().from_json(d) return self def to_debug(self, indent): s = 'h\'' s += binascii.b2a_hex(self.to_suit()).decode('utf-8') s += '\' / ' s += self.v.to_debug(indent) s += ' /' return s return SUITBWrapper class SUITManifestArray: def __init__(self): self.items=[] def __eq__(self, rhs): if not isinstance(rhs, type(self)): return False if len(self.items) != len(rhs.items): return False for a,b in zip(self.items, rhs.items): if not a == b: return False return True def from_json(self, data): self.items = [] for d in data: self.items.append(self.field.obj().from_json(d)) return self def to_json(self): j = [] for i in self.items: j.append(i.to_json()) return j def from_suit(self, data): self.items = [] TreeBranch.append(type(self)) for d in data: TreeBranch.append(len(self.items)) self.items.append(self.field.obj().from_suit(d)) TreeBranch.pop() TreeBranch.pop() return self def to_suit(self): l = [] for i in self.items: l.append(i.to_suit()) return l def append(self, element): if not isinstance(element, self.field.obj): raise Exception('element {} is not a {}'.format(element, self.field.obj)) self.items.append(element) def to_debug(self, indent): newindent = indent + one_indent s = '[\n' s += ' ,\n'.join([newindent + v.to_debug(newindent) for v in self.items]) s += '\n' + indent + ']' return s class SUITBytes: def to_json(self): return binascii.b2a_hex(self.v).decode('utf-8') def from_json(self, d): self.v = to_bytes(d) return self def from_suit(self, d): self.v = bytes(d) return self def to_suit(self): return self.v def to_debug(self, indent): return 'h\'' + self.to_json() + '\'' def __eq__(self, rhs): return self.v == rhs.v class SUITUUID(SUITBytes): def from_json(self, d): self.v = uuid.UUID(d).bytes return self def from_suit(self, d): self.v = uuid.UUID(bytes=d).bytes return self def to_debug(self, indent): return 'h\'' + json.dumps(self.to_json(), sort_keys=True) + '\' / ' + str(uuid.UUID(bytes=self.v)) + ' /' class SUITRaw: def to_json(self): return self.v def from_json(self, d): self.v = d return self def to_suit(self): return self.v def from_suit(self, d): self.v = d return self def to_debug(self, indent): return str(self.v) class SUITNil: def to_json(self): return None def from_json(self, d): if d is not None: raise Exception('Expected Nil') return self def to_suit(self): return None def from_suit(self, d): if d is not None: raise Exception('Expected Nil') return self def to_debug(self, indent): return 'F6 / nil /' class SUITTStr(SUITRaw): def from_json(self, d): self.v = str(d) return self def from_suit(self, d): self.v = str(d) return self def to_debug(self, indent): return '\''+ str(self.v) + '\'' class SUITComponentId(SUITManifestArray): field = collections.namedtuple('ArrayElement', 'obj')(obj=SUITBytes) def to_suit(self): return tuple(super(SUITComponentId, self).to_suit()) def to_debug(self, indent): newindent = indent + one_indent s = '[' + ''.join([v.to_debug(newindent) for v in self.items]) + ']' return s def __hash__(self): return hash(tuple([i.v for i in self.items])) class SUITComponentIndex(SUITComponentId): def to_suit(self): return suitCommonInfo.component_id_to_index(self) def from_suit(self, d): return super(SUITComponentIndex, self).from_suit( suitCommonInfo.component_ids[d].to_suit() ) def to_debug(self, indent): newindent = indent + one_indent s = '{suit} / [{dbg}] /'.format( suit=self.to_suit(), dbg=''.join([v.to_debug(newindent) for v in self.items]) ) return s class SUITComponents(SUITManifestArray): field = collections.namedtuple('ArrayElement', 'obj')(obj=SUITComponentId) def from_suit(self, data): super(SUITComponents, self).from_suit(data) suitCommonInfo.component_ids = self.items return self def from_json(self, j): super(SUITComponents, self).from_json(j) suitCommonInfo.component_ids = self.items return self class SUITDigestAlgo(SUITKeyMap): rkeymap, keymap = SUITKeyMap.mkKeyMaps({ 'sha224' : 1, 'sha256' : 2, 'sha384' : 3, 'sha512' : 4 }) class SUITDigest(SUITManifestNamedList): fields = SUITManifestNamedList.mkfields({ 'algo' : ('algorithm-id', 0, SUITDigestAlgo), 'digest' : ('digest-bytes', 1, SUITBytes) }) def __hash__(self): return hash(tuple([getattr(self, k) for k in self.fields.keys() if hasattr(self, k)])) class SUITCompressionInfo(SUITKeyMap): rkeymap, keymap = SUITKeyMap.mkKeyMaps({ 'gzip' : 1, 'bzip2' : 2, 'deflate' : 3, 'lz4' : 4, 'lzma' : 7 }) class SUITParameters(SUITManifestDict): fields = SUITManifestDict.mkfields({ 'vendor-id' : ('vendor-id', 1, SUITUUID), 'class-id' : ('class-id', 2, SUITUUID), 'digest' : ('image-digest', 3, SUITBWrapField(SUITDigest)), 'size' : ('image-size', 14, SUITPosInt), 'uri' : ('uri', 21, SUITTStr), 'src' : ('source-component', 22, SUITComponentIndex), 'compress' : ('compression-info', 19, SUITCompressionInfo), 'offset' : ('offset', 5, SUITPosInt) }) def from_json(self, j): return super(SUITParameters, self).from_json(j) class SUITTryEach(SUITManifestArray): pass class dependencyIndex(int): def __new__(cls, value): return super(cls, cls).__new__(cls, value) class componentIndex(int): def __new__(cls, value): return super(cls, cls).__new__(cls, value) def SUITCommandContainer(jkey, skey, argtype, dp=[]): class SUITCmd(SUITCommand): json_key = jkey suit_key = skey dep_params = dp def __init__(self): pass def to_suit(self): return [self.suit_key, self.arg.to_suit()] def to_json(self): if self.json_key == 'directive-set-component-index': return {} else: return { 'command-id' : self.json_key, 'command-arg' : self.arg.to_json(), 'component-id' : self.cid.to_json() } def from_json(self, j): if j['command-id'] != self.json_key: raise Except('JSON Key mismatch error') if self.json_key != 'directive-set-component-index' and self.json_key != 'directive-set-dependency-index': try: self.cid = SUITComponentId().from_json(j['component-id']) except: self.cid = SUITDigest().from_json(j['component-id']) self.arg = argtype().from_json(j['command-arg']) return self def from_suit(self, s): if s[0] != self.suit_key: raise Except('SUIT Key mismatch error') if self.json_key == 'directive-set-component-index': suitCommonInfo.current_index = componentIndex(s[1]) elif self.json_key == 'directive-set-dependency-index': suitCommonInfo.current_index = dependencyIndex(s[1]) else: if isinstance(suitCommonInfo.current_index, dependencyIndex): self.cid = suitCommonInfo.dependencies[suitCommonInfo.current_index] else: self.cid = suitCommonInfo.component_ids[suitCommonInfo.current_index] self.arg = argtype().from_suit(s[1]) return self def to_debug(self, indent): s = '/ {} / {},'.format(self.json_key, self.suit_key) s += self.arg.to_debug(indent) return s return SUITCmd def mkPolicy(policy): class SUITReportingPolicy(SUITPosInt): default_policy = policy def from_json(self, j): if j is None: j = self.default_policy return super(SUITReportingPolicy, self).from_json(j) return SUITReportingPolicy class SUITCommand: def from_json(self, j): return self.jcommands[j['command-id']]().from_json(j) def from_suit(self, s): return self.scommands[s[0]]().from_suit(s) SUITCommand.commands = [ SUITCommandContainer('condition-vendor-identifier', 1, mkPolicy(policy=0xF), dp=['vendor-id']), SUITCommandContainer('condition-class-identifier', 2, mkPolicy(policy=0xF), dp=['class-id']), SUITCommandContainer('condition-image-match', 3, mkPolicy(policy=0xF), dp=['digest']), SUITCommandContainer('condition-use-before', 4, mkPolicy(policy=0xA)), SUITCommandContainer('condition-component-offset', 5, mkPolicy(policy=0x5), dp=['offset']), SUITCommandContainer('condition-device-identifier', 24, mkPolicy(policy=0xF)), SUITCommandContainer('condition-image-not-match', 25, mkPolicy(policy=0xF)), SUITCommandContainer('condition-minimum-battery', 26, mkPolicy(policy=0xA)), SUITCommandContainer('condition-update-authorised', 27, mkPolicy(policy=0x3)), SUITCommandContainer('condition-version', 28, mkPolicy(policy=0xF)), SUITCommandContainer('directive-set-component-index', 12, SUITPosInt), SUITCommandContainer('directive-set-dependency-index', 13, SUITPosInt), SUITCommandContainer('directive-abort', 14, mkPolicy(policy=0x2)), SUITCommandContainer('directive-try-each', 15, SUITTryEach), SUITCommandContainer('directive-process-dependency', 18, mkPolicy(policy=0)), SUITCommandContainer('directive-set-parameters', 19, SUITParameters), SUITCommandContainer('directive-override-parameters', 20, SUITParameters), SUITCommandContainer('directive-fetch', 21, mkPolicy(policy=0x2)), SUITCommandContainer('directive-copy', 22, mkPolicy(policy=0x2)), SUITCommandContainer('directive-run', 23, mkPolicy(policy=0x2)), SUITCommandContainer('directive-wait', 29, mkPolicy(policy=0x2)), SUITCommandContainer('directive-run-sequence', 30, SUITRaw), SUITCommandContainer('directive-run-with-arguments', 31, SUITRaw), SUITCommandContainer('directive-swap', 32, mkPolicy(policy=0x2)), ] SUITCommand.jcommands = { c.json_key : c for c in SUITCommand.commands} SUITCommand.scommands = { c.suit_key : c for c in SUITCommand.commands} class SUITSequence(SUITManifestArray): field = collections.namedtuple('ArrayElement', 'obj')(obj=SUITCommand) def to_suit(self): suit_l = [] suitCommonInfo.current_index = 0 if len(suitCommonInfo.component_ids) == 1 else None for i in self.items: if i.json_key == 'directive-set-component-index': suitCommonInfo.current_index = componentIndex(i.arg.v) elif i.json_key == 'directive-set-dependency-index': suitCommonInfo.current_index = dependencyIndex(i.arg.v) else: # Option 1: current & command index same class, same number, # Do nothing # Option 2: current & command not equal, command is component # set component index # Option 3: current & command not equal, command is dependency # set dependency index cidx = suitCommonInfo.component_id_to_index(i.cid) if cidx != suitCommonInfo.current_index: op = 'directive-set-component-index' if isinstance(cidx, dependencyIndex): op = 'directive-set-dependency-index' # Change component/dependency suitCommonInfo.current_index = cidx suit_l += SUITCommand().from_json({ 'command-id' : op, 'command-arg' : int(cidx) }).to_suit() suit_l += i.to_suit() return suit_l def to_debug(self, indent): return super(SUITSequence, SUITSequence().from_suit(self.to_suit())).to_debug(indent) def from_suit(self, s): self.items = [SUITCommand().from_suit(i) for i in zip(*[iter(s)]*2)] return self SUITTryEach.field = collections.namedtuple('ArrayElement', 'obj')(obj=SUITBWrapField(SUITSequence)) class SUITSequenceComponentReset(SUITSequence): def to_suit(self): suitCommonInfo.current_index = None return super(SUITSequenceComponentReset, self).to_suit() def SUITMakeSeverableField(c): class SUITSeverableField: objtype = SUITBWrapField(c) def from_json(self, data): if 'algorithm-id' in data: self.v = SUITDigest().from_json(data) else: self.v = self.objtype().from_json(data) return self def from_suit(self, data): if isinstance(data, list): self.v = SUITDigest().from_suit(data) else: self.v = self.objtype().from_suit(data) return self def to_json(self): return self.v.to_json() def to_suit(self): return self.v.to_suit() def to_debug(self, indent): return self.v.to_debug(indent) return SUITSeverableField class SUITDependency(SUITManifestDict): fields = SUITManifestDict.mkfields({ 'digest' : ('dependency-digest', 1, SUITDigest), 'prefix' : ('dependency-prefix', 2, SUITComponentId), }) class SUITDependencies(SUITManifestArray): field = collections.namedtuple('ArrayElement', 'obj')(obj=SUITDependency) def from_suit(self, data): super(SUITDependencies, self).from_suit(data) suitCommonInfo.dependencies = self.items return self def from_json(self, j): super(SUITDependencies, self).from_json(j) suitCommonInfo.dependencies = self.items return self class SUITCommon(SUITManifestDict): fields = SUITManifestNamedList.mkfields({ 'dependencies' : ('dependencies', 1, SUITBWrapField(SUITDependencies)), 'components' : ('components', 2, SUITComponents), 'common_sequence' : ('common-sequence', 4, SUITBWrapField(SUITSequenceComponentReset)), }) class SUITComponentText(SUITManifestDict): fields = SUITManifestDict.mkfields({ 'vendorname' : ('vendor-name', 1, SUITTStr), 'modelname' : ('model-name', 2, SUITTStr), 'vendordomain' : ('vendor-domain', 3, SUITTStr), 'modelinfo' : ('json-source', 4, SUITTStr), 'cdesc' : ('component-description', 5, SUITTStr), 'version' : ('version', 6, SUITTStr), 'reqversion' : ('required-version', 7, SUITTStr), }) class SUITText(SUITManifestDict): fields = SUITManifestDict.mkfields({ 'mdesc' : ('manifest-description', 1, SUITTStr), 'udesc' : ('update-description', 2, SUITTStr), 'json' : ('json-source', 3, SUITTStr), 'yaml' : ('yaml-source', 4, SUITTStr), }) components={} def to_json(self): d = super(SUITText, self).to_json() d.update({k.to_json() : v.to_json() for k,v in self.components.items()}) return d def from_json(self, data): # Handle components for k,v in data.items(): if not isinstance(v, str): self.components[SUITComponentId().from_json(k)] = SUITComponentText().from_json(v) # Treat everything else as a normal manifestDict return super(SUITText, self).from_json(data) def to_suit(self): d = super(SUITText, self).to_suit() d.update({k.to_suit() : v.to_suit() for k,v in self.components.items()}) return d def from_suit(self, data): # Handle components for k,v in data.items(): if not isinstance(v, str): self.components[SUITComponentId().from_suit(k)] = SUITComponentText().from_suit(v) # Treat everything else as a normal manifestDict return super(SUITText, self).from_json(data) def to_debug(self, indent): s = '{' newindent = indent + one_indent for k, f in self.fields.items(): v = getattr(self, k) if v: s += '\n{ind}/ {jk} / {sk}:'.format(ind=newindent, jk=f.json_key, sk=f.suit_key) s += v.to_debug(newindent) + ',' for k, f in self.components.items(): s += '\n' + newindent + '{}:'.format(k.to_debug(newindent + one_indent)) s += f.to_debug(newindent + one_indent) s += '\n' + indent + '}' return s class SUITManifest(SUITManifestDict): fields = SUITManifestDict.mkfields({ 'version' : ('manifest-version', 1, SUITPosInt), 'sequence' : ('manifest-sequence-number', 2, SUITPosInt), 'common' : ('common', 3, SUITBWrapField(SUITCommon)), 'refuri' : ('reference-uri', 4, SUITTStr), 'deres' : ('dependency-resolution', 7, SUITMakeSeverableField(SUITSequenceComponentReset)), 'fetch' : ('payload-fetch', 8, SUITMakeSeverableField(SUITSequenceComponentReset)), 'install' : ('install', 9, SUITMakeSeverableField(SUITSequenceComponentReset)), 'validate' : ('validate', 10, SUITBWrapField(SUITSequenceComponentReset)), 'load' : ('load', 11, SUITBWrapField(SUITSequenceComponentReset)), 'run' : ('run', 12, SUITBWrapField(SUITSequenceComponentReset)), 'text' : ('text', 13, SUITMakeSeverableField(SUITText)), 'coswid' : ('coswid', 14, SUITBytes), }) class COSE_Algorithms(SUITKeyMap): rkeymap, keymap = SUITKeyMap.mkKeyMaps({ 'ES256' : -7, 'ES384' : -35, 'ES512' : -36, 'EdDSA' : -8, 'HSS-LMS' : -46, }) class COSE_CritList(SUITManifestArray): field = collections.namedtuple('ArrayElement', 'obj')(obj=SUITInt) class COSE_header_map(SUITManifestDict): fields = SUITManifestDict.mkfields({ # 1: algorithm Identifier 'alg' : ('alg', 1, COSE_Algorithms), # 2: list of critical headers (criticality) # 3: content type # 4: key id 'kid' : ('kid', 4, SUITBytes), # 5: IV # 6: partial IV # 7: counter signature(s) }) class COSE_Sign: pass class COSE_Sign1(SUITManifestNamedList): fields = SUITManifestDict.mkfields({ 'protected' : ('protected', 0, SUITBWrapField(COSE_header_map)), 'unprotected' : ('unprotected', 1, COSE_header_map), 'payload' : ('payload', 2, SUITBWrapField(SUITDigest)), 'signature' : ('signature', 3, SUITBytes) }) class COSE_Mac: pass class COSE_Mac0: pass class COSETagChoice(SUITManifestDict): def to_suit(self): for k, f in self.fields.items(): v = getattr(self, k, None) if v: return cbor.CBORTag(tag=f.suit_key, value=v.to_suit()) return None def from_suit(self, data): for k, f in self.fields.items(): if data.tag == f.suit_key: v = data.value d = f.obj().from_suit(v) if v is not None else None setattr(self, k, d) return self def to_debug(self, indent): s = '' for k, f in self.fields.items(): if hasattr(self, k): v = getattr(self, k) newindent = indent + one_indent s = '{tag}({value})'.format(tag=f.suit_key, value=v.to_debug(newindent)) return s class COSETaggedAuth(COSETagChoice): fields = SUITManifestDict.mkfields({ 'cose_sign' : ('COSE_Sign_Tagged', 98, COSE_Sign), 'cose_sign1' : ('COSE_Sign1_Tagged', 18, COSE_Sign1), 'cose_mac' : ('COSE_Mac_Tagged', 97, COSE_Mac), 'cose_mac0' : ('COSE_Mac0_Tagged', 17, COSE_Mac0) }) class COSEList(SUITManifestArray): field = collections.namedtuple('ArrayElement', 'obj')(obj=SUITBWrapField(COSETaggedAuth)) def from_suit(self, data): return super(COSEList, self).from_suit(data) class SUITEnvelope(SUITManifestDict): fields = SUITManifestDict.mkfields({ 'auth' : ('authentication-wrapper', 2, SUITBWrapField(COSEList)), 'manifest' : ('manifest', 3, SUITBWrapField(SUITManifest)), 'deres': ('dependency-resolution', 7, SUITBWrapField(SUITSequence)), 'fetch': ('payload-fetch', 8, SUITBWrapField(SUITSequence)), 'install': ('install', 9, SUITBWrapField(SUITSequence)), 'validate': ('validate', 10, SUITBWrapField(SUITSequence)), 'load': ('load', 11, SUITBWrapField(SUITSequence)), 'run': ('run', 12, SUITBWrapField(SUITSequence)), 'text': ('text', 13, SUITBWrapField(SUITText)), 'coswid': ('coswid', 14, SUITBytes), }) severable_fields = {'deres', 'fetch', 'install', 'text', 'coswid'} digest_algorithms = { 'sha224' : hashes.SHA224, 'sha256' : hashes.SHA256, 'sha384' : hashes.SHA384, 'sha512' : hashes.SHA512 } def to_severable(self, digest_alg): sev = copy.deepcopy(self) for k in sev.severable_fields: f = sev.manifest.v.fields[k] if not hasattr(sev.manifest.v, k): continue v = getattr(sev.manifest.v, k) if v is None: continue cbor_field = cbor.dumps(v.to_suit(), canonical=True) digest = hashes.Hash(self.digest_algorithms.get(digest_alg)(), backend=default_backend()) digest.update(cbor_field) field_digest = SUITDigest().from_json({ 'algorithm-id' : digest_alg, 'digest-bytes' : digest.finalize() }) cbor_digest = cbor.dumps(field_digest.to_suit(), canonical=True) if len(cbor_digest) < len(cbor_field): setattr(sev.manifest.v, k, field_digest) setattr(sev,k,v) return sev def from_severable(self): raise Exception('From Severable unimplemented') nsev = copy.deepcopy(self) for k in nsev.severable_fields: f = nsev.fields[k] if not hasattr(nsev, k): continue v = getattr(nsev, k) if v is None: continue # Verify digest cbor_field = cbor.dumps(v.to_suit(), canonical=True) digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.update(cbor_field) actual_digest = digest.finalize() field_digest = getattr(nsev.v, k) expected_digest = field_digest.to_suit()[1] if digest != expected_digest: raise Exception('Field Digest mismatch: For {}, expected: {}, got {}'.format( f.json_key, expected_digest, actual_digest )) setattr(nsev.manifest.v, k, v) delattr(nsev, k) return nsev
unknown
codeparrot/codeparrot-clean
# (c) 2013, Jan-Piet Mens <jpmens(at)gmail.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ lookup: csvfile author: Jan-Piet Mens (@jpmens) <jpmens(at)gmail.com> version_added: "1.5" short_description: read data from a TSV or CSV file description: - The csvfile lookup reads the contents of a file in CSV (comma-separated value) format. The lookup looks for the row where the first column matches keyname, and returns the value in the second column, unless a different column is specified. options: col: description: column to return (0 index). default: "1" default: description: what to return if the value is not found in the file. default: '' delimiter: description: field separator in the file, for a tab you can specify "TAB" or "t". default: TAB file: description: name of the CSV/TSV file to open. default: ansible.csv encoding: description: Encoding (character set) of the used CSV file. default: utf-8 version_added: "2.1" notes: - The default is for TSV files (tab delimited) not CSV (comma delimited) ... yes the name is misleading. """ EXAMPLES = """ - name: Match 'Li' on the first column, return the second column (0 based index) debug: msg="The atomic number of Lithium is {{ lookup('csvfile', 'Li file=elements.csv delimiter=,') }}" - name: msg="Match 'Li' on the first column, but return the 3rd column (columns start counting after the match)" debug: msg="The atomic mass of Lithium is {{ lookup('csvfile', 'Li file=elements.csv delimiter=, col=2') }}" """ RETURN = """ _raw: description: - value(s) stored in file column """ import codecs import csv from collections import MutableSequence from ansible.errors import AnsibleError, AnsibleAssertionError from ansible.plugins.lookup import LookupBase from ansible.module_utils.six import PY2 from ansible.module_utils._text import to_bytes, to_native, to_text class CSVRecoder: """ Iterator that reads an encoded stream and reencodes the input to UTF-8 """ def __init__(self, f, encoding='utf-8'): self.reader = codecs.getreader(encoding)(f) def __iter__(self): return self def __next__(self): return next(self.reader).encode("utf-8") next = __next__ # For Python 2 class CSVReader: """ A CSV reader which will iterate over lines in the CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding='utf-8', **kwds): if PY2: f = CSVRecoder(f, encoding) else: f = codecs.getreader(encoding)(f) self.reader = csv.reader(f, dialect=dialect, **kwds) def __next__(self): row = next(self.reader) return [to_text(s) for s in row] next = __next__ # For Python 2 def __iter__(self): return self class LookupModule(LookupBase): def read_csv(self, filename, key, delimiter, encoding='utf-8', dflt=None, col=1): try: f = open(filename, 'rb') creader = CSVReader(f, delimiter=to_native(delimiter), encoding=encoding) for row in creader: if len(row) and row[0] == key: return row[int(col)] except Exception as e: raise AnsibleError("csvfile: %s" % to_native(e)) return dflt def run(self, terms, variables=None, **kwargs): ret = [] for term in terms: params = term.split() key = params[0] paramvals = { 'col': "1", # column to return 'default': None, 'delimiter': "TAB", 'file': 'ansible.csv', 'encoding': 'utf-8', } # parameters specified? try: for param in params[1:]: name, value = param.split('=') if name not in paramvals: raise AnsibleAssertionError('%s not in paramvals' % name) paramvals[name] = value except (ValueError, AssertionError) as e: raise AnsibleError(e) if paramvals['delimiter'] == 'TAB': paramvals['delimiter'] = "\t" lookupfile = self.find_file_in_search_path(variables, 'files', paramvals['file']) var = self.read_csv(lookupfile, key, paramvals['delimiter'], paramvals['encoding'], paramvals['default'], paramvals['col']) if var is not None: if isinstance(var, MutableSequence): for v in var: ret.append(v) else: ret.append(var) return ret
unknown
codeparrot/codeparrot-clean
""" Created on Mar 15, 2014 @author: tjoneslo """ from .pdfcolor import PDFColor class PDFDraw(object): """ Base class for the drawing classes: PDFLine, PDFRectangle, PDFEllipse """ def __init__(self, session, page, color=None, style=None, stroke=None, size=1): # S is plain, B is filled with border, F is filled no border. self.style_list = ['S', 'B', 'F'] self.stroke_list = ['solid', 'dashed', 'dots'] self.session = session self.page = page self.color = color self._set_size(size) self._set_style(style) self._set_stroke(stroke) self.fill_color = None def _set_size(self, line_size=1): self.line_size = line_size def _set_style(self, style=None): if style in self.stroke_list: raise Exception("Style in stroke list : %s" % style) style = style.upper() if style is not None else 'S' self._style = style if style in self.style_list else 'S' def _set_stroke(self, stroke='solid'): if stroke in self.style_list: raise Exception("Stroke in style list : %s" % stroke) if stroke == "dashed" or stroke == 1: self._stroke = "dashed" elif stroke == 'dots' or stroke == 2: self._stroke = 'dots' else: self._stroke = "solid" def _draw_color(self): if isinstance(self.color, PDFColor): self.color._set_type('d') if not self.session._compare_color(self.color): self.session._out(self.color._get_color_string(), self.page) self.session._save_color(self.color.copy()) def _draw_colors(self): self._draw_color() if isinstance(self.fill_color, PDFColor): self.fill_color._set_type('f') if not self.session._compare_color(self.fill_color): self.session._out(self.fill_color._get_color_string(), self.page) self.session._save_color(self.fill_color.copy()) def _draw_stroke(self): if self._stroke == "dashed": self.session._out('[%s] %s d' % (3, 0), self.page) elif self._stroke == "solid": self.session._out('[] 0 d', self.page) elif self._stroke == 'dots': self.session._out('[%s] %s d' % (1, 1), self.page) def _draw_line_size(self): self.session._out('%.2f w' % self.line_size, self.page) def _draw(self): raise NotImplementedError
unknown
codeparrot/codeparrot-clean
import { InstantSample, Metric } from "../api/responseTypes/query"; import { formatPrometheusFloat, parsePrometheusFloat, } from "../lib/formatFloatValue"; import { binaryOperatorType, vectorMatchCardinality, VectorMatching, } from "./ast"; import { isComparisonOperator, isSetOperator } from "./utils"; // We use a special (otherwise invalid) sample value to indicate that // a sample has been filtered away by a comparison operator. export const filteredSampleValue = "filtered"; export enum MatchErrorType { multipleMatchesForOneToOneMatching = "multipleMatchesForOneToOneMatching", multipleMatchesOnBothSides = "multipleMatchesOnBothSides", multipleMatchesOnOneSide = "multipleMatchesOnOneSide", } // There's no group_x() modifier, but one of the sides has multiple matches. export interface MultipleMatchesForOneToOneMatchingError { type: MatchErrorType.multipleMatchesForOneToOneMatching; dupeSide: "left" | "right"; } // There's no group_x() modifier and there are multiple matches on both sides. // This is good to keep as a separate error from MultipleMatchesForOneToOneMatchingError // because it can't be fixed by adding group_x() but rather by expanding the set of // matching labels. export interface MultipleMatchesOnBothSidesError { type: MatchErrorType.multipleMatchesOnBothSides; } // There's a group_x() modifier, but the "one" side has multiple matches. This could mean // that either the matching labels are not sufficient or that group_x() is the wrong way around. export interface MultipleMatchesOnOneSideError { type: MatchErrorType.multipleMatchesOnOneSide; } export type VectorMatchError = | MultipleMatchesForOneToOneMatchingError | MultipleMatchesOnBothSidesError | MultipleMatchesOnOneSideError; export type MaybeFilledInstantSample = InstantSample & { // If the sample was filled in via a fill(...) modifier, this is true. filled?: boolean; }; // A single match group as produced by a vector-to-vector binary operation, with all of its // left-hand side and right-hand side series, as well as a result and error, if applicable. export type BinOpMatchGroup = { groupLabels: Metric; rhs: MaybeFilledInstantSample[]; rhsCount: number; // Number of samples before applying limits. lhs: MaybeFilledInstantSample[]; lhsCount: number; // Number of samples before applying limits. result: { sample: InstantSample; // Which "many"-side sample did this sample come from? This is needed for use cases where // we want to style the corresponding "many" side input sample and the result sample in // a similar way (e.g. shading them in the same color) to be able to trace which "many" // side sample a result sample came from. manySideIdx: number; }[]; error: VectorMatchError | null; }; // The result of computeVectorVectorBinOp(), modeling the match groups produced by a // vector-to-vector binary operation. export type BinOpMatchGroups = { [sig: string]: BinOpMatchGroup; }; export type BinOpResult = { groups: BinOpMatchGroups; // Can differ from the number of returned groups if a limit was applied. numGroups: number; }; // FNV-1a hash parameters. const FNV_PRIME = 0x01000193; const OFFSET_BASIS = 0x811c9dc5; const SEP = "\uD800".charCodeAt(0); // Using a Unicode "high surrogate" code point as a separator. These should not appear by themselves (without a low surrogate pairing) in a valid Unicode string. // Compute an FNV-1a hash over a given set of values in order to // produce a signature for a match group. export const fnv1a = (values: string[]): string => { let h = OFFSET_BASIS; for (let i = 0; i < values.length; i++) { // Skip labels that are not set on the metric. if (values[i] !== undefined) { for (let c = 0; c < values[i].length; c++) { h ^= values[i].charCodeAt(c); h *= FNV_PRIME; } } if (i < values.length - 1) { h ^= SEP; h *= FNV_PRIME; } } return h.toString(); }; // Return a function that generates the match group signature for a given label set. const signatureFunc = (on: boolean, names: string[]) => { names.sort(); if (on) { return (lset: Metric): string => { return fnv1a(names.map((ln: string) => lset[ln])); }; } return (lset: Metric): string => fnv1a( Object.keys(lset) .filter((ln) => !names.includes(ln) && ln !== "__name__") .map((ln) => lset[ln]) ); }; // For a given metric, return only the labels used for matching. const matchLabels = (metric: Metric, on: boolean, labels: string[]): Metric => { const result: Metric = {}; for (const name in metric) { if (labels.includes(name) === on && (on || name !== "__name__")) { result[name] = metric[name]; } } return result; }; export const scalarBinOp = ( op: binaryOperatorType, lhs: number, rhs: number ): number => { const { value, keep } = vectorElemBinop(op, lhs, rhs); if (isComparisonOperator(op)) { return Number(keep); } return value; }; export const vectorElemBinop = ( op: binaryOperatorType, lhs: number, rhs: number ): { value: number; keep: boolean } => { switch (op) { case binaryOperatorType.add: return { value: lhs + rhs, keep: true }; case binaryOperatorType.sub: return { value: lhs - rhs, keep: true }; case binaryOperatorType.mul: return { value: lhs * rhs, keep: true }; case binaryOperatorType.div: return { value: lhs / rhs, keep: true }; case binaryOperatorType.pow: return { value: Math.pow(lhs, rhs), keep: true }; case binaryOperatorType.mod: return { value: lhs % rhs, keep: true }; case binaryOperatorType.eql: return { value: lhs, keep: lhs === rhs }; case binaryOperatorType.neq: return { value: lhs, keep: lhs !== rhs }; case binaryOperatorType.gtr: return { value: lhs, keep: lhs > rhs }; case binaryOperatorType.lss: return { value: lhs, keep: lhs < rhs }; case binaryOperatorType.gte: return { value: lhs, keep: lhs >= rhs }; case binaryOperatorType.lte: return { value: lhs, keep: lhs <= rhs }; case binaryOperatorType.atan2: return { value: Math.atan2(lhs, rhs), keep: true }; default: throw new Error("invalid binop"); } }; // Operations that change the metric's original meaning should drop the metric name from the result. const shouldDropMetricName = (op: binaryOperatorType): boolean => [ binaryOperatorType.add, binaryOperatorType.sub, binaryOperatorType.mul, binaryOperatorType.div, binaryOperatorType.pow, binaryOperatorType.mod, binaryOperatorType.atan2, ].includes(op); // Compute the time series labels for the result metric. export const resultMetric = ( lhs: Metric, rhs: Metric, op: binaryOperatorType, matching: VectorMatching ): Metric => { const result: Metric = {}; // Start out with all labels from the LHS. for (const name in lhs) { result[name] = lhs[name]; } // Drop metric name for operations that change the metric's meaning. if (shouldDropMetricName(op)) { delete result.__name__; } // Keep only match group labels for 1:1 matches. if (matching.card === vectorMatchCardinality.oneToOne) { if (matching.on) { // Drop all labels that are not in the "on" clause. for (const name in result) { if (!matching.labels.includes(name)) { delete result[name]; } } } else { // Drop all labels that are in the "ignoring" clause. for (const name of matching.labels) { delete result[name]; } } } // Include extra labels from the RHS that were mentioned in a group_x(...) modifier. matching.include.forEach((name) => { if (name in rhs) { result[name] = rhs[name]; } else { // If we are trying to include a label from the "one" side that is not actually set there, // we need to make sure that we don't accidentally take its value from the "many" side // if it exists there. // // Example to provoke this case: // // up == on(job, instance) group_left(__name__) node_exporter_build_info*1 delete result[name]; } }); return result; }; // Compute the match groups and results for each match group for a binary operator between two vectors. // In the error case, the match groups are still populated and returned, but the error field is set for // the respective group. Results are not populated for error cases, since especially in the case of a // many-to-many matching, the cross-product output can become prohibitively expensive. export const computeVectorVectorBinOp = ( op: binaryOperatorType, matching: VectorMatching, bool: boolean, lhs: InstantSample[], rhs: InstantSample[], limits?: { maxGroups?: number; maxSeriesPerGroup?: number; } ): BinOpResult => { // For the simplification of further calculations, we assume that the "one" side of a one-to-many match // is always the right-hand side of the binop and swap otherwise to ensure this. We swap back in the end. [lhs, rhs] = matching.card === vectorMatchCardinality.oneToMany ? [rhs, lhs] : [lhs, rhs]; const groups: BinOpMatchGroups = {}; const sigf = signatureFunc(matching.on, matching.labels); // While we only use this set to compute a count of limited groups in the end, we can encounter each // group multiple times (since multiple series can map to the same group). So we need to use a set // to track which groups we've already counted. const outOfLimitGroups = new Set<string>(); // Add all RHS samples to the grouping map. rhs.forEach((rs) => { const sig = sigf(rs.metric); if (!(sig in groups)) { if (limits?.maxGroups && Object.keys(groups).length >= limits.maxGroups) { outOfLimitGroups.add(sig); return; } groups[sig] = { groupLabels: matchLabels(rs.metric, matching.on, matching.labels), lhs: [], lhsCount: 0, rhs: [], rhsCount: 0, result: [], error: null, }; } if ( !limits?.maxSeriesPerGroup || groups[sig].rhsCount < limits.maxSeriesPerGroup ) { groups[sig].rhs.push(rs); } groups[sig].rhsCount++; }); // Add all LHS samples to the grouping map. lhs.forEach((ls) => { const sig = sigf(ls.metric); if (!(sig in groups)) { if (limits?.maxGroups && Object.keys(groups).length >= limits.maxGroups) { outOfLimitGroups.add(sig); return; } groups[sig] = { groupLabels: matchLabels(ls.metric, matching.on, matching.labels), lhs: [], lhsCount: 0, rhs: [], rhsCount: 0, result: [], error: null, }; } if ( !limits?.maxSeriesPerGroup || groups[sig].lhsCount < limits.maxSeriesPerGroup ) { groups[sig].lhs.push(ls); } groups[sig].lhsCount++; }); // Check for any LHS / RHS with no series and fill in default values, if specified. Object.values(groups).forEach((mg) => { if (mg.lhs.length === 0 && matching.fillValues.lhs !== null) { mg.lhs.push({ metric: mg.groupLabels, value: [0, formatPrometheusFloat(matching.fillValues.lhs as number)], filled: true, }); mg.lhsCount = 1; } if (mg.rhs.length === 0 && matching.fillValues.rhs !== null) { mg.rhs.push({ metric: mg.groupLabels, value: [0, formatPrometheusFloat(matching.fillValues.rhs as number)], filled: true, }); mg.rhsCount = 1; } }); // Annotate the match groups with errors (if any) and populate the results. Object.values(groups).forEach((mg) => { switch (matching.card) { case vectorMatchCardinality.oneToOne: if (mg.lhs.length > 1 && mg.rhs.length > 1) { mg.error = { type: MatchErrorType.multipleMatchesOnBothSides }; } else if (mg.lhs.length > 1 || mg.rhs.length > 1) { mg.error = { type: MatchErrorType.multipleMatchesForOneToOneMatching, dupeSide: mg.lhs.length > 1 ? "left" : "right", }; } break; case vectorMatchCardinality.oneToMany: case vectorMatchCardinality.manyToOne: if (mg.rhs.length > 1) { mg.error = { type: MatchErrorType.multipleMatchesOnOneSide, }; } break; case vectorMatchCardinality.manyToMany: // Should be a set operator - these don't have errors that aren't caught during parsing. if (!isSetOperator(op)) { throw new Error( "unexpected many-to-many matching for non-set operator" ); } break; default: throw new Error("unknown vector matching cardinality"); } if (mg.error) { // We don't populate results for error cases, as especially in the case of a // many-to-many matching, the cross-product output can become expensive, // and the LHS/RHS are sufficient to diagnose the matching problem. return; } if (isSetOperator(op)) { // Add LHS samples to the result, depending on specific operator condition and RHS length. mg.lhs.forEach((ls, lIdx) => { if ( (op === binaryOperatorType.and && mg.rhs.length > 0) || (op === binaryOperatorType.unless && mg.rhs.length === 0) || op === binaryOperatorType.or ) { mg.result.push({ sample: { metric: ls.metric, value: ls.value, }, manySideIdx: lIdx, }); } }); // For OR, also add all RHS samples to the result if the LHS for the group is empty. if (op === binaryOperatorType.or) { mg.rhs.forEach((rs, rIdx) => { if (mg.lhs.length === 0) { mg.result.push({ sample: { metric: rs.metric, value: rs.value, }, manySideIdx: rIdx, }); } }); } } else { // Calculate the results for this match group. mg.rhs.forEach((rs) => { mg.lhs.forEach((ls, lIdx) => { if (!ls.value || !rs.value) { // TODO: Implement native histogram support. throw new Error("native histogram support not implemented yet"); } const [vl, vr] = matching.card !== vectorMatchCardinality.oneToMany ? [ls.value[1], rs.value[1]] : [rs.value[1], ls.value[1]]; let { value, keep } = vectorElemBinop( op, parsePrometheusFloat(vl), parsePrometheusFloat(vr) ); const metric = resultMetric(ls.metric, rs.metric, op, matching); if (bool) { value = keep ? 1.0 : 0.0; delete metric.__name__; } mg.result.push({ sample: { metric: metric, value: [ ls.value[0], keep || bool ? formatPrometheusFloat(value) : filteredSampleValue, ], }, manySideIdx: lIdx, }); }); }); } }); // If we originally swapped the LHS and RHS, swap them back to the original order. if (matching.card === vectorMatchCardinality.oneToMany) { Object.keys(groups).forEach((sig) => { [groups[sig].lhs, groups[sig].rhs] = [groups[sig].rhs, groups[sig].lhs]; [groups[sig].lhsCount, groups[sig].rhsCount] = [ groups[sig].rhsCount, groups[sig].lhsCount, ]; }); } return { groups, numGroups: Object.keys(groups).length + outOfLimitGroups.size, }; };
typescript
github
https://github.com/prometheus/prometheus
web/ui/mantine-ui/src/promql/binOp.ts
import uuid from django.utils import lru_cache class IntConverter: regex = '[0-9]+' def to_python(self, value): return int(value) def to_url(self, value): return str(value) class StringConverter: regex = '[^/]+' def to_python(self, value): return value def to_url(self, value): return value class UUIDConverter: regex = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' def to_python(self, value): return uuid.UUID(value) def to_url(self, value): return str(value) class SlugConverter(StringConverter): regex = '[-a-zA-Z0-9_]+' class PathConverter(StringConverter): regex = '.+' DEFAULT_CONVERTERS = { 'int': IntConverter(), 'path': PathConverter(), 'slug': SlugConverter(), 'str': StringConverter(), 'uuid': UUIDConverter(), } REGISTERED_CONVERTERS = {} def register_converter(converter, type_name): REGISTERED_CONVERTERS[type_name] = converter() get_converters.cache_clear() @lru_cache.lru_cache(maxsize=None) def get_converters(): return {**DEFAULT_CONVERTERS, **REGISTERED_CONVERTERS} def get_converter(raw_converter): return get_converters()[raw_converter]
unknown
codeparrot/codeparrot-clean
from __future__ import unicode_literals try: # For Python 3.0 and later from urllib.error import URLError from urllib.parse import urlencode except ImportError: # Fall back to Python 2's urllib2 from urllib2 import URLError from urllib import urlencode from django.http import HttpResponseRedirect from .forms import WireForm from .. import BasicProvider, RedirectNeeded, PaymentError class WireProvider(BasicProvider): ''' Wire payment provider ''' def get_form(self, payment, data=None): if payment.status == 'waiting': payment.change_status('input') form = WireForm(data=data, hidden_inputs=False, provider=self, payment=payment) if form.is_valid(): new_status = form.cleaned_data['status'] payment.change_status(new_status) new_fraud_status = form.cleaned_data['raup_status'] payment.change_fraud_status(new_fraud_status) gateway_response = form.cleaned_data.get('gateway_response') verification_result = form.cleaned_data.get('verification_result') if gateway_response or verification_result: if gateway_response == '3ds-disabled': # Standard request without 3DSecure pass elif gateway_response == '3ds-redirect': # Simulate redirect to 3DS and get back to normal # payment processing process_url = payment.get_process_url() params = urlencode( {'verification_result': verification_result}) redirect_url = '%s?%s' % (process_url, params) raise RedirectNeeded(redirect_url) elif gateway_response == 'failure': # Gateway raises error (HTTP 500 for example) raise URLError('Opps') elif gateway_response == 'payment-error': raise PaymentError('Unsupported operation') if new_status in ['preauth', 'confirmed']: raise RedirectNeeded(payment.get_success_url()) raise RedirectNeeded(payment.get_failure_url()) return form def process_data(self, payment, request): verification_result = request.GET.get('verification_result') if verification_result: payment.change_status(verification_result) if payment.status in ['confirmed', 'preauth']: return HttpResponseRedirect(payment.get_success_url()) return HttpResponseRedirect(payment.get_failure_url()) def capture(self, payment, amount=None): payment.change_status('confirmed') return amount def release(self, payment): return None def refund(self, payment, amount=None): return amount or 0
unknown
codeparrot/codeparrot-clean
#!/usr/local/bin/python """ This script converts a subset of SVG into an HTML imagemap Note *subset*. It only handles <path> elements, for which it only pays attention to the M and L commands. Futher, it only notices the "translate" transform. It was written to generate the examples in the documentation for maphilight, and thus is very squarely aimed at handling several SVG maps from wikipedia. It *assumes* that all the <path>s it will need are inside a <g>. Any <path> outside of a <g> will be ignored. It takes several possible arguments, in the form: $ svn2imagemap.py FILENAME [x y [group1 group2 ... groupN]] FILENAME must be the name of an SVG file. All other arguments are optional. x and y, if present, are the dimensions of the image you'll be creating from the SVG. If not present, it assumes the values of the width and height attributes in the SVG file. group1 through groupN are group ids. If only want particular groups used, enter their ids here and all others will be ignored. """ import os import re import sys import xml.dom.minidom import parse_path if len(sys.argv) == 1: sys.exit("svn2imagemap.py FILENAME [x y [group1 group2 ... groupN]]") if not os.path.exists(sys.argv[1]): sys.exit("Input file does not exist") x, y, groups = None, None, None if len(sys.argv) >= 3: x = float(sys.argv[2]) y = float(sys.argv[3]) if len(sys.argv) > 3: groups = sys.argv[4:] svg_file = xml.dom.minidom.parse(sys.argv[1]) svg = svg_file.getElementsByTagName('svg')[0] raw_width = float(svg.getAttribute('width')) raw_height = float(svg.getAttribute('height')) width_ratio = x and (x / raw_width) or 1 height_ratio = y and (y / raw_height) or 1 if groups: elements = [g for g in svg.getElementsByTagName('g') if (g.hasAttribute('id') and g.getAttribute('id') in groups)] elements.extend([p for p in svg.getElementsByTagName('path') if (p.hasAttribute('id') and p.getAttribute('id') in groups)]) else: elements = svg.getElementsByTagName('g') parsed_groups = {} for e in elements: paths = [] if e.nodeName == 'g': for path in e.getElementsByTagName('path'): points = parse_path.get_points(path.getAttribute('d')) for pointset in points: paths.append([path.getAttribute('id'), pointset]) else: points = parse_path.get_points(e.getAttribute('d')) for pointset in points: paths.append([e.getAttribute('id'), pointset]) if e.hasAttribute('transform'): print e.getAttribute('id'), e.getAttribute('transform') for transform in re.findall(r'(\w+)\((-?\d+.?\d*),(-?\d+.?\d*)\)', e.getAttribute('transform')): if transform[0] == 'translate': x_shift = float(transform[1]) y_shift = float(transform[2]) for path in paths: path[1] = [(p[0] + x_shift, p[1] + y_shift) for p in path[1]] parsed_groups[e.getAttribute('id')] = paths out = [] for g in parsed_groups: for path in parsed_groups[g]: out.append('<area href="#" title="%s" shape="poly" coords="%s"></area>' % (path[0], ', '.join([("%d,%d" % (p[0]*width_ratio, p[1]*height_ratio)) for p in path[1]]))) outfile = open(sys.argv[1].replace('.svg', '.html'), 'w') outfile.write('\n'.join(out))
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import logging import os import re import time from collections import namedtuple from os import listdir from threading import Thread, Lock from odoo import http import odoo.addons.hw_proxy.controllers.main as hw_proxy _logger = logging.getLogger(__name__) DRIVER_NAME = 'scale' try: import serial except ImportError: _logger.error('Odoo module hw_scale depends on the pyserial python module') serial = None def _toledo8217StatusParse(status): """ Parse a scale's status, returning a `(weight, weight_info)` pair. """ weight, weight_info = None, None stat = ord(status[status.index('?') + 1]) if stat == 0: weight_info = 'ok' else: weight_info = [] if stat & 1 : weight_info.append('moving') if stat & 1 << 1: weight_info.append('over_capacity') if stat & 1 << 2: weight_info.append('negative') weight = 0.0 if stat & 1 << 3: weight_info.append('outside_zero_capture_range') if stat & 1 << 4: weight_info.append('center_of_zero') if stat & 1 << 5: weight_info.append('net_weight') return weight, weight_info ScaleProtocol = namedtuple( 'ScaleProtocol', "name baudrate bytesize stopbits parity timeout writeTimeout weightRegexp statusRegexp " "statusParse commandTerminator commandDelay weightDelay newWeightDelay " "weightCommand zeroCommand tareCommand clearCommand emptyAnswerValid autoResetWeight") # 8217 Mettler-Toledo (Weight-only) Protocol, as described in the scale's Service Manual. # e.g. here: https://www.manualslib.com/manual/861274/Mettler-Toledo-Viva.html?page=51#manual # Our recommended scale, the Mettler-Toledo "Ariva-S", supports this protocol on # both the USB and RS232 ports, it can be configured in the setup menu as protocol option 3. # We use the default serial protocol settings, the scale's settings can be configured in the # scale's menu anyway. Toledo8217Protocol = ScaleProtocol( name='Toledo 8217', baudrate=9600, bytesize=serial.SEVENBITS, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_EVEN, timeout=1, writeTimeout=1, weightRegexp="\x02\\s*([0-9.]+)N?\\r", statusRegexp="\x02\\s*(\\?.)\\r", statusParse=_toledo8217StatusParse, commandDelay=0.2, weightDelay=0.5, newWeightDelay=0.2, commandTerminator='', weightCommand='W', zeroCommand='Z', tareCommand='T', clearCommand='C', emptyAnswerValid=False, autoResetWeight=False, ) # The ADAM scales have their own RS232 protocol, usually documented in the scale's manual # e.g at https://www.adamequipment.com/media/docs/Print%20Publications/Manuals/PDF/AZEXTRA/AZEXTRA-UM.pdf # https://www.manualslib.com/manual/879782/Adam-Equipment-Cbd-4.html?page=32#manual # Only the baudrate and label format seem to be configurable in the AZExtra series. ADAMEquipmentProtocol = ScaleProtocol( name='Adam Equipment', baudrate=4800, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_NONE, timeout=0.2, writeTimeout=0.2, weightRegexp=r"\s*([0-9.]+)kg", # LABEL format 3 + KG in the scale settings, but Label 1/2 should work statusRegexp=None, statusParse=None, commandTerminator="\r\n", commandDelay=0.2, weightDelay=0.5, newWeightDelay=5, # AZExtra beeps every time you ask for a weight that was previously returned! # Adding an extra delay gives the operator a chance to remove the products # before the scale starts beeping. Could not find a way to disable the beeps. weightCommand='P', zeroCommand='Z', tareCommand='T', clearCommand=None, # No clear command -> Tare again emptyAnswerValid=True, # AZExtra does not answer unless a new non-zero weight has been detected autoResetWeight=True, # AZExtra will not return 0 after removing products ) SCALE_PROTOCOLS = ( Toledo8217Protocol, ADAMEquipmentProtocol, # must be listed last, as it supports no probing! ) class Scale(Thread): def __init__(self): Thread.__init__(self) self.lock = Lock() self.scalelock = Lock() self.status = {'status':'connecting', 'messages':[]} self.input_dir = '/dev/serial/by-path/' self.weight = 0 self.weight_info = 'ok' self.device = None self.path_to_scale = '' self.protocol = None def lockedstart(self): with self.lock: if not self.isAlive(): self.daemon = True self.start() def set_status(self, status, message=None): if status == self.status['status']: if message is not None and message != self.status['messages'][-1]: self.status['messages'].append(message) if status == 'error' and message: _logger.error('Scale Error: '+ message) elif status == 'disconnected' and message: _logger.warning('Disconnected Scale: '+ message) else: self.status['status'] = status if message: self.status['messages'] = [message] else: self.status['messages'] = [] if status == 'error' and message: _logger.error('Scale Error: '+ message) elif status == 'disconnected' and message: _logger.info('Disconnected Scale: %s', message) def _get_raw_response(self, connection): answer = [] while True: char = connection.read(1) # may return `bytes` or `str` if not char: break else: answer.append(char) return ''.join(answer) def _parse_weight_answer(self, protocol, answer): """ Parse a scale's answer to a weighing request, returning a `(weight, weight_info, status)` pair. """ weight, weight_info, status = None, None, None try: _logger.debug("Parsing weight [%r]", answer) if not answer and protocol.emptyAnswerValid: # Some scales do not return the same value again, but we # should not clear the weight data, POS may still be reading it return weight, weight_info, status if protocol.statusRegexp and re.search(protocol.statusRegexp, answer): # parse status to set weight_info - we'll try weighing again later weight, weight_info = protocol.statusParse(answer) else: match = re.search(protocol.weightRegexp, answer) if match: weight_text = match.group(1) try: weight = float(weight_text) _logger.info('Weight: %s', weight) except ValueError: _logger.exception("Cannot parse weight [%r]", weight_text) status = 'Invalid weight, please power-cycle the scale' else: _logger.error("Cannot parse scale answer [%r]", answer) status = 'Invalid scale answer, please power-cycle the scale' except Exception as e: _logger.exception("Cannot parse scale answer [%r]", answer) status = ("Could not weigh on scale %s with protocol %s: %s" % (self.path_to_scale, protocol.name, e)) return weight, weight_info, status def get_device(self): if self.device: return self.device with hw_proxy.rs232_lock: try: if not os.path.exists(self.input_dir): self.set_status('disconnected', 'No RS-232 device found') return None devices = [device for device in listdir(self.input_dir)] for device in devices: driver = hw_proxy.rs232_devices.get(device) if driver and driver != DRIVER_NAME: # belongs to another driver _logger.info('Ignoring %s, belongs to %s', device, driver) continue path = self.input_dir + device for protocol in SCALE_PROTOCOLS: _logger.info('Probing %s with protocol %s', path, protocol) connection = serial.Serial(path, baudrate=protocol.baudrate, bytesize=protocol.bytesize, stopbits=protocol.stopbits, parity=protocol.parity, timeout=1, # longer timeouts for probing writeTimeout=1) # longer timeouts for probing connection.write(protocol.weightCommand + protocol.commandTerminator) time.sleep(protocol.commandDelay) answer = self._get_raw_response(connection) weight, weight_info, status = self._parse_weight_answer(protocol, answer) if status: _logger.info('Probing %s: no valid answer to protocol %s', path, protocol.name) else: _logger.info('Probing %s: answer looks ok for protocol %s', path, protocol.name) self.path_to_scale = path self.protocol = protocol self.set_status( 'connected', 'Connected to %s with %s protocol' % (device, protocol.name) ) connection.timeout = protocol.timeout connection.writeTimeout = protocol.writeTimeout hw_proxy.rs232_devices[path] = DRIVER_NAME return connection self.set_status('disconnected', 'No supported RS-232 scale found') except Exception as e: _logger.exception('Failed probing for scales') self.set_status('error', 'Failed probing for scales: %s' % e) return None def get_weight(self): self.lockedstart() return self.weight def get_weight_info(self): self.lockedstart() return self.weight_info def get_status(self): self.lockedstart() return self.status def read_weight(self): with self.scalelock: p = self.protocol try: self.device.write(p.weightCommand + p.commandTerminator) time.sleep(p.commandDelay) answer = self._get_raw_response(self.device) weight, weight_info, status = self._parse_weight_answer(p, answer) if status: self.set_status('error', status) self.device = None else: if weight is not None: self.weight = weight if weight_info is not None: self.weight_info = weight_info except Exception as e: self.set_status( 'error', "Could not weigh on scale %s with protocol %s: %s" % (self.path_to_scale, p.name, e)) self.device = None def set_zero(self): with self.scalelock: if self.device: try: self.device.write(self.protocol.zeroCommand + self.protocol.commandTerminator) time.sleep(self.protocol.commandDelay) except Exception as e: self.set_status( 'error', "Could not zero scale %s with protocol %s: %s" % (self.path_to_scale, self.protocol.name, e)) self.device = None def set_tare(self): with self.scalelock: if self.device: try: self.device.write(self.protocol.tareCommand + self.protocol.commandTerminator) time.sleep(self.protocol.commandDelay) except Exception as e: self.set_status( 'error', "Could not tare scale %s with protocol %s: %s" % (self.path_to_scale, self.protocol.name, e)) self.device = None def clear_tare(self): with self.scalelock: if self.device: p = self.protocol try: # if the protocol has no clear, we can just tare again clearCommand = p.clearCommand or p.tareCommand self.device.write(clearCommand + p.commandTerminator) time.sleep(p.commandDelay) except Exception as e: self.set_status( 'error', "Could not clear tare on scale %s with protocol %s: %s" % (self.path_to_scale, p.name, e)) self.device = None def run(self): self.device = None while True: if self.device: old_weight = self.weight self.read_weight() if self.weight != old_weight: _logger.info('New Weight: %s, sleeping %ss', self.weight, self.protocol.newWeightDelay) time.sleep(self.protocol.newWeightDelay) if self.weight and self.protocol.autoResetWeight: self.weight = 0 else: _logger.info('Weight: %s, sleeping %ss', self.weight, self.protocol.weightDelay) time.sleep(self.protocol.weightDelay) else: with self.scalelock: self.device = self.get_device() if not self.device: # retry later to support "plug and play" time.sleep(10) scale_thread = None if serial: scale_thread = Scale() hw_proxy.drivers[DRIVER_NAME] = scale_thread class ScaleDriver(hw_proxy.Proxy): @http.route('/hw_proxy/scale_read/', type='json', auth='none', cors='*') def scale_read(self): if scale_thread: return {'weight': scale_thread.get_weight(), 'unit': 'kg', 'info': scale_thread.get_weight_info()} return None @http.route('/hw_proxy/scale_zero/', type='json', auth='none', cors='*') def scale_zero(self): if scale_thread: scale_thread.set_zero() return True @http.route('/hw_proxy/scale_tare/', type='json', auth='none', cors='*') def scale_tare(self): if scale_thread: scale_thread.set_tare() return True @http.route('/hw_proxy/scale_clear_tare/', type='json', auth='none', cors='*') def scale_clear_tare(self): if scale_thread: scale_thread.clear_tare() return True
unknown
codeparrot/codeparrot-clean
# Load the AlchemyAPI module code. import AlchemyAPI # Create an AlchemyAPI object. alchemyObj = AlchemyAPI.AlchemyAPI() # Load the API key from disk. alchemyObj.loadAPIKey("api_key.txt"); ''' # Extract a title from a web URL. result = alchemyObj.URLGetTitle("http://www.techcrunch.com/"); print result ''' # Extract page text from a web URL (ignoring navigation links, ads, etc.). result = alchemyObj.URLGetText("http://www.reuters.com/article/2012/11/30/us-china-apple-iphone-idUSBRE8AT06G20121130?type=companyNews"); print result ''' # Extract raw page text from a web URL (including navigation links, ads, etc.). result = alchemyObj.URLGetRawText("http://www.techcrunch.com/"); print result # Load a HTML document to analyze. htmlFileHandle = open("data/example.html", 'r') htmlFile = htmlFileHandle.read() htmlFileHandle.close() # Extract a title from a HTML document. result = alchemyObj.HTMLGetTitle(htmlFile, "http://www.test.com/"); print result # Extract page text from a HTML document (ignoring navigation links, ads, etc.). result = alchemyObj.HTMLGetText(htmlFile, "http://www.reuters.com/article/2012/11/30/us-china-apple-iphone-idUSBRE8AT06G20121130?type=companyNews"); print result # Extract raw page text from a HTML document (including navigation links, ads, etc.). result = alchemyObj.HTMLGetRawText(htmlFile, "http://www.test.com/"); print result '''
unknown
codeparrot/codeparrot-clean
/* * Copyright (C) 2012 The Guava Authors * * 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. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkState; import static java.util.Collections.synchronizedSet; import static java.util.Collections.unmodifiableSet; import com.google.common.base.Equivalence; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import org.jspecify.annotations.NullUnmarked; /** * Helper classes for various benchmarks. * * @author Christopher Swenson */ @NullUnmarked final class BenchmarkHelpers { /** So far, this is the best way to test various implementations of {@link Set} subclasses. */ public interface CollectionsImplEnum { <E extends Comparable<E>> Collection<E> create(Collection<E> contents); String name(); } public interface MapsImplEnum { <K extends Comparable<K>, V> Map<K, V> create(Map<K, V> contents); String name(); } public interface InternerImplEnum { <E> Interner<E> create(Collection<E> contents); String name(); } public enum SetImpl implements CollectionsImplEnum { HashSetImpl { @Override public <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return new HashSet<E>(contents); } }, LinkedHashSetImpl { @Override public <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return new LinkedHashSet<E>(contents); } }, TreeSetImpl { @Override public <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return new TreeSet<E>(contents); } }, UnmodifiableSetImpl { @Override public <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return unmodifiableSet(new HashSet<E>(contents)); } }, SynchronizedSetImpl { @Override public <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return synchronizedSet(new HashSet<E>(contents)); } }, ImmutableSetImpl { @Override public <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return ImmutableSet.copyOf(contents); } }, ImmutableSortedSetImpl { @Override public <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return ImmutableSortedSet.copyOf(contents); } }, ContiguousSetImpl { @Override public <E extends Comparable<E>> Set<E> create(Collection<E> contents) { return ContiguousSet.copyOf(contents); } }, ; } public enum ListMultimapImpl { ArrayListMultimapImpl { @Override <K, V> ListMultimap<K, V> create(Multimap<K, V> contents) { return ArrayListMultimap.create(contents); } }, LinkedListMultimapImpl { @Override <K, V> ListMultimap<K, V> create(Multimap<K, V> contents) { return LinkedListMultimap.create(contents); } }, ImmutableListMultimapImpl { @Override <K, V> ListMultimap<K, V> create(Multimap<K, V> contents) { return ImmutableListMultimap.copyOf(contents); } }; abstract <K, V> ListMultimap<K, V> create(Multimap<K, V> contents); } public enum RangeSetImpl { TreeRangeSetImpl { @Override <K extends Comparable<K>> RangeSet<K> create(RangeSet<K> contents) { return TreeRangeSet.create(contents); } }, ImmutableRangeSetImpl { @Override <K extends Comparable<K>> RangeSet<K> create(RangeSet<K> contents) { return ImmutableRangeSet.copyOf(contents); } }; abstract <K extends Comparable<K>> RangeSet<K> create(RangeSet<K> contents); } public enum SetMultimapImpl { HashMultimapImpl { @Override <K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create( Multimap<K, V> contents) { return HashMultimap.create(contents); } }, LinkedHashMultimapImpl { @Override <K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create( Multimap<K, V> contents) { return LinkedHashMultimap.create(contents); } }, TreeMultimapImpl { @Override <K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create( Multimap<K, V> contents) { return TreeMultimap.create(contents); } }, ImmutableSetMultimapImpl { @Override <K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create( Multimap<K, V> contents) { return ImmutableSetMultimap.copyOf(contents); } }; abstract <K extends Comparable<K>, V extends Comparable<V>> SetMultimap<K, V> create( Multimap<K, V> contents); } public enum MapImpl implements MapsImplEnum { HashMapImpl { @Override public <K extends Comparable<K>, V> Map<K, V> create(Map<K, V> map) { return new HashMap<>(map); } }, LinkedHashMapImpl { @Override public <K extends Comparable<K>, V> Map<K, V> create(Map<K, V> map) { return new LinkedHashMap<>(map); } }, ConcurrentHashMapImpl { @Override public <K extends Comparable<K>, V> Map<K, V> create(Map<K, V> map) { return new ConcurrentHashMap<>(map); } }, ImmutableMapImpl { @Override public <K extends Comparable<K>, V> Map<K, V> create(Map<K, V> map) { return ImmutableMap.copyOf(map); } }, MapMakerStrongKeysStrongValues { @Override public <K extends Comparable<K>, V> Map<K, V> create(Map<K, V> map) { // We use a "custom" equivalence to force MapMaker to make a MapMakerInternalMap. ConcurrentMap<K, V> newMap = new MapMaker().keyEquivalence(Equivalence.equals()).makeMap(); checkState(newMap instanceof MapMakerInternalMap); newMap.putAll(map); return newMap; } }, MapMakerStrongKeysWeakValues { @Override public <K extends Comparable<K>, V> Map<K, V> create(Map<K, V> map) { ConcurrentMap<K, V> newMap = new MapMaker().weakValues().makeMap(); checkState(newMap instanceof MapMakerInternalMap); newMap.putAll(map); return newMap; } }, MapMakerWeakKeysStrongValues { @Override public <K extends Comparable<K>, V> Map<K, V> create(Map<K, V> map) { ConcurrentMap<K, V> newMap = new MapMaker().weakKeys().makeMap(); checkState(newMap instanceof MapMakerInternalMap); newMap.putAll(map); return newMap; } }, MapMakerWeakKeysWeakValues { @Override public <K extends Comparable<K>, V> Map<K, V> create(Map<K, V> map) { ConcurrentMap<K, V> newMap = new MapMaker().weakKeys().weakValues().makeMap(); checkState(newMap instanceof MapMakerInternalMap); newMap.putAll(map); return newMap; } }; } enum SortedMapImpl implements MapsImplEnum { TreeMapImpl { @Override public <K extends Comparable<K>, V> SortedMap<K, V> create(Map<K, V> map) { SortedMap<K, V> result = Maps.newTreeMap(); result.putAll(map); return result; } }, ConcurrentSkipListImpl { @Override public <K extends Comparable<K>, V> SortedMap<K, V> create(Map<K, V> map) { return new ConcurrentSkipListMap<>(map); } }, ImmutableSortedMapImpl { @Override public <K extends Comparable<K>, V> SortedMap<K, V> create(Map<K, V> map) { return ImmutableSortedMap.copyOf(map); } }; } enum BiMapImpl implements MapsImplEnum { HashBiMapImpl { @Override public <K extends Comparable<K>, V> BiMap<K, V> create(Map<K, V> map) { return HashBiMap.create(map); } }, ImmutableBiMapImpl { @Override public <K extends Comparable<K>, V> BiMap<K, V> create(Map<K, V> map) { return ImmutableBiMap.copyOf(map); } }; @Override public abstract <K extends Comparable<K>, V> BiMap<K, V> create(Map<K, V> map); } enum MultisetImpl implements CollectionsImplEnum { HashMultisetImpl { @Override public <E extends Comparable<E>> Multiset<E> create(Collection<E> contents) { return HashMultiset.create(contents); } }, LinkedHashMultisetImpl { @Override public <E extends Comparable<E>> Multiset<E> create(Collection<E> contents) { return LinkedHashMultiset.create(contents); } }, ConcurrentHashMultisetImpl { @Override public <E extends Comparable<E>> Multiset<E> create(Collection<E> contents) { return ConcurrentHashMultiset.create(contents); } }, ImmutableMultisetImpl { @Override public <E extends Comparable<E>> Multiset<E> create(Collection<E> contents) { return ImmutableMultiset.copyOf(contents); } }; } enum SortedMultisetImpl implements CollectionsImplEnum { TreeMultisetImpl { @Override public <E extends Comparable<E>> SortedMultiset<E> create(Collection<E> contents) { return TreeMultiset.create(contents); } }, ImmutableSortedMultisetImpl { @Override public <E extends Comparable<E>> SortedMultiset<E> create(Collection<E> contents) { return ImmutableSortedMultiset.copyOf(contents); } }; } enum QueueImpl implements CollectionsImplEnum { MinMaxPriorityQueueImpl { @Override public <E extends Comparable<E>> Queue<E> create(Collection<E> contents) { return MinMaxPriorityQueue.create(contents); } }; } enum TableImpl { HashBasedTableImpl { @Override <R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create( Table<R, C, V> contents) { return HashBasedTable.create(contents); } }, TreeBasedTableImpl { @Override <R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create( Table<R, C, V> contents) { Table<R, C, V> table = TreeBasedTable.create(); table.putAll(contents); return table; } }, ArrayTableImpl { @Override <R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create( Table<R, C, V> contents) { if (contents.isEmpty()) { return ImmutableTable.of(); } else { return ArrayTable.create(contents); } } }, ImmutableTableImpl { @Override <R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create( Table<R, C, V> contents) { return ImmutableTable.copyOf(contents); } }; abstract <R extends Comparable<R>, C extends Comparable<C>, V> Table<R, C, V> create( Table<R, C, V> contents); } public enum InternerImpl implements InternerImplEnum { WeakInternerImpl { @Override public <E> Interner<E> create(Collection<E> contents) { Interner<E> interner = Interners.newWeakInterner(); for (E e : contents) { E unused = interner.intern(e); } return interner; } }, StrongInternerImpl { @Override public <E> Interner<E> create(Collection<E> contents) { Interner<E> interner = Interners.newStrongInterner(); for (E e : contents) { E unused = interner.intern(e); } return interner; } }; } public enum Value { INSTANCE; } public enum ListSizeDistribution { UNIFORM_0_TO_2(0, 2), UNIFORM_0_TO_9(0, 9), ALWAYS_0(0, 0), ALWAYS_10(10, 10); final int min; final int max; ListSizeDistribution(int min, int max) { this.min = min; this.max = max; } public int chooseSize(Random random) { return random.nextInt(max - min + 1) + min; } } private BenchmarkHelpers() {} }
java
github
https://github.com/google/guava
android/guava-tests/test/com/google/common/collect/BenchmarkHelpers.java
- Feature Name: Workload Level Index Recommendation - Status: draft - Start Date: 2023-06-05 - Authors: Aiden He - RFC PR: (PR # after acceptance of initial draft) - Cockroach Issue: # Summary This document is about the “workload level index recommendation”. As introduced in [Index Recommendation Engine](https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/20211112_index_recommendation.md), CockroachDB has already enabled single statement recommendations. But it is limited in the scope of that single statement. When we want to build a bunch of indexes to optimize the whole workload, it will not be a good idea to create or drop indexes according to the index recommendations for all sql statements in that workload. Since there must be many overlapped indexes, some of them may be contained by other indexes. The workload level index recommendations will be done by collecting the previous indexes recommendations and then using the finding coverage algorithm to extract a small subset of indexes. The impact of this project is boosting the workload efficiency without too much space and time cost. # Motivation Audience: PMs, end-users, CockroachDB team members. The motivation is to enhance the index recommendation engine with considering all the other statements in the same workload. Adding certain indexes can have drastic impacts on the performance of a query, but adding overlapped indexes or adding indexes included by other indexes will waste time and space with ineligible benefits. Workload level index recommendation will only contain those representative indexes with little or nearly empty overlap, meaning that this project could improve query performance without too much cost. # Technical design Audience: CockroachDB team members, expert users. For the existing index recommendation engine, the general idea is collecting an index set that could improve performance and then using the optimizer to determine the best one. Similarly, we also split the whole process into two parts, finding index candidates and extracting the most valuable representatives. As for the workload level, the existing insight system run in the background can only find those costly queries and provide index recommendations for that query. Thus, it is incapable of finding shared indexes among many queries. This project is aimed to make full use of the shared parts to recommend space efficient and effective indexes. The input and output become an array of sql statements instead of one. Besides those sql statements, user can specify the time range (e.g. last 6 hours, last 2 weeks) they want to optimize the workload and the budget they can afford (e.g. 15GB, 500MB, 1TB). We can filter from the candidates source correspondingly or find smaller indexes to use. The details will be covered in the UI section. Since partial indexes, inverted indexes, or hash-sharded indexes are not similar to the regular indexes, it is hard to deal with them together, the algorithm below will only cover regular indexes. There 3 kinds of index recommendations for regular indexes: ```sql 1. CREATE INDEX ON ... (CREATE) 2. CREATE INDEX ... DROP INDEX ... (REPLACE) 3. ALTER INDEX ... (ALTER) ``` The `ALTER INDEX` is used if there exists a suitable invisible index. Its underlying content is another `CREATE INDEX …`. Thus, we can categorize all the index recommendations into two types: `CREATE INDEX …` and `DROP INDEX …` (splitting the `REPLACE` type into two parts). Let us consider all the `CREATE INDEX …` at first. ## Find index candidates In the background, there is a cache for index recommendations, then the cache will be saved to in-memory tables, next it will be flushed to the system tables `system.statement_statistics`. To begin with, we can collect all the index recommendations (with time filter if necessary) from this table and use them as an index candidate set since they are the optimal ones chosen by the optimizer before. All of them are represented as a sql statement. Finally, we will get an array of sql statements. As for the cache mentioned before, there is a space limit for all the index recommendations. Thus, all the index recommendations stored in that cache is from those sql statements run frequently and recently. You can check the detailed requirement in the method [`pkg.sql.idxrecommendations.idx_recommendations_cache.ShouldGenerateIndexRecommendation()`](https://github.com/cockroachdb/cockroach/blob/master/pkg/sql/idxrecommendations/idx_recommendations_cache.go#L77). Meanwhile, it will also clear those index recommendations which was not used for more than one day in method [`pkg.sql.idxrecommendations.idx_recommendations_cache.clearOldIdxRecommendations()`](https://github.com/cockroachdb/cockroach/blob/master/pkg/sql/idxrecommendations/idx_recommendations_cache.go#L239). Thus, all the index recommendations we select from the table `system.statement_statistics` are those which are run more frequently and are crucial for the performance. ## Extracting valuable index representatives All the examples below is based on the table `t(i INT, j INT, k INT)`. `CREATE`-based index recommendations has two forms: ```sql CREATE INDEX ON t(i, j) CREATE INDEX ON t(i) STORING (j) ``` The first one creates indexes on all the columns (i, j) involved. The second one creates index only on column i but storing column j, meaning there is no order guarantee on column j. ### Indexed Columns Without considering the storing part, all the indexes can be represented by a list of ordered columns. Since the order matters a lot, finding their similarities is just like comparing the prefix among strings. Consider the following index candidates: ```sql 1. CREATE INDEX ON t(i) 2. CREATE INDEX ON t(i, j) 3. CREATE INDEX ON t(j) ``` For thees 3 indexes, we can regard them as strings i, ij, j, then let us build a trie tree for them associated with table `t`, all the `t` below means the trie tree is built for table `t`, you can regard it as an empty root for indexes: ``` t / \ j i | j ``` As you can find that, the first index `(i)` is completely contained by the second one `(i, j)`, in order to cover all the indexes, we only need to build indexes `(j)` and `(i, j)`. One interesting thing we can find is that they are all the leaf nodes for this trie tree. According to the definition of trie, any string represented by the leaf node covers all the strings represented by any nodes in the path from the leaf node to the root. Therefore, the initial idea for finding representative indexes are selecting all the indexes corresponding to the leaf nodes. The algorithm above works only when the space and time cost is not that constrained. Further optimization will be covered later. ### Stored columns As for the storing part, it becomes tricky, since the order of storing does not matter. Let us consider the following index: ``` 4. CREATE INDEX ON t(i) storing (j) ``` After inserting the indexed columns to the trie tree and keep the storing part, the tree is like: ``` t / \ j i store (j) | j ``` Then, for the node `i store (j)`, there will be two cases for the storing part depending on whether we can find a path from a leaf node to the current node in its subtree covering the storing part (it means some existing indexes chosen before has already covered the storing part). If we can find, just like the case for the 4th index in the example, then we do not need to add an extra index for the storing part since index `(i, j)` will cover the need for index `(i) storing (j)`. To check whether the storing part of one internal one is covered by some leaf nodes, we will exhaustively search all the leaf nodes inside the subtree of the that node, if we find it, we will remove the storing part of the node (see "Extracting valuable index representatives" under "Future work" for further optimization). Otherwise, let us consider the indexes as follows: ```sql 5. CREATE INDEX ON t(j) storing (i) 6. CREATE INDEX ON t(j, k) ``` Insert them to the trie, we can get: ``` t / \ i store (j) j store (i) | | j k ``` There is no path covering the storing (i) for the right node `j store (i)` in the first level since it has only one leaf node `k`, so we need to add an extra index to store it or store it in an existing index. Storing it to an existing index is more efficient due to the implementation of key-value layer (will be covered in References). As for existing indexes, not to make the large index larger, the storing part will be added to the shallowest leaf node (which is more likely to be the smallest index) in the `j store (i)`'s subtree (under t, not the leaf node). In our example, there is only one leaf node for node `j store (i)`, thus i will be stored there (the leaf node `k`). To sum up, for the index 1-6, we will build indexes `(i, j)` and `(j, k) storing (i)`. Now that we have discussed the cases for one storing part per node, when there are multiple storing parts, we can merge them in advance and then treat them as one storing part, think about the following indexes: ```sql 7. CREATE INDEX ON t(k) 8. CREATE INDEX ON t(k) storing (i) 9. CREATE INDEX ON t(k) storing (j) ``` The trie tree will become: ``` t / | \ i store (j) j store (i) k store (i); store (j) | | j k ``` Thus, it is straightforward to think about merging all the storings. In this example, i and j will be stored with index `(k)`. In total, we will merge all the storing parts in one node and find the shallowest leaf node to put them if there is no covering path is found. Next I will explain why we use this simple idea. First of all, the space cost of putting them together storing in one leaf one and splitting them into multiple groups and storing them in multiple leaf nodes is almost the same. Next, if we accidentally split the storing part of one original index into two, then the corresponding query cannot be optimized. In addition, we do not want to make the index too large (the size of key and value). Thus, we decide to merge all the storing parts in one node together and put them in one leaf node, the shallowest one. To sum up, we build a trie tree on the indexed columns from previous index recommendations and attach the storing parts to each tree node. Then, select all the leaf nodes to build representative indexes. For each node with attached storing parts, they will be merged. Next, if we do not find a path from the one node to the leaf node in its subtree, meaning that there does not exist an index storing all the columns we need, then we will choose the shallowest leaf nodes to mount all the storing columns. ## Drop index Let us consider all the `DROP INDEX` for the next step. It only exists in the index recommendation for replace where the index to drop shares the same index columns as the index to create, but the storing columns is a subset compared to the index to create. If we think about it from the perspective of trie tree, all the dropped indexes are covered by all the indexes represented by the leaf nodes. Therefore, we can drop all the `Drop`-based indexes. ## User Interface ### How to use Initially, several built-in function will be provided command line interface. `workload_index_recs`, `workload_index_recs(timestamp)`, `workload_index_recs(budget)`, and `workload_index_recs(timestamp, budget)`. User can enter `SELECT workload_index_recs();`, then they will see the workload level index recommendations. For the parameter, the type of the `timestamp` can be TIMESTAMP/TIMESTAMPZ. We will use it as a filter and only consider those indexes after the timestamp from the table `system.statement_statistics`. The `budget` is a string like "15GB", "500MB", "1TB" meaning the space the user can afford so that we will apply some algorithm to reduce the space cost, you can find details in the cost optimization section later. ### Insight delivered to users Since we have the statistics for the frequency about the queries, so that we can deliver the "impact" for each index, like, the number of fingerprints, the number of executions (some fingerprint may be executed many times). In addition, we can also deliver the space cost for all the index recommendations. For the command line interface (CLI), we show all the index recommendations in the descending order of the number of executions one can optimize by default. In the future, we can deliver more information, e.g. all the fingerprints one index can optimize and the trie tree to represent the relationship among indexes. It will be too overwhelming to deliver too much statistics in CLI. But we will still provide built-in functions `workload_index_recs_with_insights()` which returns an array of strings (representing the index recommendation) and jsons containing all the statistics for each index recommendation. It will be used for DBConsole or debugging purposes. ## Future work ### Find index candidates All the index recommendation candidates collected from the table `system.statement_statistics` are out of date since they are generated before, the data may change after that, meaning the optimal index chosen by the optimizer (those we collect) may not the optimal one. To get a wider range of index recommendation candidates, we can collect index candidates from the raw sql statements stored by the `sql.opt.indexrec.FindIndexCandidateSet()`. Then, use this much larger set of candidates to find representative indexes to optimize the workload. In this way, since the exploring range becomes much larger, the potential results should be better, but at the expense of time and space consuming. One idea to deal with it is issue two level workload index recommendations. The first one is a lightweight one using the idea collecting existing index recommendations as candidates running comparatively frequent, the other one using the idea above running less often. ### Extracting valuable index representatives Whether attaching all the storing columns to the shallowest leaf node is the optimal solution remains controversial. As you can see in the example below: ``` t | i store (j, k) / \ j store (k) k ``` The optimal solution should be indexes `(i, j) storing (k)` and `(i, k)`. If we assign storing columns `(j, k)` to the right leaf node since the left and right leaf nodes are in the same level, then the output will be indexes `(i, j) storing (k)` and `(i, k) storing (j)`, which is a suboptimal solution. If we attach them to the left child, that will lead to the optimal result. One potential answer for this question is that we can compare the storing parts in the internal node with the path from the current node to its leaf nodes. But the statistics we need to keep while traversing the tree is too overwhelming. If we prefer a lightweight method, we can convert this problem to deciding which child node to push down the storing columns of one internal node so that we can merge the storing parts with the one in the child node. But there remain some problems. If we push them down too shallowly, there may be more opportunities to share more storing parts among indexes. Otherwise, we may add it to a very large leaf node index, which may make the optimization not that obvious since visiting a large index is costly if we only want few columns. Another problem is whether we need to merging all the storing parts originally from different index candidates in one tree. Think about the example as follows: ``` t | i store (j, l); store (k, l) / \ j k | | l l ``` If we merge them together, the storing part becomes `(j, k, l)` for the node in the first level, then there is no leaf node that can cover them. Then we will assign them to one of the two leaf nodes since they are at the same level. The final output of the algorithm will be indexes `(i, j, l) storing (k)` and `(i, k, l)`, or `(i, j, l)` and `(i, k, l) storing (j)`. However, the optimal solution should be `(i, j, l)` and `(i, k, l)` if we do not merge the storing parts from different original indexes since `store (j, l)` is covered by `(i, j, l)` and `store (k, l)` is covered by `(i, k, l)`. Nevertheless, it will cost more space if not merging. Thus, whether merging the storing parts from different original indexes is a trade-off between space cost and the quality of the final index recommendations. I suggest that we can keep a counter for the number of original indexes of the storing part from a node. If it exceeds a limit, we will merge them to save space and time for finding covering leaf nodes. Otherwise, we can deal with them one by one. ### Cost optimization The second point is for further optimization. If we do not have enough time or space budget to support all the leaf node indexes, what should we do? Along the idea of trie tree, we can use some internal node to build index, here is one example: ``` t | k / \ i j ``` We can build a index `(k)` instead of two `(k, i)` and `(k, j)` but still get a good performance. The idea behind is merging leaf nodes. As for the example above of two leaf nodes, we can find the [lowest common ancestor (LCA)](https://en.wikipedia.org/wiki/Lowest_common_ancestor) to represent them, since we reduce the number of indexes by 1 and keep the longest share between them. If we need to merge more than two indexes, we can borrow the idea from [Huffman coding](https://en.wikipedia.org/wiki/Huffman_coding), each time we merge the most expensive index with its nearest indexes (may from the leaf node or internal node) and then repeat this process until the budget satisfied. Just like the example above, we merge the indexes `(k, i)` and `(k, j)` to `(k)`. If there is no sharing between existing indexes, we can get rid of those expensive one. Another choice is to eliminate the storing parts. In order to complete the algorithm above, we need to think of some objective function to estimate the cost for different indexes based on the number of indexed columns, the number of storing columns, different types of columns, usage in the whole workload, etc. Besides those space cost, the mutation cost should also be considered, the larger the index, the more time consuming the mutations. As mentioned in the finding index candidates, the frequency is an important aspect we should pay attention to, in `system.statement_statistics`, there is a column called `statistics` containing the times of on a type of query has been executed, we can use this to assign a weight for each node in the tree so that the merging algorithm will cover the importance of the indexes (by frequency). If we collect from the raw sql statements mentioned in the future work, we can re-compute the frequency from scratch and use such more precise information to assign the weight. ## Drop index As for the `DROP INDEX`, since we select all the leaf nodes before, so we can directly drop them without hesitation (covered by all the leaf nodes). Nevertheless, we only select some internal nodes to build indexes when we need to merge some leaf nodes for cost optimization so that not everything in the tree is covered, meaning that some dropped indexes are not covered by the indexes selected to create. Since the space and time budget is confined, we can also take dropping indexes into account, the cost function can be used to calculate the space released by dropping one index. Following the idea of the trie tree, we can add all the indexes to drop to the tree. When we decide to merge two indexes, there may exist some indexes to drop along the paths to their LCA, when we compute the space to save, we can minus those space occupied by the indexes to drop since we can't cover them once we merge these two indexes. Thus, our merging process will be more comprehensive. ## Rationale and alternatives ### OrderingChoice [OrderingChoice](https://github.com/cockroachdb/cockroach/blob/1a339b712842a768d48bf658fa00c3f5af7b02bb/pkg/sql/opt/props/ordering_choice.go) is a struct implemented in CRDB to define the set of possible row orderings that are provided or required by an operator. If we consider about using it for workload index recommendations (as a replacement as index representation consisting of indexed columns and storing columns), there are some useful method implmented in the OrderingChoice: 1. The `Columns` defined in OrderingChoice specify an order for columns involved, similar to the indexed columns in index representation. 2. There are some useful methods implemented in OrderingChoice, like [Intersection](https://github.com/cockroachdb/cockroach/blob/1a339b712842a768d48bf658fa00c3f5af7b02bb/pkg/sql/opt/props/ordering_choice.go#L375), [CommonPrefix](https://github.com/cockroachdb/cockroach/blob/1a339b712842a768d48bf658fa00c3f5af7b02bb/pkg/sql/opt/props/ordering_choice.go#L463), [PrefixIntersection](https://github.com/cockroachdb/cockroach/blob/1a339b712842a768d48bf658fa00c3f5af7b02bb/pkg/sql/opt/props/ordering_choice.go#L851), [Implies](https://github.com/cockroachdb/cockroach/blob/1a339b712842a768d48bf658fa00c3f5af7b02bb/pkg/sql/opt/props/ordering_choice.go#L289). They can be used to find shared part of indexed columns, judge whether two indexed columns are mergeable. But there are also some limitations: 1. Even if the each ordering slot in OrderingChoice can represent multiple options, e.g. `(a|b)` means we can order by column a or column b in this slot. But it cannot represente multiple options for a list of columns. Like the example below: `SELECT * FROM t WHERE a = 1 AND b = 2`. The two index candidates will be `(a, b)` and `(b, a)`. A single OrderingChoice cannot represent them. `(a|b)`, `(a|b)` is not a valid answer since it can also represent `(b, b)` and `(a, a)`. We cannot specify any dependency between the two slots (we must pick `b` in the second slot if `a` is picked by the first slot). Thus, the expressiveness of OrderingChoice is very limited for index representation. 2. The other drawback is the `Optional` which represents a set of optional columns that can be put anywhere or not put them in the final order, e.g. `+1 opt(2)` represents `(1, 2)` and `(2, 1)` and `(1)`. As for the indexes, it is ok that one column can be put among a range, just like the previous example, both `(a, b)` or `(b, a)` work. However, it is very seldom that one column can be put anywhere which means the `Optional` is not that usefull for index representation. Consider these large limitaions and not that many useful methods, we decide not to use the OrderingChoice for workload level index recommendations. ### Partial Order As introduced by the paper [AIM](https://research.facebook.com/micro_site/url/?click_from_context_menu=true&country=US&destination=https%3A%2F%2Fresearch.facebook.com%2Ffile%2F215595724407039%2FAIM_SRT_Update.pdf&event_type=click&last_nav_impression_id=049WEwN9gpSINlkGu&max_percent_page_viewed=37&max_viewport_height_px=758&max_viewport_width_px=1369&orig_request_uri=https%3A%2F%2Fresearch.facebook.com%2Fpublications%2Faim-a-practical-approach-to-automated-index-management-for-sql-databases%2F&region=noam&scrolled=true&session_id=0SECykrURLuPBYYoo&site=mc_research), the partial order shows its expressness in index representation. `({a, b})` is an partial order that simultaneously represents both `(a, b)` and `(b, a)`, offering a compact form of index representation. However, this brevity comes at a cost - a more complex, time-intensive merging process. As discussed in the section III.E of the paper, the merging rule is intricate. The whole problem will not be modeled as a trie based merging problem but a knapsack problem (proposed in section III.F of AIM). Another consideration is that CRDB currently does not support partial order-based index representation. It necessitates a final, defined order for all columns participating in the index. There are ideas outlined in the paper AIM, such as ordering columns by selectivity, that could serve as potential solutions. Consider the scenarios that we only store the fingerprint without constants, deciding on the order becomes increasingly challenging. In summary, while partial orders might present a more robust method of index representation, they also demand substantial future development and refinement. # References ## KV layer representations for indexes Generally, key representation for the index is `/tableID/indexID/indexColumns.../primaryKey`, the value will be `[/StoreColumns]`. Suppose there are 3 tuples inserted to the table `t`: `{4, 5, 6}, {7, 8, 9}, {10, 11, 12}` and i is the primary key. If we create the following index: ```sql CREATE INDEX ON t(j, k) ``` Assume the tableID is 1 and the indexID is also 2. The key-value pairs for this index will be: | Key | Value | |---------------|-------| | /1/2/5/6/4 | Ø | | /1/2/8/9/7 | Ø | | /1/2/11/12/10 | Ø | As for an index with storing: ```sql CREATE INDEX ON t(j) storing (k) ``` Assume the indexID is 3. The key-value pairs are: | Key | Value | |------------|-------| | /1/3/5/4 | 6 | | /1/3/8/7 | 9 | | /1/3/11/10 | 12 | As you can see, the storage cost for the two indexes above are almost the same, but since the SSTable is ordered by the key, thus longer key may cost more. For the question about adding an extra index to store the storing part or attaching them to an existing index, the answer should be the latter one since adding an extra index means adding the tableID, indexID, indexColumns again. What is more, adding more keys means higher search latency, thus attaching them to an existing index is a better idea. For the question about storing the storing part of one node on multiple leaf nodes or one leaf node, the answer should be one leaf node, adding one storing column to the index just means adding it to the value, thus the space cost for these two methods are almost the same, but storing all of them in one leaf node will decrease the number of vists for kv stores, thus that will be a efficiency improvement.
unknown
github
https://github.com/cockroachdb/cockroach
docs/RFCS/20230605_workload_level_index_recommendation.md
# -*- coding: utf-8 -*- """ *==LICENSE==* CyanWorlds.com Engine - MMOG client, server and tools Copyright (C) 2011 Cyan Worlds, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Additional permissions under GNU GPL version 3 section 7 If you modify this Program, or any covered work, by linking or combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK, NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK (or a modified version of those libraries), containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA, PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the licensors of this Program grant you additional permission to convey the resulting work. Corresponding Source for a non-source form of such a combination shall include the source code for the parts of OpenSSL and IJG JPEG Library used as well as that of the covered work. You can contact Cyan Worlds, Inc. by email legal@cyan.com or by snail mail at: Cyan Worlds, Inc. 14617 N Newport Hwy Mead, WA 99021 *==LICENSE==* """ MaxVersionNumber = 58 MinorVersionNumber = 52 # Plasma engine. from Plasma import * from PlasmaTypes import * from PlasmaKITypes import * from PlasmaConstants import * from PlasmaVaultConstants import * from PlasmaNetConstants import * import time import string import xCensor import xLinkingBookDefs import xBookGUIs import re # Used for CoD Fix. import os # Used for saving pictures locally. import glob # Used for saving pictures locally. import math import xLocTools import xEnum # Personal age SDL helper. from xPsnlVaultSDL import * # Jalak constants. from jlakConstants import * # xKI sub-modules. import xKIExtChatCommands import xKIChat from xKIConstants import * from xKIHelpers import * # Marker Game thingies import xMarkerMgr # Define the attributes that will be entered in Max. KIBlackbar = ptAttribGUIDialog(1, "The Blackbar dialog") xKIChat.KIBlackbar = KIBlackbar KIMini = ptAttribGUIDialog(2, "The KIMini dialog") xKIChat.KIMini = KIMini KIYesNo = ptAttribGUIDialog(3, "The KIYesNo dialog") BigKI = ptAttribGUIDialog(5, "The BigKI (Mr. BigStuff)") xKIChat.BigKI = BigKI NewItemAlert = ptAttribGUIDialog(7, "The new item alert dialog") KIListModeDialog = ptAttribGUIDialog(9, "The list mode dialog") KIPictureExpanded = ptAttribGUIDialog(10, "The Picture expanded dialog") KIJournalExpanded = ptAttribGUIDialog(11, "The journal entry expanded dialog") KIOnAnim = ptAttribAnimation(12, "Turn on/off the KI on animation") KIOnResp = ptAttribResponder(13, "Turn On responder") KIOffResp = ptAttribResponder(14, "Turn Off responder") KIPlayerExpanded = ptAttribGUIDialog(17, "The player expanded dialog") KIMicroBlackbar = ptAttribGUIDialog(18, "The micro Blackbar dialog") KIMicro = ptAttribGUIDialog(19, "The micro KI dialog") xKIChat.KIMicro = KIMicro KIVolumeExpanded = ptAttribGUIDialog(21, "The volume control dialog") KIAgeOwnerExpanded = ptAttribGUIDialog(22, "The Age Owner settings dialog") # Disabled: KIRateIt = ptAttribGUIDialog(23, "The Rate It dialog") KISettings = ptAttribGUIDialog(24, "The KI settings dialog") KIMarkerFolderExpanded = ptAttribGUIDialog(27, "The Marker Folder dialog") KIMarkerFolderPopupMenu = ptAttribGUIPopUpMenu(28, "The MarkerFolder Time Popup Menu") # Disabled: KIQuestionNote = ptAttribGUIDialog(29, "The Question Note dialog") # Disabled: KIMarkerTypePopupMenu = ptAttribGUIPopUpMenu(30, "The MarkerFolder Type Popup Menu") KICreateMarkerGameGUI = ptAttribGUIDialog(31, "The Marker Game Creation GUI") KIMarkerGameGUIOpen = ptAttribResponder(32, "Marker Game GUI Open Responder") KIMarkerGameGUIClose = ptAttribResponder(33, "Marker Game GUI Close Responder") KIJalakMiniIconOn = ptAttribResponder(34, "Jalak KIMini icon 'on/off' resp", ["on", "off"]) KIJalakGUIDialog = ptAttribGUIDialog(35, "The Jalak GUI dialog") KIJalakGUIOpen = ptAttribResponder(36, "Jalak GUI 'open' resp") KIJalakGUIClose = ptAttribResponder(37, "Jalak GUI 'close' resp") KIJalakBtnLights = ptAttribResponder(38, "Jalak GUI btn lights resp", statelist=JalakBtnStates, netForce=0) ## The master class handling all of Uru's GUI. # This includes the KI itself, the blackbar, the Jalak GUI... class xKI(ptModifier): ## Initialize the KI. # Called only once during Uru execution when the game is started. At this # stage, Plasma is not yet initialized. def __init__(self): # Set up the KI. ptModifier.__init__(self) self.id = 199 self.version = MaxVersionNumber self.folderOfDevices = DeviceFolder(PtGetLocalizedString("KI.Folders.Devices")) PtDebugPrint(u"xKI: Max version {} - minor version {}.".format(MaxVersionNumber, MinorVersionNumber)) # Prepare the GUI's default state. self.KIGUIInitialized = False self.KIDisabled = False self.KIHardDisabled = False self.isPlayingLookingAtKIMode = False self.miniKIWasUp = False self.sawTheKIAtLeastOnce = False self.miniKIFirstTimeShow = True # Set the default KI levels. self.censorLevel = 0 self.gKIMarkerLevel = 0 self.KILevel = kMicroKI # Assume the KI is at the lowest level. self.MGKILevel = 0 # Player state. self.onlyGetPMsFromBuddies = False self.onlyAllowBuddiesOnRequest = False self.takingAPicture = False self.waitingForAnimation = False # Transparency settings. self.originalForeAlpha = 1.0 self.originalSelectAlpha = 1.0 self.originalminiKICenter = None self.lastminiKICenter = None #~~~~~~~# # BigKI # #~~~~~~~# self.previousTime = "20:20" self.timeBlinker = True self.BKPlayerList = [] self.BKPlayerSelected = None self.previouslySelectedPlayer = None self.BKJournalFolderDict = {} self.BKJournalListOrder = [] self.BKJournalFolderSelected = 0 self.BKJournalFolderTopLine = 0 self.BKPlayerFolderDict = {} self.BKPlayerListOrder = [] self.BKPlayerFolderSelected = 0 self.BKPlayerFolderTopLine = 0 self.BKConfigFolderDict = {} self.BKConfigListOrder = [PtGetLocalizedString("KI.Config.Settings")] self.BKConfigDefaultListOrder = [PtGetLocalizedString("KI.Config.Settings")] self.BKConfigFolderSelected = 0 self.BKConfigFolderTopLine = 0 self.BKFolderLineDict = self.BKJournalFolderDict self.BKFolderListOrder = self.BKJournalListOrder self.BKFolderSelected = self.BKJournalFolderSelected self.BKFolderTopLine = self.BKJournalFolderTopLine self.BKFolderSelectChanged = False self.BKIncomingFolder = None self.BKNewItemsInInbox = 0 self.BKCurrentContent = None self.BKContentList = [] self.BKContentListTopLine = 0 self.BKInEditMode = False self.BKEditContent = None self.BKEditField = -1 self.BKGettingPlayerID = False self.BKRightSideMode = kGUI.BKListMode self.BKAgeOwnerEditDescription = False # New item alert. self.alertTimerActive = False self.alertTimeToUse = kAlertTimeDefault # Yes/No dialog globals. self.YNWhatReason = kGUI.YNQuit self.YNOutsideSender = None # Player book globals. self.bookOfferer = None self.offerLinkFromWho = None self.offeredBookMode = 0 self.psnlOfferedAgeInfo = None # The ptBook Yeesha book object. self.isEntireYeeshaBookEnabled = True self.isYeeshaBookEnabled = True self.yeeshaBook = None # KI light state. self.lightOn = False self.lightStop = 0 # Pellet score operations. self.scoreOpCur = kPellets.ScoreNoOp self.scoreOps = [] # KI usage values. self.numberOfPictures = 0 self.numberOfNotes = 0 self.numberOfMarkerFolders = 0 self.numberOfMarkers = 0 # Marker Games state. self.currentPlayingMarkerGame = None self.markerGameState = kGames.MGNotActive self.markerGameTimeID = 0 self.markerJoinRequests = [] self.MFdialogMode = kGames.MFOverview # New Marker Game dialog globals. self.markerGameDefaultColor = "" self.markerGameSelectedColor = "" self.selectedMGType = 0 # GZ missions state. self.gGZPlaying = 0 self.gGZMarkerInRange = 0 self.gGZMarkerInRangeRepy = None self.gMarkerToGetColor = "off" self.gMarkerGottenColor = "off" self.gMarkerToGetNumber = 0 self.gMarkerGottenNumber = 0 # Jalak GUI globals. self.jalakGUIButtons = [] self.jalakGUIState = False self.jalakScript = None # Miscellaneous. self.imagerMap = {} self.pelletImager = "" ## Auto-completion manager. self.autocompleteState = AutocompleteState() ## The chatting manager. self.chatMgr = xKIChat.xKIChat(self.StartFadeTimer, self.ResetFadeState, self.FadeCompletely, self.GetCensorLevel) ## Unloads any loaded dialogs upon exit. def __del__(self): PtUnloadDialog("KIMicroBlackBar") PtUnloadDialog("KIMicro") PtUnloadDialog("KIMini") PtUnloadDialog("KIMain") PtUnloadDialog("KIListMode") PtUnloadDialog("KIJournalExpanded") PtUnloadDialog("KIPictureExpanded") PtUnloadDialog("KIPlayerExpanded") PtUnloadDialog("KIAgeOwnerSettings") PtUnloadDialog("KISettings") PtUnloadDialog("KIMarkerFolder") PtUnloadDialog("KIMarkerTimeMenu") PtUnloadDialog("KIMarkerTypeMenu") PtUnloadDialog("KIYesNo") PtUnloadDialog("KINewItemAlert") PtUnloadDialog("OptionsMenuGUI") PtUnloadDialog("IntroBahroBgGUI") PtUnloadDialog("KIHelp") PtUnloadDialog("KIHelpMenu") PtUnloadDialog("KeyMapDialog") PtUnloadDialog("GameSettingsDialog") PtUnloadDialog("CalibrationGUI") PtUnloadDialog("TrailerPreviewGUI") PtUnloadDialog("KeyMap2Dialog") PtUnloadDialog("AdvancedGameSettingsDialog") PtUnloadDialog("OptionsHelpGUI") PtUnloadDialog("bkNotebook") PtUnloadDialog("bkBahroRockBook") PtUnloadDialog("YeeshaPageGUI") PtUnloadDialog("KIMiniMarkers") if PtGetAgeName() == "Jalak": PtDebugPrint(u"xKI: Unloading Jalak GUI dialog.", level=kWarningLevel) KIJalakMiniIconOn.run(self.key, state="off", netPropagate=0, fastforward=1) ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).disable() ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).hide() PtUnloadDialog("jalakControlPanel") #~~~~~~~~~~~~~~~~~~# # Plasma Functions # #~~~~~~~~~~~~~~~~~~# ## Called by Plasma on receipt of the first PythonFileMod message. # Preloads all the GUI dialogs. def OnInit(self): # Preload all the dialogs. PtLoadDialog("KIBlackBar", self.key) PtLoadDialog("KIMicroBlackBar", self.key) PtLoadDialog("KIMicro", self.key) PtLoadDialog("KIMini", self.key) PtLoadDialog("KIMain", self.key) PtLoadDialog("KIListMode", self.key) PtLoadDialog("KIJournalExpanded", self.key) PtLoadDialog("KIPictureExpanded", self.key) PtLoadDialog("KIPlayerExpanded", self.key) PtLoadDialog("KIAgeOwnerSettings", self.key) PtLoadDialog("KISettings", self.key) PtLoadDialog("KIMarkerFolder", self.key) PtLoadDialog("KIMarkerTimeMenu", self.key) PtLoadDialog("KIMarkerTypeMenu", self.key) PtLoadDialog("KIYesNo", self.key) PtLoadDialog("KINewItemAlert", self.key) PtLoadDialog("OptionsMenuGUI") PtLoadDialog("IntroBahroBgGUI") PtLoadDialog("KIHelp") PtLoadDialog("KIHelpMenu") PtLoadDialog("KeyMapDialog") PtLoadDialog("GameSettingsDialog") PtLoadDialog("CalibrationGUI") PtLoadDialog("TrailerPreviewGUI") PtLoadDialog("KeyMap2Dialog") PtLoadDialog("AdvancedGameSettingsDialog") PtLoadDialog("OptionsHelpGUI") PtLoadDialog("bkNotebook") PtLoadDialog("bkBahroRockBook") PtLoadDialog("YeeshaPageGUI") PtLoadDialog("KIMiniMarkers", self.key) self.markerGameManager = xMarkerMgr.MarkerGameManager() # Pass the newly-initialized key to the modules. self.chatMgr.key = self.key ## Called by Plasma on receipt of the first plEvalMsg. # Loads all the dialogs for the first update. def OnFirstUpdate(self): # Create the dnicoordinate keeper. self.dniCoords = ptDniCoordinates() # To start with, use randized numbers instead of the real thing. self.chatMgr.logFile = ptStatusLog() xBookGUIs.LoadAllBookGUIs() logoutText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutTextID)) logoutText.hide() logoutButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutButtonID)) logoutButton.hide() ## Called by Plasma when the player updates his account. # This includes switching avatars and changing passwords. Because the KI # gets started at initial load time, the KI needs to be re-initialized once # the playerID has been updated, triggering this function. def OnAccountUpdate(self, updateType, result, playerID): if updateType == PtAccountUpdateType.kActivePlayer and result == 0 and playerID != 0: PtDebugPrint(u"xKI.OnAccountUpdate(): Active player set. Clear to re-init KI GUI.", level=kDebugDumpLevel) self.KIGUIInitialized = False elif updateType == PtAccountUpdateType.kChangePassword: if result == 0: self.chatMgr.DisplayStatusMessage(PtGetLocalizedString("KI.Messages.PasswordChangeSuccess")) else: self.chatMgr.DisplayStatusMessage(PtGetLocalizedString("KI.Messages.PasswordChangeFailure")) ## Called by Plasma when the Age state has been fully received. # This function re-initializes Marker Games, puts away the KI and performs # various other preparations. def OnServerInitComplete(self): # Force any open KIs to close. self.ToggleMiniKI() self.CheckKILight() ageName = PtGetAgeName() PtDebugPrint(u"xKI.OnServerInitComplete(): Age = ", ageName, level=kDebugDumpLevel) if ageName.lower() != "startup": self.markerGameManager.OnServerInitComplete() # Set up Jalak GUI. if ageName == "Jalak": PtDebugPrint(u"xKI.OnServerInitComplete(): Loading Jalak GUI dialog.", level=kWarningLevel) PtLoadDialog("jalakControlPanel", self.key) KIJalakMiniIconOn.run(self.key, state="on", netPropagate=0) ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).show() ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).enable() self.AlertKIStart() else: KIJalakMiniIconOn.run(self.key, state="off", netPropagate=0, fastforward=1) ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).disable() ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).hide() ## Called by Plasma when the avatar is linked out of an Age. # Depending on the Age the avatar was linking out, the Jalak GUI will be # disabled and the KI light turned off. def BeginAgeUnLoad(self, avObj): ageName = PtGetAgeName() if ageName == "Descent": return elif ageName == "Jalak": if self.jalakGUIState: self.JalakGUIToggle(1) if not self.lightOn: return local = 0 try: local = PtGetLocalAvatar() except: PtDebugPrint(u"xKI.BeginAgeUnLoad(): Failed to get local avatar.") return if local == avObj: PtDebugPrint(u"xKI.BeginAgeUnLoad(): Avatar page out.", level=kDebugDumpLevel) curTime = PtGetDniTime() timeRemaining = (self.lightStop - curTime) if timeRemaining > 0: self.DoKILight(0, 1, timeRemaining) LocalAvatar = PtGetLocalAvatar() avatarKey = LocalAvatar.getKey() PtSetLightAnimStart(avatarKey, kKILightObjectName, False) ## Get any leftover, unwanted keystrokes. def OnDefaultKeyCaught(self, ch, isDown, isRepeat, isShift, isCtrl, keycode): if ord(ch) != 0: if not ord(ch) in kDefaultKeyIgnoreList: if isDown and not isCtrl and not isRepeat: if not self.KIDisabled and not PtIsEnterChatModeKeyBound(): self.chatMgr.ToggleChatMode(1, firstChar=ch) ## Called by Plasma on receipt of a plNotifyMsg. # This big function deals with the various responses sent upon a triggered # event, such as a book being offered. def OnNotify(self, state, ID, events): PtDebugPrint(u"xKI.OnNotify(): Notify state = {}, ID = {}.".format(state, ID), level=kDebugDumpLevel) # Is it a notification from the scene input interface or PlayerBook? for event in events: if event[0] == kOfferLinkingBook: if self.KILevel == kMicroKI: plybkCB = ptGUIControlCheckBox(KIMicroBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID)) else: plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID)) # Make sure we get the events back if someone else used the PlayerBook. if event[2] == -999: # If waiting for offeree to accept. if self.offeredBookMode == kGUI.Offeree: # Then take the offered PlayerBook. self.yeeshaBook.hide() PtToggleAvatarClickability(True) plybkCB.setChecked(0) # Else, they were too late. self.offeredBookMode = kGUI.NotOffering self.bookOfferer = None PtDebugPrint(u"xKI.OnNotify(): Offerer is rescinding the book offer.", level=kDebugDumpLevel) PtToggleAvatarClickability(True) return # The book is being offered by someone else. elif event[2] == 999: self.bookOfferer = event[1] avID = PtGetClientIDFromAvatarKey(self.bookOfferer.getKey()) if ptVault().getIgnoreListFolder().playerlistHasPlayer(avID): self.offeredBookMode = kGUI.NotOffering PtNotifyOffererLinkRejected(avID) self.bookOfferer = None PtToggleAvatarClickability(True) return else: self.offeredBookMode = kGUI.Offeree PtDebugPrint(u"xKI.OnNotify(): Offered book by ", self.bookOfferer.getName(), level=kDebugDumpLevel) self.ShowYeeshaBook() PtToggleAvatarClickability(False) return # Is it from the YeeshaBook? elif event[0] == PtEventType.kBook: if self.KILevel == kMicroKI: plybkCB = ptGUIControlCheckBox(KIMicroBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID)) else: plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID)) if event[1] == PtBookEventTypes.kNotifyImageLink: if event[2] == xLinkingBookDefs.kYeeshaBookShareID: if self.isYeeshaBookEnabled: # Rescind any previous offers. PtClearOfferBookMode() if self.offeredBookMode == kGUI.NotOffering: # Take the PlayerBook. self.yeeshaBook.hide() PtToggleAvatarClickability(True) plybkCB.setChecked(0) # Prepare to choose who to offer the link to. PtSetOfferBookMode(self.key, "Personal", "Relto") elif event[2] == xLinkingBookDefs.kYeeshaBookLinkID: if self.isYeeshaBookEnabled: self.yeeshaBook.hide() plybkCB.setChecked(0) if self.offeredBookMode == kGUI.Offeree: self.offeredBookMode = kGUI.NotOffering avID = PtGetClientIDFromAvatarKey(self.bookOfferer.getKey()) PtNotifyOffererLinkAccepted(avID) PtNotifyOffererLinkCompleted(avID) self.bookOfferer = None else: # Is the player on a ladder or something? curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode() if self.isEntireYeeshaBookEnabled and (curBrainMode == PtBrainModes.kNonGeneric or curBrainMode == PtBrainModes.kAFK or curBrainMode == PtBrainModes.kSit): linkmgr = ptNetLinkingMgr() linkmgr.linkToMyPersonalAgeWithYeeshaBook() PtToggleAvatarClickability(True) elif event[2] >= xLinkingBookDefs.kYeeshaPageStartID: whatpage = event[2] - xLinkingBookDefs.kYeeshaPageStartID sdlvar = xLinkingBookDefs.xYeeshaPages[whatpage][0] self.ToggleYeeshaPageSDL(sdlvar, 1) elif event[1] == PtBookEventTypes.kNotifyShow: pass elif event[1] == PtBookEventTypes.kNotifyHide: PtToggleAvatarClickability(True) plybkCB.setChecked(0) if self.offeredBookMode == kGUI.Offeree: self.offeredBookMode = kGUI.NotOffering avID = PtGetClientIDFromAvatarKey(self.bookOfferer.getKey()) PtNotifyOffererLinkRejected(avID) self.bookOfferer = None elif event[1] == PtBookEventTypes.kNotifyNextPage: pass elif event[1] == PtBookEventTypes.kNotifyPreviousPage: pass elif event[1] == PtBookEventTypes.kNotifyCheckUnchecked: if event[2] >= xLinkingBookDefs.kYeeshaPageStartID: whatpage = event[2] - xLinkingBookDefs.kYeeshaPageStartID sdlvar = xLinkingBookDefs.xYeeshaPages[whatpage][0] self.ToggleYeeshaPageSDL(sdlvar, 0) return if state: # Is it one of the responders that are displaying the BigKI? if ID == KIOnResp.id: self.ShowBigKIMode() self.waitingForAnimation = False toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID)) toggleCB.enable() elif ID == KIOffResp.id: BigKI.dialog.hide() self.waitingForAnimation = False toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID)) toggleCB.enable() if ID == KIMarkerGameGUIClose.id: PtHideDialog("KIMiniMarkers") if ID == KIJalakGUIClose.id: PtHideDialog("jalakControlPanel") ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).enable() elif ID == KIJalakGUIOpen.id: KIJalakGUIDialog.dialog.enable() ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).enable() elif ID == KIJalakBtnLights.id: btnID = int(KIJalakBtnLights.getState()) SendNote(self.key, self.jalakScript, "{}".format(btnID)) PtAtTimeCallback(self.key, kJalakBtnDelaySeconds, kTimers.JalakBtnDelay) ## Called by Plasma when a page has been loaded. # This is used to delay the display of objects until something is paged in. def OnPageLoad(self, what, room): if not self.KIGUIInitialized: self.KIGUIInitialized = True self.SetupKI() # When we unload the page, then the device we have must be gone. if what == kUnloaded: self.folderOfDevices.removeAll() # Remove any selected player. if self.KILevel == kNormalKI: self.BKPlayerSelected = None sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine)) sendToField.setString(" ") if self.gGZMarkerInRange: self.gGZMarkerInRange = 0 self.gGZMarkerInRangeRepy = None self.RefreshMiniKIMarkerDisplay() NewItemAlert.dialog.hide() kialert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertKIAlert)) kialert.hide() if self.pelletImager != "": self.pelletImager = "" ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.PelletScoreButton)).hide() ## Called by Plasma when a GUI event occurs. # Delegates the appropriate response to the correct handler. def OnGUINotify(self, ID, control, event): PtDebugPrint(u"xKI.OnGUINotify(): ID = {}, event = {}, control = {}.".format(ID, event, control), level=kDebugDumpLevel) if ID == KIBlackbar.id: self.ProcessNotifyBlackbar(control, event) elif ID == KIMicroBlackbar.id: self.ProcessNotifyMicroBlackbar(control, event) elif ID == KIMicro.id: self.ProcessNotifyMicro(control, event) elif ID == KIMini.id: self.ProcessNotifyMini(control, event) elif ID == BigKI.id: self.ProcessNotifyBigKI(control, event) elif ID == KIListModeDialog.id: self.ProcessNotifyListMode(control, event) elif ID == KIPictureExpanded.id: self.ProcessNotifyPictureExpanded(control, event) elif ID == KIJournalExpanded.id: self.ProcessNotifyJournalExpanded(control, event) elif ID == KIPlayerExpanded.id: self.ProcessNotifyPlayerExpanded(control, event) elif ID == KISettings.id: self.ProcessNotifySettingsExpanded(control, event) elif ID == KIVolumeExpanded.id: self.ProcessNotifyVolumeExpanded(control, event) elif ID == KIAgeOwnerExpanded.id: self.ProcessNotifyAgeOwnerExpanded(control, event) elif ID == KIYesNo.id: self.ProcessNotifyYesNo(control, event) elif ID == NewItemAlert.id: self.ProcessNotifyNewItemAlert(control, event) elif ID == KICreateMarkerGameGUI.id: self.ProcessNotifyCreateMarkerGameGUI(control, event) elif ID == KIMarkerFolderExpanded.id: self.ProcessNotifyMarkerFolderExpanded(control, event) elif ID == KIMarkerFolderPopupMenu.id: self.ProcessNotifyMarkerFolderPopupMenu(control, event) elif ID == KIJalakGUIDialog.id: self.ProcessNotifyJalakGUI(control, event) ## Called by Plasma on receipt of a KI message. # These are messages which instruct xKI to perform a certain command like # enabling or disabling the KI, showing a Yes/No dialog, etc.. These # messages can also be sent from the Python to Plasma and back. def OnKIMsg(self, command, value): PtDebugPrint(u"xKI.OnKIMsg(): command = {} value = {}.".format(command, value), level=kDebugDumpLevel) if self.markerGameManager.OnKIMsg(command, value): return if command == kEnterChatMode and not self.KIDisabled: self.chatMgr.ToggleChatMode(1) elif command == kSetChatFadeDelay: self.chatMgr.ticksOnFull = value elif command == kSetTextChatAdminMode: self.chatMgr.isAdmin = value elif command == kDisableKIandBB: self.KIDisabled = True self.chatMgr.KIDisabled = True self.KIHardDisabled = True if self.KILevel == kMicroKI: KIMicroBlackbar.dialog.hide() if KIMicro.dialog.isEnabled(): self.miniKIWasUp = True KIMicro.dialog.hide() else: self.miniKIWasUp = False else: KIBlackbar.dialog.hide() if KIMini.dialog.isEnabled(): self.miniKIWasUp = True KIMini.dialog.hide() else: self.miniKIWasUp = False if not self.waitingForAnimation: # Hide all dialogs on the right side of the BigKI and hide it. KIListModeDialog.dialog.hide() KIPictureExpanded.dialog.hide() KIJournalExpanded.dialog.hide() KIPlayerExpanded.dialog.hide() BigKI.dialog.hide() KIOnAnim.animation.skipToTime(1.5) # If an outsider has a Yes/No up, tell them No. if self.YNWhatReason == kGUI.YNOutside: if self.YNOutsideSender is not None: note = ptNotify(self.key) note.clearReceivers() note.addReceiver(self.YNOutsideSender) note.netPropagate(0) note.netForce(0) note.setActivate(0) note.addVarNumber("YesNo", 0) note.send() self.YNOutsideSender = None # Hide the Yeesha Book. if self.yeeshaBook: self.yeeshaBook.hide() PtToggleAvatarClickability(True) plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID)) plybkCB.setChecked(0) self.YNWhatReason = kGUI.YNQuit KIYesNo.dialog.hide() elif command == kEnableKIandBB: self.KIDisabled = False self.chatMgr.KIDisabled = False self.KIHardDisabled = False if self.KILevel == kMicroKI: KIMicroBlackbar.dialog.show() if self.miniKIWasUp: KIMicro.dialog.show() else: KIBlackbar.dialog.show() if self.miniKIWasUp: self.chatMgr.ClearBBMini(0) KIMini.dialog.show() elif command == kTempDisableKIandBB: self.KIDisabled = True self.chatMgr.KIDisabled = True if self.KILevel == kMicroKI: KIMicroBlackbar.dialog.hide() else: KIBlackbar.dialog.hide() if self.yeeshaBook: self.yeeshaBook.hide() PtToggleAvatarClickability(True) plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID)) plybkCB.setChecked(0) elif command == kTempEnableKIandBB and not self.KIHardDisabled: self.KIDisabled = False self.chatMgr.KIDisabled = False if self.KILevel == kMicroKI: KIMicroBlackbar.dialog.showNoReset() else: KIBlackbar.dialog.showNoReset() elif command == kYesNoDialog: self.YNWhatReason = kGUI.YNOutside self.YNOutsideSender = value[1] yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID)) yesText.setStringW(value[0]) self.LocalizeDialog(1) KIYesNo.dialog.show() elif command == kAddPlayerDevice: if "<p>" in value: self.pelletImager = value.rstrip("<p>") ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.PelletScoreButton)).show() PtDebugPrint(u"Pellet Imager:", self.pelletImager, level=kDebugDumpLevel) return try: self.folderOfDevices.index(Device(value)) except ValueError: self.folderOfDevices.append(Device(value)) self.RefreshPlayerList() elif command == kRemovePlayerDevice: if "<p>" in value: self.pelletImager = "" ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.PelletScoreButton)).hide() return try: self.folderOfDevices.remove(Device(value)) except ValueError: pass self.RefreshPlayerList() elif command == kUpgradeKILevel: if value >= kLowestKILevel and value <= kHighestKILevel: if value > self.KILevel: PtDebugPrint(u"xKI.OnKIMsg(): Upgrading from KI level {} to new KI level of {}.".format(self.KILevel, value), level=kWarningLevel) self.RemoveKILevel(self.KILevel) self.KILevel = value self.chatMgr.KILevel = self.KILevel self.UpdateKILevelChronicle() self.WearKILevel(self.KILevel) else: PtDebugPrint(u"xKI.OnKIMsg(): Ignoring, trying to upgrade from KI level {} to new KI level of {}.".format(self.KILevel, value), level=kWarningLevel) self.MakeSureWeWereKILevel() else: PtDebugPrint(u"xKI.OnKIMsg(): Invalid KI level {}.".format(value), level=kErrorLevel) elif command == kDowngradeKILevel: if value == self.KILevel: PtDebugPrint(u"xKI.OnKIMsg(): Remove KI level of {}.".format(value), level=kWarningLevel) if value == kNormalKI: self.RemoveKILevel(kNormalKI) self.KILevel = kMicroKI self.chatMgr.KILevel = self.KILevel self.UpdateKILevelChronicle() self.WearKILevel(self.KILevel) else: PtDebugPrint(u"xKI.OnKIMsg(): Ignoring, can't remove to any lower than {}.".format(value), level=kWarningLevel) else: PtDebugPrint(u"xKI.OnKIMsg(): Ignoring, trying to remove KI Level {}, but currently at {}.".format(value, self.KILevel), level=kWarningLevel) elif command == kSetPrivateChatChannel: self.chatMgr.privateChatChannel = value elif command == kUnsetPrivateChatChannel: self.chatMgr.privateChatChannel = 0 elif command == kStartBookAlert: self.AlertBookStart() elif command == kStartKIAlert: self.AlertKIStart() elif command == kUpdatePelletScore: self.UpdatePelletScore() self.AlertKIStart() elif command == kMiniBigKIToggle: self.ToggleKISize() elif command == kKIPutAway: self.ToggleMiniKI() elif command == kChatAreaPageUp: self.chatMgr.ScrollChatArea(PtGUIMultiLineDirection.kPageUp) elif command == kChatAreaPageDown: self.chatMgr.ScrollChatArea(PtGUIMultiLineDirection.kPageDown) elif command == kChatAreaGoToBegin: self.chatMgr.ScrollChatArea(PtGUIMultiLineDirection.kBufferStart) elif command == kChatAreaGoToEnd: self.chatMgr.ScrollChatArea(PtGUIMultiLineDirection.kBufferEnd) elif command == kKITakePicture: self.TakePicture() elif command == kKICreateJournalNote: self.MiniKICreateJournalNote() elif command == kKIToggleFade: if self.chatMgr.IsFaded(): self.ResetFadeState() else: self.FadeCompletely() elif command == kKIToggleFadeEnable: self.KillFadeTimer() if self.chatMgr.fadeEnableFlag: self.chatMgr.fadeEnableFlag = False else: self.chatMgr.fadeEnableFlag = True self.StartFadeTimer() elif command == kKIChatStatusMsg: self.chatMgr.DisplayStatusMessage(value, 1) elif command == kKILocalChatStatusMsg: self.chatMgr.DisplayStatusMessage(value, 0) elif command == kKILocalChatErrorMsg: self.chatMgr.AddChatLine(None, value, kChat.SystemMessage) elif command == kKIUpSizeFont: self.ChangeFontSize(1) elif command == kKIDownSizeFont: self.ChangeFontSize(-1) elif command == kKIOpenYeehsaBook: nm = ptNetLinkingMgr() if self.KILevel >= kMicroKI and not self.KIDisabled and not self.waitingForAnimation and nm.isEnabled(): curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode() if self.isEntireYeeshaBookEnabled and (curBrainMode == PtBrainModes.kNonGeneric or curBrainMode == PtBrainModes.kAFK or curBrainMode == PtBrainModes.kSit): self.ShowYeeshaBook() if self.KILevel == kMicroKI: plybkCB = ptGUIControlCheckBox(KIMicroBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID)) else: plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID)) plybkCB.setChecked(1) elif command == kKIOpenKI: if not self.waitingForAnimation: if not KIMini.dialog.isEnabled(): self.ToggleMiniKI(1) elif not BigKI.dialog.isEnabled(): if self.chatMgr.fadeEnableFlag and self.chatMgr.IsFaded(): self.ResetFadeState() else: self.ToggleKISize() else: self.ToggleMiniKI() elif command == kKIShowOptionsMenu: if self.yeeshaBook: self.yeeshaBook.hide() PtToggleAvatarClickability(True) if self.KILevel == kMicroKI: plybkCB = ptGUIControlCheckBox(KIMicroBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID)) plybkCB.setChecked(0) elif self.KILevel > kMicroKI: plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID)) plybkCB.setChecked(0) if not self.waitingForAnimation and not self.KIDisabled: PtShowDialog("OptionsMenuGUI") elif command == kKIOKDialog or command == kKIOKDialogNoQuit: reasonField = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID)) try: localized = kLoc.OKDialogDict[value] except KeyError: localized = U"UNTRANSLATED: " + unicode(value) reasonField.setStringW(localized) noButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.NoButtonID)) noButton.hide() noBtnText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.NoButtonTextID)) noBtnText.hide() yesBtnText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesButtonTextID)) yesBtnText.setStringW(PtGetLocalizedString("KI.YesNoDialog.OKButton")) self.YNWhatReason = kGUI.YNQuit if command == kKIOKDialogNoQuit: self.YNWhatReason = kGUI.YNNoReason KIYesNo.dialog.show() elif command == kDisableYeeshaBook: self.isYeeshaBookEnabled = False elif command == kEnableYeeshaBook: self.isYeeshaBookEnabled = True elif command == kQuitDialog: yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID)) yesText.setStringW(PtGetLocalizedString("KI.Messages.LeaveGame")) self.LocalizeDialog() logoutText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutTextID)) logoutText.show() logoutButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutButtonID)) logoutButton.show() KIYesNo.dialog.show() elif command == kDisableEntireYeeshaBook: self.isEntireYeeshaBookEnabled = False elif command == kEnableEntireYeeshaBook: self.isEntireYeeshaBookEnabled = True elif command == kUpgradeKIMarkerLevel: self.UpgradeKIMarkerLevel(value) self.RefreshMiniKIMarkerDisplay() elif command == kKIShowMiniKI: if self.KILevel >= kNormalKI: self.chatMgr.ClearBBMini(0) elif command == kFriendInviteSent: if value == 0: self.chatMgr.DisplayStatusMessage(PtGetLocalizedString("KI.Messages.InviteSuccess")) else: if value == 30: msg = PtGetLocalizedString("KI.Errors.InvitesDisabled") else: msg = "Error occured trying to send invite: " + str(value) self.chatMgr.AddChatLine(None, msg, kChat.SystemMessage) elif command == kRegisterImager: self.imagerMap[value[0]] = value[1] #~~~~~~~~~~~~~~~~~~~~~# # GZ Markers messages # #~~~~~~~~~~~~~~~~~~~~~# elif command == kGZUpdated: if value != 0: # Setting the max in the GZ marker chronicle. vault = ptVault() entry = vault.findChronicleEntry(kChronicleGZMarkersAquired) if entry is not None: markers = entry.chronicleGetValue() if len(markers) < value: # Need to increase the capacity of the markers; start as active. markers += kGZMarkerAvailable * (value - len(markers)) entry.chronicleSetValue(markers) entry.save() else: # If there are none, then just add another entry; start as active. markers = kGZMarkerAvailable * value vault.addChronicleEntry(kChronicleGZMarkersAquired, kChronicleGZMarkersAquiredType, markers) self.DetermineKILevel() self.DetermineGZ() self.RefreshMiniKIMarkerDisplay() elif command == kGZFlashUpdate: try: args = value.split() GZGame = int(args[0]) except: PtDebugPrint(u"xKI.OnKIMsg(): Cannot Update Marker Display, invalid Parameters: {}.".format(value)) return if GZGame == -1: self.GZFlashUpdate(value) else: self.DetermineKILevel() if self.gKIMarkerLevel > kKIMarkerNotUpgraded and self.gKIMarkerLevel < kKIMarkerNormalLevel: self.GZFlashUpdate(value) self.RefreshMiniKIMarkerDisplay() elif command == kGZInRange: # Only say markers are in range if there are more markers to get. if self.gMarkerToGetNumber > self.gMarkerGottenNumber: self.gGZMarkerInRange = value[0] self.gGZMarkerInRangeRepy = value[1] self.RefreshMiniKIMarkerDisplay() # Show alert NewItemAlert.dialog.show() KIAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertKIAlert)) KIAlert.show() elif command == kGZOutRange: self.gGZMarkerInRange = 0 self.gGZMarkerInRangeRepy = None self.RefreshMiniKIMarkerDisplay() NewItemAlert.dialog.hide() KIAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertKIAlert)) KIAlert.hide() #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# # User-created Marker Games messages # #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# elif command == kKICreateMarker: self.CreateAMarker() elif command == kKICreateMarkerFolder: self.CreateMarkerGame() ## Called by Plasma on receipt of a backdoor message. # These backdoor messages can trigger various actions. def OnBackdoorMsg(self, target, param): if target == "ki" and param == "refresh": self.BKFolderLineDict = self.BKJournalFolderDict self.BKFolderListOrder = self.BKJournalListOrder self.BKFolderSelected = self.BKJournalFolderSelected self.BKFolderTopLine = self.BKJournalFolderTopLine self.BigKIRefreshFolderList() self.BigKIRefreshFolderDisplay() self.BigKIRefreshContentList() self.BigKIRefreshContentListDisplay() self.ChangeBigKIMode(kGUI.BKListMode) if target.lower() == "cgz": self.markerGameManager.OnBackdoorMsg(target, param) ## Called by Plasma on receipt of a chat message. # This does not get called if the user sends a chat message through the KI, # only if he's getting a new message from another player. def OnRTChat(self, player, message, flags): if message is not None: cFlags = xKIChat.ChatFlags(flags) # Is it a private channel message that can't be listened to? if cFlags.broadcast and cFlags.channel != self.chatMgr.privateChatChannel: return # Is the message from an ignored plaer? vault = ptVault() ignores = vault.getIgnoreListFolder() if ignores is not None and ignores.playerlistHasPlayer(player.getPlayerID()): return # Display the message if it passed all the above checks. self.chatMgr.AddChatLine(player, message, cFlags, forceKI=not self.sawTheKIAtLeastOnce) # If they are AFK and the message was directly to them, send back their state to sender. try: if self.KIDisabled or PtGetLocalAvatar().avatar.getCurrentMode() == PtBrainModes.kAFK and cFlags.private and not cFlags.toSelf: myself = PtGetLocalPlayer() AFKSelf = ptPlayer(myself.getPlayerName() + PtGetLocalizedString("KI.Chat.AFK"), myself.getPlayerID()) PtSendRTChat(AFKSelf, [player], " ", cFlags.flags) except NameError: pass ## Called by Plasma when a timer is running. # Used to handle fading and the current time in the BigKI. def OnTimer(self, ID): # Chat fading. if ID == kTimers.Fade: # If it is fading, fade a tick. if self.chatMgr.fadeMode == kChat.FadeFullDisp: self.chatMgr.currentFadeTick -= 1 # Setup call for next second. if self.chatMgr.currentFadeTick > 0: PtAtTimeCallback(self.key, kChat.FullTickTime, kTimers.Fade) else: self.chatMgr.fadeMode = kChat.FadeDoingFade self.chatMgr.currentFadeTick = kChat.TicksOnFade PtAtTimeCallback(self.key, kChat.FadeTickTime, kTimers.Fade) elif self.chatMgr.fadeMode == kChat.FadeDoingFade: self.chatMgr.currentFadeTick -= 1 if self.chatMgr.currentFadeTick > 0: # Fade a little. if self.KILevel < kNormalKI: mKIdialog = KIMicro.dialog else: mKIdialog = KIMini.dialog mKIdialog.setForeColor(-1, -1, -1, self.originalForeAlpha * self.chatMgr.currentFadeTick / kChat.TicksOnFade) mKIdialog.setSelectColor(-1, -1, -1, self.originalSelectAlpha * self.chatMgr.currentFadeTick / kChat.TicksOnFade) mKIdialog.refreshAllControls() # Setup call for next second. PtAtTimeCallback(self.key, kChat.FadeTickTime, kTimers.Fade) else: # Completely fade out. self.chatMgr.FadeCompletely() elif self.chatMgr.fadeMode == kChat.FadeStopping: self.chatMgr.fadeMode = kChat.FadeNotActive # Time of day. elif ID == kTimers.BKITODCheck and BigKI.dialog.isEnabled(): self.BigKISetChanging() # Time of the currently played Marker Game. elif ID == kTimers.MarkerGame and self.currentPlayingMarkerGame is not None: self.currentPlayingMarkerGame.updateGameTime() PtAtTimeCallback(self.key, 1, kTimers.MarkerGame) # Stop an alert. elif ID == kTimers.AlertHide: self.AlertStop() # Take a snapshot after a waiting period. elif ID == kTimers.TakeSnapShot: PtDebugPrint(u"xKI.OnTimer(): Taking snapshot.") PtStartScreenCapture(self.key) # Dump the open logs. elif ID == kTimers.DumpLogs: if (PtDumpLogs(self.chatMgr.logDumpDest)): self.chatMgr.DisplayStatusMessage(PtGetLocalizedString("KI.Messages.LogDumpSuccess", [self.chatMgr.logDumpDest])) else: self.chatMgr.DisplayStatusMessage(PtGetLocalizedString("KI.Messages.LogDumpFailed", [self.chatMgr.logDumpDest])) # Turn off the KI light. elif ID == kTimers.LightStop: self.DoKILight(0, 0) # Turn on the Jalak GUI buttons. elif ID == kTimers.JalakBtnDelay: self.SetJalakGUIButtons(1) ## Called by Plasma when a screen capture is done. # This gets called once the screen capture is performed and ready to be # processed by the KI. def OnScreenCaptureDone(self, image): PtDebugPrint(u"xKI.OnScreenCaptureDone(): Snapshot is ready to be processed.") self.BigKICreateJournalImage(image) # Only show the KI if there isn't a dialog in the way. if not PtIsGUIModal(): # Make sure that we are in journal mode. if self.BKFolderLineDict is not self.BKJournalFolderDict: modeselector = ptGUIControlRadioGroup(BigKI.dialog.getControlFromTag(kGUI.BKRadioModeID)) modeselector.setValue(0) # Hide any previously opened picture. if self.BKRightSideMode != kGUI.BKPictureExpanded: self.HideBigKIMode() self.BKRightSideMode = kGUI.BKPictureExpanded # Reset the top line and selection. self.BigKIRefreshFolderDisplay() # Prepare to edit the caption of the picture. self.BigKIEnterEditMode(kGUI.BKEditFieldPICTitle) BigKI.dialog.show() # Was just the miniKI showing? if self.lastminiKICenter is None and self.originalminiKICenter is not None: dragBar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar)) self.lastminiKICenter = dragBar.getObjectCenter() dragBar.setObjectCenter(self.originalminiKICenter) dragBar.anchor() KIMini.dialog.show() else: # If the KI isn't supposed to be displayed, at least flash it so they know something happened. self.AlertKIStart() self.takingAPicture = False # Save the image to the filesystem. if "saveAsPNG" in dir(image): preferredExtension = "png" else: preferredExtension = "jpg" basePath = os.path.join(PtGetUserPath(), kImages.Directory) if not PtCreateDir(basePath): PtDebugPrint(u"xKI.OnScreenCaptureDone(): Unable to create \"{}\" directory. Image not saved to disk.".formatZ(basePath)) return imageList = glob.iglob(os.path.join(basePath, "{}[0-9][0-9][0-9][0-9].{}".format(kImages.FileNameTemplate, preferredExtension))) imageNumbers = [int(os.path.basename(img)[7:-4]) for img in imageList] + [0] missingNumbers = set(range(1, max(imageNumbers))).difference(set(imageNumbers)) if len(missingNumbers) > 0: firstMissing = min(missingNumbers) else: firstMissing = max(imageNumbers) + 1 tryName = os.path.join(basePath, U"{}{:04d}.{}".format(kImages.FileNameTemplate, firstMissing, preferredExtension)) PtDebugPrint(u"xKI.OnScreenCaptureDone(): Saving image to \"{}\".".format(tryName), level=kWarningLevel) if "saveAsPNG" in dir(image): image.saveAsPNG(tryName) else: image.saveAsJPEG(tryName, 90) ## Called by Plasma when the player list has been updated. # This makes sure that everything is updated and refreshed. def OnMemberUpdate(self): PtDebugPrint(u"xKI.OnMemberUpdate(): Refresh player list.", level=kDebugDumpLevel) if PtIsDialogLoaded("KIMini"): self.RefreshPlayerList() ## Called by Plasma when a new player is selected in the player list. def OnRemoteAvatarInfo(self, player): if self.KILevel < kNormalKI: return avatarSet = 0 if isinstance(player, ptPlayer): avatarSet = 1 self.BKPlayerSelected = player sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine)) sendToField.setString(player.getPlayerName()) self.SetBigKIToButtons() # Find the player in the list and select them. for pidx in range(len(self.BKPlayerList)): if isinstance(self.BKPlayerList[pidx], ptPlayer) and self.BKPlayerList[pidx] == player: playerlist = ptGUIControlListBox(KIMini.dialog.getControlFromTag(kGUI.PlayerList)) playerlist.setSelection(pidx) # Set the caret for the chat. caret = ptGUIControlTextBox(KIMini.dialog.getControlFromTag(kGUI.ChatCaretID)) caret.setStringW(PtGetLocalizedString("KI.Chat.TOPrompt") + unicode(player.getPlayerName()) + U" >") privateChbox = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniPrivateToggle)) privateChbox.setChecked(1) break if avatarSet: if not KIMini.dialog.isEnabled(): KIMini.dialog.show() self.ResetFadeState() ## Called by Plasma on receipt of a high-level player vault event. def OnVaultNotify(self, event, tupData): PtDebugPrint(u"xKI.OnVaultNotify(): Event = {} and data = {}.".format(event, tupData), level=kDebugDumpLevel) if not tupData: PtDebugPrint(u"xKI.OnVaultNotify(): Bailing, no Age data.") return if PtIsDialogLoaded("KIMain"): if event == PtVaultNotifyTypes.kRegisteredOwnedAge or event == PtVaultNotifyTypes.kUnRegisteredOwnedAge or event == PtVaultNotifyTypes.kRegisteredVisitAge or event == PtVaultNotifyTypes.kUnRegisteredVisitAge: if self.KILevel > kMicroKI: # A new owned Age was added, refresh its folders. if isinstance(tupData[0], ptVaultAgeLinkNode): # Is it the neighborhood? ownedAge = tupData[0].getAgeInfo() if ownedAge is not None: if self.IsAgeMyNeighborhood(ownedAge): self.BigKIRefreshHoodStatics(ownedAge) self.RefreshPlayerList() # Rebuild the player folder list because it might have changed. self.BigKIRefreshFolderList() self.BigKIRefreshFolderDisplay() self.BigKIRefreshContentList() self.BigKIRefreshContentListDisplay() self.RefreshAgeOwnerSettings() else: PtDebugPrint(u"xKI.OnVaultNotify(): No ageInfo. ", level=kErrorLevel) else: PtDebugPrint(u"xKI.OnVaultNotify(): Unknown tuple data type. ", level=kErrorLevel) else: PtDebugPrint(u"xKI.OnVaultNotify(): Unknown event {}.".format(event), level=kWarningLevel) else: PtDebugPrint(u"xKI.OnVaultNotify(): BigKI dialog was not loaded, waiting.", level=kDebugDumpLevel) ## Called by Plasma on receipt of a low-level player vault event. def OnVaultEvent(self, event, tupData): PtDebugPrint(u"xKI.VaultEvent(): Event = {} and data = {}.".format(event, tupData), level=kDebugDumpLevel) self.HandleVaultTypeEvents(event, tupData) ## Called by Plasma on receipt of a low-level Age vault event. def OnAgeVaultEvent(self, event, tupData): PtDebugPrint(u"xKI.OnAgeVaultEvent(): Event = {} and data = {}.".format(event, tupData), level=kDebugDumpLevel) self.HandleVaultTypeEvents(event, tupData) ## Called by Plasma when a marker has been captured by the player. def OnMarkerMsg(self, msgType, tupData): self.markerGameManager.OnMarkerMsg(msgType, tupData) ## Called by Plasma on receipt of a game score message. # This is used for handling pellet scoring. def OnGameScoreMsg(self, msg): if isinstance(msg, ptGameScoreListMsg): pelletTextBox = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPelletDrop)) try: score = msg.getScores()[0] points = score.getPoints() if self.scoreOpCur == kPellets.ScoreFetchForDisplay: if points < 0: points = 0 pelletTextBox.setString(str(points)) PtDebugPrint(u"xKI.OnGameScoreMsg(): PelletDrop score: {}.".format(points), level=kWarningLevel) elif self.scoreOpCur == kPellets.ScoreFetchMineForUpload: self.scoreSource = score self.DoScoreOp(kPellets.ScoreFetchUploadDestination) elif self.scoreOpCur == kPellets.ScoreFetchUploadDestination: self.scoreDestination = score self.scoreUploaded = self.scoreSource.getPoints() self.DoScoreOp(kPellets.ScoreTransfer) except: if self.scoreOpCur == kPellets.ScoreFetchForDisplay: pelletTextBox.setString("000") elif self.scoreOpCur == kPellets.ScoreFetchUploadDestination: self.DoScoreOp(kPellets.ScoreCreateUploadDestination) elif isinstance(msg, ptGameScoreTransferMsg): pelletTextBox = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPelletDrop)) pelletTextBox.setString("000") self.UploadPelletScore(self.scoreUploaded) del self.scoreDestination del self.scoreSource self.scoreUploaded = 0 elif isinstance(msg, ptGameScoreUpdateMsg): if self.scoreOpCur == kPellets.ScoreCreateUploadDestination: self.scoreDestination = msg.getScore() self.scoreUploaded = self.scoreSource.getPoints() self.DoScoreOp(kPellets.ScoreTransfer) # Process any remaining queued ops. self.ProcessScoreOps() #~~~~~~~~~~# # KI Setup # #~~~~~~~~~~# ## Sets up the KI for a given player. # Goes through all the steps required to ensure the player's KI is # appropriately up-to-date when a user starts playing. def SetupKI(self): self.BKPlayerList = [] self.BKPlayerSelected = None self.previouslySelectedPlayer = None self.BKJournalFolderDict = {} self.BKJournalListOrder = [] self.BKJournalFolderSelected = 0 self.BKJournalFolderTopLine = 0 self.BKPlayerFolderDict = {} self.BKPlayerListOrder = [] self.BKPlayerFolderSelected = 0 self.BKPlayerFolderTopLine = 0 self.BKConfigFolderDict = {} self.BKConfigFolderSelected = 0 self.BKConfigFolderTopLine = 0 self.BKFolderLineDict = self.BKJournalFolderDict self.BKFolderListOrder = self.BKJournalListOrder self.BKFolderSelected = self.BKJournalFolderSelected self.BKFolderTopLine = self.BKJournalFolderTopLine self.BKFolderSelectChanged = False self.BKIncomingFolder = None self.BKNewItemsInInbox = 0 self.BKCurrentContent = None self.BKContentList = [] self.BKContentListTopLine = 0 self.isYeeshaBookEnabled = True self.isEntireYeeshaBookEnabled = True self.DetermineCensorLevel() self.DetermineKILevel() self.DetermineKIFlags() self.DetermineGZ() # Hide all dialogs first. KIMicroBlackbar.dialog.hide() KIMicro.dialog.hide() KIMini.dialog.hide() KIBlackbar.dialog.hide() BigKI.dialog.hide() self.chatMgr.ToggleChatMode(0) # Remove unneeded kFontShadowed flags (as long as we can't do that directly in the PRPs) for dialogAttr in (BigKI, KIListModeDialog, KIJournalExpanded, KIPictureExpanded, KIPlayerExpanded, KIAgeOwnerExpanded, KISettings, KIMarkerFolderExpanded, KICreateMarkerGameGUI): for i in xrange(dialogAttr.dialog.getNumControls()): f = ptGUIControl(dialogAttr.dialog.getControlFromIndex(i)) # call this on all controls, even those that use the color scheme of the # dialog and would already report the flag cleared after the first one, # as they still need the setFontFlags call to refresh themselves f.setFontFlags(f.getFontFlags() & ~int(PtFontFlags.kFontShadowed)) if self.KILevel == kMicroKI: # Show the microBlackbar. KIMicroBlackbar.dialog.show() # Show the microKI. KIMicro.dialog.show() elif self.KILevel == kNormalKI: # Show the normal Blackbar. KIBlackbar.dialog.show() self.chatMgr.ClearBBMini() # Check for unseen messages. self.CheckInboxForUnseen() self.ToggleMiniKI() modeselector = ptGUIControlRadioGroup(BigKI.dialog.getControlFromTag(kGUI.BKRadioModeID)) modeselector.setValue(0) self.BigKIRefreshFolderList() self.BigKIRefreshFolderDisplay() self.BigKIRefreshContentList() self.BigKIRefreshContentListDisplay() self.ChangeBigKIMode(kGUI.BKListMode) # Load the ding dang marker game if self.gKIMarkerLevel == kKIMarkerNormalLevel: self.markerGameManager.LoadFromVault() #~~~~~~~~~~# # KI Flags # #~~~~~~~~~~# ## Sets the KI Flags from the Chronicle. # KI Flags are settings for the player's KI (pertaining to Buddies). def DetermineKIFlags(self): vault = ptVault() # Only get PMs and KI Mails from Buddies. entry = vault.findChronicleEntry(kChron.OnlyPMs) if entry is None: # Not found, set to 0 by default. vault.addChronicleEntry(kChron.OnlyPMs, kChron.OnlyPMsType, str(int(self.onlyGetPMsFromBuddies))) else: self.onlyGetPMsFromBuddies = int(entry.chronicleGetValue()) # Only allow the player to be buddied on request. entry = vault.findChronicleEntry(kChron.BuddiesOnRequest) if entry is None: # Not found, set to 0 by default. vault.addChronicleEntry(kChron.BuddiesOnRequest, kChron.BuddiesOnRequestType, str(int(self.onlyAllowBuddiesOnRequest))) else: self.onlyAllowBuddiesOnRequest = int(entry.chronicleGetValue()) ## Save the KI Flags to the Chronicle. def SaveKIFlags(self): vault = ptVault() # Only get PMs and KI Mails from Buddies. entry = vault.findChronicleEntry(kChron.OnlyPMs) if entry is not None: entry.chronicleSetValue(str(int(self.onlyGetPMsFromBuddies))) entry.save() else: vault.addChronicleEntry(kChron.OnlyPMs, kChron.OnlyPMsType, str(int(self.onlyGetPMsFromBuddies))) # Only allow the player to be buddied on request. entry = vault.findChronicleEntry(kChron.BuddiesOnRequest) if entry is not None: entry.chronicleSetValue(str(int(self.onlyAllowBuddiesOnRequest))) entry.save() else: vault.addChronicleEntry(kChron.BuddiesOnRequest, kChron.BuddiesOnRequestType, str(int(self.onlyAllowBuddiesOnRequest))) #~~~~~~~~~~# # KI Light # #~~~~~~~~~~# ## Finds out what the current KI light state is. def CheckKILight(self): timeRemaining = self.GetKILightChron() if not timeRemaining: PtDebugPrint(u"xKI.CheckKILight(): Had KI light, but it's currently off.", level=kDebugDumpLevel) self.DoKILight(0, 1) elif timeRemaining > 0: PtDebugPrint(u"xKI.CheckKILight(): Have KI light, time remaining = ", timeRemaining, level=kDebugDumpLevel) self.DoKILight(1, 1, timeRemaining) self.SetKILightChron(0) else: PtDebugPrint(u"No KI light.", level=kDebugDumpLevel) ## Get the KI light remaining time from the chronicle. def GetKILightChron(self): vault = ptVault() entry = vault.findChronicleEntry("KILightStop") if entry is not None: entryValue = entry.chronicleGetValue() remaining = int(entryValue) return remaining else: PtDebugPrint(u"xKI.GetKILightChron(): No KI light.", level=kDebugDumpLevel) return -1 ## Set the KI light remaining time in the chronicle. def SetKILightChron(self, remaining): vault = ptVault() entry = vault.findChronicleEntry("KILightStop") if entry is not None: entryValue = entry.chronicleGetValue() oldVal = int(entryValue) if remaining == oldVal: return PtDebugPrint(u"xKI.SetKILightChron(): Set KI light chron to: ", remaining, level=kDebugDumpLevel) entry.chronicleSetValue(str(int(remaining))) entry.save() ## Manages the KI light. def DoKILight(self, state, ff, remaining=0): thisResp = kListLightResps[state] LocalAvatar = PtGetLocalAvatar() avatarKey = LocalAvatar.getKey() avatarObj = avatarKey.getSceneObject() respList = avatarObj.getResponders() if len(respList) > 0: PtDebugPrint(u"xKI.DoKILight(): Responder list:", level=kDebugDumpLevel) for resp in respList: PtDebugPrint(u" {}".format(resp.getName())) if resp.getName() == thisResp: PtDebugPrint(u"xKI.DoKILight(): Found KI light resp: {}.".format(thisResp), level=kDebugDumpLevel) atResp = ptAttribResponder(42) atResp.__setvalue__(resp) atResp.run(self.key, avatar=LocalAvatar, fastforward=ff) if state: PtAtTimeCallback(self.key, remaining, kTimers.LightStop) PtDebugPrint(u"xKI.DoKILight(): Light was on in previous age, turning on for remaining ", remaining, " seconds.", level=kWarningLevel) curTime = PtGetDniTime() self.lightStop = (remaining + curTime) self.lightOn = True else: PtDebugPrint(u"xKI.DoKILight(): Light is shut off, updating chron.", level=kWarningLevel) self.SetKILightChron(remaining) self.lightOn = False PtSetLightAnimStart(avatarKey, kKILightObjectName, False) break else: PtDebugPrint(u"xKI.DoKILight(): Couldn't find any responders.", level=kErrorLevel) #~~~~~~~~~~~~~~# # Localization # #~~~~~~~~~~~~~~# ## Gets the appropriate localized values for a Yes/No dialog. def LocalizeDialog(self, dialog_type=0): confirm = "KI.YesNoDialog.QuitButton" if dialog_type == 1: confirm = "KI.YesNoDialog.YESButton" yesButton = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesButtonTextID)) noButton = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.NoButtonTextID)) yesButton.setStringW(PtGetLocalizedString(confirm)) noButton.setStringW(PtGetLocalizedString("KI.YesNoDialog.NoButton")) #~~~~~~~~~# # Pellets # #~~~~~~~~~# ## Perform an operation on the pellet score. def DoScoreOp(self, op): self.scoreOps.append(op) if self.scoreOpCur == kPellets.ScoreNoOp: self.ProcessScoreOps() ## Process the stored score operations. def ProcessScoreOps(self): if not len(self.scoreOps): self.scoreOpCur = kPellets.ScoreNoOp return self.scoreOpCur = self.scoreOps.pop(0) if self.scoreOpCur == kPellets.ScoreFetchForDisplay: ptGameScore.findPlayerScores("PelletDrop", self.key) elif self.scoreOpCur == kPellets.ScoreFetchMineForUpload: ptGameScore.findPlayerScores("PelletDrop", self.key) elif self.scoreOpCur == kPellets.ScoreFetchUploadDestination: ptGameScore.findAgeScores("PelletDrop", self.key) elif self.scoreOpCur == kPellets.ScoreCreateUploadDestination: ptGameScore.createAgeScore("PelletDrop", PtGameScoreTypes.kAccumulative, 0, self.key) elif self.scoreOpCur == kPellets.ScoreTransfer: self.scoreSource.transferPoints(self.scoreDestination, key=self.key) ## Update the pellet score to the specified value. # If no value is specified, fetch the current score for display. def UpdatePelletScore(self, points=0): pelletTextBox = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPelletDrop)) if points: pelletTextBox.setString(str(points)) else: pelletTextBox.setString("...") # Fetching from server. self.DoScoreOp(kPellets.ScoreFetchForDisplay) ## Upload the new pellet score to the server. def UploadPelletScore(self, score=None): if score: hoodInfoUpdate = PtFindActivator("PythHoodInfoImagerUpdater") PtDebugPrint(u"xKI.UploadPelletScore(): HoodInfoUpdate: {}.".format(hoodInfoUpdate), level=kDebugDumpLevel) if hoodInfoUpdate: notify = ptNotify(self.key) notify.clearReceivers() notify.addReceiver(hoodInfoUpdate) notify.netPropagate(1) notify.netForce(1) notify.setActivate(1.0) sName = "Score={}".format(PtGetLocalPlayer().getPlayerName()) notify.addVarNumber(sName, score) notify.send() PtDebugPrint(u"xKI.UploadPelletScore(): Sending score notify: {} {}.".format(sName, score), level=kDebugDumpLevel) else: self.DoScoreOp(kPellets.ScoreFetchMineForUpload) #~~~~~~~~~~~~~~~# # Auto-complete # #~~~~~~~~~~~~~~~# ## Auto-completes the text for a given editing control. def Autocomplete(self, control): text = control.getStringW() proposition = self.autocompleteState.pickNext(text) if proposition is not None: control.setStringW(proposition) control.end() control.refresh() return players = set() for item in self.BKPlayerList: if isinstance(item, ptPlayer): players.add(item.getPlayerName()) elif isinstance(item, ptVaultNodeRef): player = item.getChild() playerInfo = player.upcastToPlayerInfoNode() if playerInfo is not None: players.add(playerInfo.playerGetName()) proposition = self.autocompleteState.pickFirst(text, players) if proposition is not None: control.setStringW(proposition) control.end() control.refresh() #~~~~~~~~~~~~~~~~~# # Message History # #~~~~~~~~~~~~~~~~~# ## Set a control's text to a log entry in the message history def MessageHistory(self, control, set): if (set == "up"): if (self.chatMgr.MessageHistoryIs < len(self.chatMgr.MessageHistoryList)-1): self.chatMgr.MessageHistoryIs = self.chatMgr.MessageHistoryIs +1 control.setStringW(self.chatMgr.MessageHistoryList[self.chatMgr.MessageHistoryIs]) control.end() control.refresh() elif (set == "down"): if (self.chatMgr.MessageHistoryIs > 0): self.chatMgr.MessageHistoryIs = self.chatMgr.MessageHistoryIs -1 control.setStringW(self.chatMgr.MessageHistoryList[self.chatMgr.MessageHistoryIs]) control.end() control.refresh() #~~~~~~~~~~# # GZ Games # #~~~~~~~~~~# ## Sets the GZ globals from the Chronicle. def DetermineGZ(self): if self.gKIMarkerLevel > kKIMarkerNotUpgraded: if self.gKIMarkerLevel < kKIMarkerNormalLevel: vault = ptVault() entry = vault.findChronicleEntry(kChronicleGZGames) error = 0 if entry is not None: gameString = entry.chronicleGetValue() PtDebugPrint(u"xKI.DetermineGZ(): Game string is: \"{}\".".format(gameString), level=kWarningLevel) args = gameString.split() if len(args) == 3: try: self.gGZPlaying = int(args[0]) colors = args[1].split(":") outof = args[2].split(":") # Check for corrupted entry. if len(colors) != 2 or len(outof) != 2: PtDebugPrint(u"xKI.DetermineGZ(): Invalid color field or marker field.") raise ValueError # Check for invalid entry. if (colors[0] == "red" or colors[0] == "green") and int(outof[1]) > 15: PtDebugPrint(u"xKI.DetermineGZ(): Invalid marker number entry (i.e. 1515 bug).") raise ValueError self.gMarkerGottenColor = colors[0] self.gMarkerToGetColor = colors[1] self.gMarkerGottenNumber = int(outof[0]) self.gMarkerToGetNumber = int(outof[1]) return except: PtDebugPrint(u"xKI.DetermineGZ(): Could not read GZ Games Chronicle.", level=kErrorLevel) error = 1 else: PtDebugPrint(u"xKI.DetermineGZ(): Invalid GZ Games string formation.", level=kErrorLevel) error = 1 # If there was a problem, reset everything to "off". self.gGZPlaying = 0 self.gMarkerToGetColor = "off" self.gMarkerGottenColor = "off" self.gMarkerToGetNumber = 0 self.gMarkerGottenNumber = 0 # Reset Marker Games if a corrupted vault occurred. if error: PtDebugPrint(u"xKI.DetermineGZ(): Vault corrupted, resetting all Marker Game data.", level=kErrorLevel) import grtzKIMarkerMachine grtzKIMarkerMachine.ResetMarkerGame() else: # Can't be playing a GZ Game. self.gGZPlaying = 0 # Clear only if there are no currently active games. if self.markerGameState == kGames.MGNotActive or self.currentPlayingMarkerGame is None: self.gMarkerToGetColor = "off" self.gMarkerGottenColor = "off" self.gMarkerToGetNumber = 0 self.gMarkerGottenNumber = 0 else: # Reset everything to "off". self.gGZPlaying = 0 self.gMarkerToGetColor = "off" self.gMarkerGottenColor = "off" self.gMarkerToGetNumber = 0 self.gMarkerGottenNumber = 0 ## Update the GZ globals using provided values, not the Chronicle. def GZFlashUpdate(self, gameString): PtDebugPrint(u"xKI.GZFlashUpdate(): Game string is: \"{}\".".format(gameString), level=kWarningLevel) args = gameString.split() if len(args) == 3: try: GZPlaying = int(args[0]) colors = args[1].split(":") outof = args[2].split(":") # Check for corrupted entry. if len(colors) != 2 or len(outof) != 2: PtDebugPrint(u"xKI.GZFlashUpdate(): Invalid color field or marker field.") raise ValueError MarkerGottenColor = colors[0] MarkerToGetColor = colors[1] MarkerGottenNumber = int(outof[0]) MarkerToGetNumber = int(outof[1]) # Check for invalid entry. if (colors[0] == "red" or colors[0] == "green") and MarkerToGetNumber > 15: PtDebugPrint(u"xKI.GZFlashUpdate(): Invalid marker number entry (i.e. 1515 bug).") raise ValueError # Make sure the player is playing a GZ Game. if GZPlaying != -1: self.gGZPlaying = GZPlaying self.gMarkerGottenColor = MarkerGottenColor self.gMarkerToGetColor = MarkerToGetColor self.gMarkerGottenNumber = MarkerGottenNumber self.gMarkerToGetNumber = MarkerToGetNumber return except: PtDebugPrint(u"xKI.GZFlashUpdate(): Could not read GZ Games Chronicle. Checking Chronicle for corruption.", level=kErrorLevel) else: PtDebugPrint(u"xKI.GZFlashUpdate(): Invalid GZ Games string formation. Checking Chronicle for corruption.", level=kErrorLevel) vault = ptVault() entry = vault.findChronicleEntry(kChronicleGZGames) if entry is not None: if gameString == entry.chronicleGetValue(): PtDebugPrint(u"xKI.GZFlashUpdate(): Vault corrupted: trying to gracefully reset to a default state.", level=kErrorLevel) import grtzKIMarkerMachine grtzKIMarkerMachine.ResetMarkerGame() return ## Update the Chronicle's GZ Games values. # This takes the form of a series of values, separated by ":". def UpdateGZGamesChronicle(self): if self.gGZPlaying: vault = ptVault() entry = vault.findChronicleEntry(kChronicleGZGames) upString = "{} {}:{} {}:{}".format(self.gGZPlaying, self.gMarkerGottenColor, self.gMarkerToGetColor, self.gMarkerGottenNumber, self.gMarkerToGetNumber) if entry is not None: entry.chronicleSetValue(upString) entry.save() else: vault.addChronicleEntry(kChronicleGZGames, kChronicleGZGamesType, upString) ## Register a captured GZ marker. def CaptureGZMarker(self): if self.gGZPlaying and self.gMarkerToGetNumber > self.gMarkerGottenNumber: # Set the marker status to "captured" in the Chronicle. vault = ptVault() entry = vault.findChronicleEntry(kChronicleGZMarkersAquired) if entry is not None: markers = entry.chronicleGetValue() markerIdx = self.gGZMarkerInRange - 1 if markerIdx >= 0 and markerIdx < len(markers): if len(markers) - (markerIdx + 1) != 0: markers = markers[:markerIdx] + kGZMarkerCaptured + markers[-(len(markers) - (markerIdx + 1)):] else: markers = markers[:markerIdx] + kGZMarkerCaptured entry.chronicleSetValue(markers) entry.save() # Update the "marker gotten" count. totalGotten = markers.count(kGZMarkerCaptured) if self.gKIMarkerLevel > kKIMarkerFirstLevel: # Is this the second wave of markers (or beyond)? totalGotten -= 15 if totalGotten < 0: totalGotten = 0 if totalGotten > self.gMarkerToGetNumber: totalGotten = self.gMarkerToGetNumber self.gMarkerGottenNumber = totalGotten # Save update to Chronicle. self.UpdateGZGamesChronicle() else: PtDebugPrint(u"xKI.CaptureGZMarker(): Invalid marker serial number of {}.".format(self.gGZMarkerInRange)) return else: PtDebugPrint(u"xKI.CaptureGZMarker(): No Chronicle entry found.") return # Start building the notify message to go back to the orignator. if self.gGZMarkerInRangeRepy is not None: note = ptNotify(self.key) note.clearReceivers() note.addReceiver(self.gGZMarkerInRangeRepy) note.netPropagate(0) note.netForce(0) note.setActivate(1) note.addVarNumber("Captured", 1) note.send() self.gGZMarkerInRangeRepy = None self.gGZMarkerInRange = 0 #~~~~~~~~~~~~~~# # Marker Games # #~~~~~~~~~~~~~~# ## Selects a new Marker Game type. def SelectMarkerType(self, tagID): dlgObj = KICreateMarkerGameGUI if tagID and self.selectedMGType != tagID and self.selectedMGType != 0: PtDebugPrint(u"xKI.SelectMarkerType(): Old Marker Game type ID: ", self.selectedMGType, level=kDebugDumpLevel) ptGUIControlButton(dlgObj.dialog.getControlFromTag(self.selectedMGType)).enable() self.ChangeMarkerTypeColor(self.selectedMGType) self.selectedMGType = tagID PtDebugPrint(u"xKI.SelectMarkerType(): Selecting new Marker Game type: ", self.selectedMGType, level=kDebugDumpLevel) ptGUIControlButton(dlgObj.dialog.getControlFromTag(self.selectedMGType)).disable() self.ChangeMarkerTypeColor(tagID) ## Change the Marker Game type color. def ChangeMarkerTypeColor(self, tagID): dlgObj = KICreateMarkerGameGUI currentColor = ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(tagID + 5)).getForeColor() if currentColor == self.markerGameDefaultColor: ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(tagID + 5)).setForeColor(self.markerGameSelectedColor) elif currentColor == self.markerGameSelectedColor: ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(tagID + 5)).setForeColor(self.markerGameDefaultColor) ## Initialize the Marker Game creation GUI. def InitMarkerGameGUI(self): dlgObj = KICreateMarkerGameGUI self.selectedMGType = kGUI.MarkerGameType1 if self.MGKILevel == 2: ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType1)).disable() ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType2)).enable() ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType2)).show() ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel2)).show() ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType3)).enable() ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType3)).show() ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel3)).show() elif self.MGKILevel == 1: ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType1)).disable() ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType2)).enable() ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType2)).show() ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel2)).show() ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType3)).hide() ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel3)).hide() elif self.MGKILevel == 0: ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType1)).disable() ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType2)).hide() ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel2)).hide() ptGUIControlButton(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameType3)).hide() ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel3)).hide() ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel1)).setForeColor(self.markerGameSelectedColor) ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel2)).setForeColor(self.markerGameDefaultColor) ptGUIControlTextBox(dlgObj.dialog.getControlFromTag(kGUI.MarkerGameLabel3)).setForeColor(self.markerGameDefaultColor) playerName = PtGetLocalPlayer().getPlayerName() if playerName[-1] == "s": addToName = "'" else: addToName = "'s" gameName = playerName + addToName + " Marker Game" ptGUIControlEditBox(KICreateMarkerGameGUI.dialog.getControlFromTag(kGUI.CreateMarkerGameNameEB)).setString(gameName) ## Begin the creation of a new Marker Game. def CreateMarkerGame(self): # Make sure the player's KI Level is appropriately high. if self.KILevel <= kMicroKI or self.KIDisabled: PtDebugPrint(u"xKI.CreateMarkerGame(): Aborting Marker Game creation request, player does not have the KI.", level=kDebugDumpLevel) return # Make sure the player's KI Marker Level is appropriately high. if self.gKIMarkerLevel < kKIMarkerNormalLevel: PtDebugPrint(u"xKI.CreateMarkerGame(): Aborting Marker Game creation request, player does not have sufficient privileges.", level=kDebugDumpLevel) return # The player cannot be doing another task. if self.takingAPicture or self.waitingForAnimation: PtDebugPrint(u"xKI.CreateMarkerGame(): Aborting Marker Game creation request, player is busy.", level=kDebugDumpLevel) return # The player cannot create a game if one is already in progress. if self.markerGameManager.playing: PtDebugPrint(u"xKI.CreateMarkerGame(): Aborting Marker Game creation request, a game is already in progress.", level=kDebugDumpLevel) self.chatMgr.AddChatLine(None, PtGetLocalizedString("KI.MarkerGame.createErrorExistingGame"), kChat.SystemMessage) return # Make sure the player has enough room. if not self.CanMakeMarkerGame(): PtDebugPrint(u"xKI.CreateMarkerGame(): Aborting Marker Game creation request, player has reached the limit of Marker Games.", level=kDebugDumpLevel) self.ShowKIFullErrorMsg(PtGetLocalizedString("KI.Messages.FullMarkerGames")) return # The player can now launch the Marker Game creation GUI. self.HideBigKI() PtShowDialog("KIMiniMarkers") KIMarkerGameGUIOpen.run(self.key, netPropagate=0) ## Finishes creating the Marker Game after the asynchronous mini-game # server registers the parameters. def FinishCreateMarkerGame(self, gameName): # Get the current Age's Journal folder. load = 0 while load < 2: try: journal = self.BKJournalFolderDict[self.GetAgeInstanceName()] if journal is None: raise load = 2 except: if load == 1: # Failed twice in a row, it's hopeless. ## @todo Create the folder in case this happens. PtDebugPrint(u"xKI.FinishCreateMarkerGame(): Could not load Age's Journal Folder, Marker Game creation failed.", level=kErrorLevel) return load += 1 self.BigKIRefreshFolderList() # Hide the blackbar, just in case. KIBlackbar.dialog.hide() # Put the toggle button back to the BigKI setting. toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID)) toggleCB.setChecked(1) # Set the current mode to the Age's Journal folder. modeSelector = ptGUIControlRadioGroup(BigKI.dialog.getControlFromTag(kGUI.BKRadioModeID)) modeSelector.setValue(0) self.BKFolderTopLine = self.BKJournalFolderTopLine = 0 self.BKFolderSelected = self.BKJournalFolderSelected = self.BKJournalListOrder.index(self.GetAgeInstanceName()) self.BigKIRefreshFolderDisplay() # Create the Marker Game node. PtDebugPrint(u"xKI.FinishCreateMarkerGame(): Creating Vault node with name = \"{}\".".format(gameName), level=kDebugDumpLevel) markerGameNode = ptVaultMarkerGameNode() markerGameNode.setCreatorNodeID(PtGetLocalClientID()) markerGameNode.setGameName(gameName) self.BKCurrentContent = journal.addNode(markerGameNode) # Change to display current content. self.ChangeBigKIMode(kGUI.BKMarkerListExpanded) if BigKI.dialog.isEnabled(): self.ShowBigKIMode() else: KIMini.dialog.hide() BigKI.dialog.show() KIMini.dialog.show() if self.lastminiKICenter is None: if self.originalminiKICenter is not None: dragbar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar)) self.lastminiKICenter = dragbar.getObjectCenter() dragbar.setObjectCenter(self.originalminiKICenter) dragbar.anchor() ## Add a new marker to the existing Marker Game. def CreateAMarker(self): if not self.takingAPicture and not self.waitingForAnimation: if self.KILevel > kMicroKI and not self.KIDisabled: self.UpdateKIUsage() if self.CanMakeMarker(): markerName = u"{} marker".format(self.markerGameManager.game_name) avaCoord = PtGetLocalAvatar().position() self.markerGameManager.AddMarker(PtGetAgeName(), avaCoord, markerName) PtDebugPrint(u"xKI.CreateAMarker(): Creating marker at: ({}, {}, {}).".format(avaCoord.getX(), avaCoord.getY(), avaCoord.getZ())) else: self.ShowKIFullErrorMsg(PtGetLocalizedString("KI.Messages.FullMarkers")) ## Perform the necessary operations to switch to a Marker Game. def SetWorkingToCurrentMarkerGame(self): if self.BKCurrentContent is None: PtDebugPrint(u"xKI.SetWorkingToCurrentMarkerGame(): Cannot set working game, as there is no Vault folder.") return element = self.BKCurrentContent.getChild() if element is None: PtDebugPrint(u"xKI.SetWorkingToCurrentMarkerGame(): Cannot set working game, as there is no Vault node.") return element = element.upcastToMarkerGameNode() if element is None: PtDebugPrint(u"xKI.SetWorkingToCurrentMarkerGame(): Cannot set working game, as the Vault node is of the wrong type.") return # Refresh the content. self.RefreshPlayerList() self.BigKICheckContentRefresh(self.BKCurrentContent) ## Reset from the working Marker Game to None. def ResetWorkingMarkerGame(self): MGmgr = ptMarkerMgr() # Don't delete any markers necessary for an existing game. if not self.markerGameManager.is_game_loaded: MGmgr.hideMarkersLocal() # Refresh the content. self.RefreshPlayerList() self.BigKICheckContentRefresh(self.BKCurrentContent) #~~~~~~~# # Jalak # #~~~~~~~# ## Initialize the Jalak KI GUI. def JalakGUIInit(self): jlakRandom = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakRandomBtn)) jlakExtreme = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakExtremeBtn)) jlakWall = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakWallToggleBtn)) jlakAllLow = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakColumnsLowBtn)) jlakAllMed = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakColumnsMedBtn)) jlakAllHigh = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakColumnsHighBtn)) jlakRamp = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakRampBtn)) jlakSphere = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakSphereBtn)) jlakBigBox = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakBigBoxBtn)) jlakLilBox = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakLilBoxBtn)) jlakRect = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakRectangleBtn)) jlakDestroy = ptGUIControlButton(KIJalakGUIDialog.dialog.getControlFromTag(kJalakDestroyBtn)) self.jalakGUIButtons = [jlakRandom, jlakExtreme, jlakWall, jlakAllLow, jlakAllMed, jlakAllHigh, jlakRamp, jlakSphere, jlakBigBox, jlakLilBox, jlakRect, jlakDestroy] obj = PtFindSceneobject("JalakDONOTTOUCH", "Jalak") pythonScripts = obj.getPythonMods() for script in pythonScripts: if script.getName() == kJalakPythonComponent: self.jalakScript = script PtDebugPrint(u"xKI.JalakGUIInit(): Found Jalak's python component.", level=kDebugDumpLevel) return PtDebugPrint(u"xKI.JalakGUIInit(): Did not find Jalak's python component.", level=kErrorLevel) ## Toggle on/off the Jalak KI GUI. def JalakGUIToggle(self, ff=0): PtDebugPrint(u"xKI.JalakGUIToggle(): toggling GUI.", level=kDebugDumpLevel) ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).disable() if PtGetAgeName() != "Jalak": self.jalakGUIState = False return if self.jalakGUIState: self.jalakGUIState = False KIJalakGUIClose.run(self.key, netPropagate=0, fastforward=ff) if ff: PtHideDialog("jalakControlPanel") else: # User cannot be busy doing some other task. if self.takingAPicture or self.waitingForAnimation: PtDebugPrint(u"xKI.JalakGUIToggle(): Aborting request for Jalak GUI: user is busy.", level=kDebugDumpLevel) return # Only those that have Gahreesen KI can create a game. if self.KILevel <= kMicroKI or self.KIDisabled: PtDebugPrint(u"xKI.JalakGUIToggle(): Aborting request for Jalak GUI: user does not have the KI.", level=kDebugDumpLevel) return self.jalakGUIState = True PtShowDialog("jalakControlPanel") KIJalakGUIOpen.run(self.key, netPropagate=0) ## Activate or deactivate all the buttons in the Jalak GUI. def SetJalakGUIButtons(self, state): for btn in self.jalakGUIButtons: if state: btn.enable() else: btn.disable() #~~~~~~~~~~~# # KI Levels # #~~~~~~~~~~~# ## Make sure all the parts of the KI specific to this level are undone. def RemoveKILevel(self, level): # Is it removing the micro while upgrading? if level == kMicroKI: # Change the display to be the normal KI. KIMicroBlackbar.dialog.hide() KIMicro.dialog.hide() # Is it going from normal back to micro? elif level == kNormalKI: avatar = PtGetLocalAvatar() gender = avatar.avatar.getAvatarClothingGroup() if gender > kFemaleClothingGroup: gender = kMaleClothingGroup avatar.netForce(1) if gender == kFemaleClothingGroup: avatar.avatar.removeClothingItem("FAccKI") else: avatar.avatar.removeClothingItem("MAccKI") avatar.avatar.saveClothing() # Fill in the listbox so that the test is near the enter box. chatArea = ptGUIControlMultiLineEdit(KIMini.dialog.getControlFromTag(kGUI.ChatDisplayArea)) chatArea.lock() # Make the chat display immutable. chatArea.unclickable() # Make the chat display non-clickable. chatArea.moveCursor(PtGUIMultiLineDirection.kBufferEnd) chatArea.disableScrollControl() # Hide everything specific to the normalKI. KIBlackbar.dialog.hide() KIMini.dialog.hide() KIListModeDialog.dialog.hide() KIPictureExpanded.dialog.hide() KIJournalExpanded.dialog.hide() KIPlayerExpanded.dialog.hide() BigKI.dialog.hide() KIOnAnim.animation.skipToTime(1.5) ## Perform all operations associated with the newly-obtained KI level. def WearKILevel(self, level): if level == kMicroKI: avatar = PtGetLocalAvatar() gender = avatar.avatar.getAvatarClothingGroup() if gender > kFemaleClothingGroup: gender = kMaleClothingGroup avatar.netForce(1) if gender == kFemaleClothingGroup: avatar.avatar.wearClothingItem("FAccPlayerBook") else: avatar.avatar.wearClothingItem("MAccPlayerBook") avatar.avatar.saveClothing() # Show the microKI. KIMicroBlackbar.dialog.show() self.chatMgr.ClearBBMini() KIMicro.dialog.show() self.chatMgr.ToggleChatMode(0) elif level == kNormalKI: avatar = PtGetLocalAvatar() gender = avatar.avatar.getAvatarClothingGroup() if gender > kFemaleClothingGroup: gender = kMaleClothingGroup avatar.netForce(1) if gender == kFemaleClothingGroup: avatar.avatar.wearClothingItem("FAccKI") else: avatar.avatar.wearClothingItem("MAccKI") avatar.avatar.saveClothing() # Change the display to match the normal KI. KIBlackbar.dialog.show() self.chatMgr.ClearBBMini() KIOnAnim.animation.skipToTime(1.5) # Alert the user to the newly-available KI. self.AlertKIStart() # Check the player's inbox. self.CheckInboxForUnseen() # Refresh the folders, which will create the age journal for this Age. self.BigKIRefreshFolderList() ## Forcefully make sure the avatar is wearing the current KI level. # This ensures the player is wearing either the Yeesha Book, or the Yeesha # Book and the Gahreesen KI. def MakeSureWeWereKILevel(self): if self.KILevel == kMicroKI: try: avatar = PtGetLocalAvatar() gender = avatar.avatar.getAvatarClothingGroup() if gender > kFemaleClothingGroup: gender = kMaleClothingGroup avatar.netForce(1) if gender == kFemaleClothingGroup: avatar.avatar.wearClothingItem("FAccPlayerBook") else: avatar.avatar.wearClothingItem("MAccPlayerBook") avatar.avatar.saveClothing() except NameError: pass elif self.KILevel == kNormalKI: try: avatar = PtGetLocalAvatar() gender = avatar.avatar.getAvatarClothingGroup() if gender > kFemaleClothingGroup: gender = kMaleClothingGroup avatar.netForce(1) if gender == kFemaleClothingGroup: avatar.avatar.wearClothingItem("FAccPlayerBook") avatar.avatar.wearClothingItem("FAccKI") else: avatar.avatar.wearClothingItem("MAccPlayerBook") avatar.avatar.wearClothingItem("MAccKI") avatar.avatar.saveClothing() except NameError: pass ## Sets the current KI level from the Chronicle. # Also sets the current KI Marker Level. def DetermineKILevel(self): # Set the global KI Level. self.KILevel = kMicroKI vault = ptVault() entry = vault.findChronicleEntry(kChronicleKILevel) if entry is None: # Not found, set to MicroKI by default. vault.addChronicleEntry(kChronicleKILevel, kChronicleKILevelType, str(self.KILevel)) else: oldLevel = int(entry.chronicleGetValue()) if oldLevel >= kLowestKILevel and oldLevel <= kHighestKILevel: self.KILevel = oldLevel elif oldLevel < kLowestKILevel: # Make sure that the user has at least a microKI. self.UpdateKILevelChronicle() self.chatMgr.KILevel = self.KILevel PtDebugPrint(u"xKI.DetermineKILevel(): The KI Level is {}.".format(self.KILevel), level=kWarningLevel) # Set the KI Marker Level. self.gKIMarkerLevel = 0 entry = vault.findChronicleEntry(kChronicleKIMarkerLevel) if entry is None: # Not found, set to 0 by default. vault.addChronicleEntry(kChronicleKIMarkerLevel, kChronicleKIMarkerLevelType, str(self.gKIMarkerLevel)) else: try: self.gKIMarkerLevel = int(entry.chronicleGetValue()) except: PtDebugPrint(u"xKI.DetermineKILevel(): Chronicle entry error with the KI's Marker Level, resetting to the default value.", level=kErrorLevel) entry.chronicleSetValue(str(self.gKIMarkerLevel)) entry.save() PtDebugPrint(u"xKI.DetermineKILevel(): The KI Marker Level is {}.".format(self.gKIMarkerLevel), level=kWarningLevel) entry = vault.findChronicleEntry("feather") if entry is None: self.chatMgr.gFeather = 0 else: try: self.chatMgr.gFeather = int(entry.chronicleGetValue()) except ValueError: self.chatMgr.gFeather = 0 ## Upgrade the KI Marker Level to a new setting. def UpgradeKIMarkerLevel(self, newLevel): PtDebugPrint(u"xKI.UpgradeKIMarkerLevel(): KI Marker Level going from {} to {}.".format(self.gKIMarkerLevel, newLevel), level=kWarningLevel) if self.KILevel > kMicroKI and newLevel > self.gKIMarkerLevel: self.gKIMarkerLevel = newLevel vault = ptVault() entry = vault.findChronicleEntry(kChronicleKIMarkerLevel) if entry is None: PtDebugPrint(u"xKI.UpgradeKIMarkerLevel(): Chronicle entry not found, set to {}.".format(self.gKIMarkerLevel), level=kWarningLevel) vault.addChronicleEntry(kChronicleKIMarkerLevel, kChronicleKIMarkerLevelType, str(self.gKIMarkerLevel)) else: PtDebugPrint(u"xKI.UpgradeKIMarkerLevel(): Upgrading existing KI Marker Level to {}.".format(self.gKIMarkerLevel), level=kWarningLevel) entry.chronicleSetValue(str(self.gKIMarkerLevel)) entry.save() ## Updates the KI level's Chronicle value. def UpdateKILevelChronicle(self): vault = ptVault() entry = vault.findChronicleEntry(kChronicleKILevel) if entry is not None: entry.chronicleSetValue(str(self.KILevel)) entry.save() else: vault.addChronicleEntry(kChronicleKILevel, kChronicleKILevelType, str(self.KILevel)) #~~~~~~~~~~~~~# # Yeesha Book # #~~~~~~~~~~~~~# ## Show the Yeesha Book to the player, in accordance with its status. def ShowYeeshaBook(self): if self.KILevel >= kMicroKI and not self.KIDisabled and not self.waitingForAnimation: if BigKI.dialog.isEnabled() or KIMini.dialog.isEnabled(): self.ToggleMiniKI() startOpen = False if self.isYeeshaBookEnabled: if self.offeredBookMode == kGUI.NotOffering: YeeshaBDef = xLinkingBookDefs.xYeeshaBookBase + self.GetYeeshaPageDefs() else: YeeshaBDef = xLinkingBookDefs.xYeeshaBookNoShare startOpen = True else: YeeshaBDef = xLinkingBookDefs.xYeeshaBookBroke + self.GetYeeshaPageDefs() self.yeeshaBook = ptBook(YeeshaBDef, self.key) self.yeeshaBook.setSize(xLinkingBookDefs.YeeshaBookSizeWidth, xLinkingBookDefs.YeeshaBookSizeHeight) self.yeeshaBook.show(startOpen) PtToggleAvatarClickability(False) ## Returns the definitions for the Yeesha pages. # Gets called whenever the Relto's Age GUI is drawn. def GetYeeshaPageDefs(self): pageDefs = "" vault = ptVault() if vault is not None: psnlSDL = vault.getPsnlAgeSDL() if psnlSDL: for SDLVar, page in xLinkingBookDefs.xYeeshaPages: FoundValue = psnlSDL.findVar(SDLVar) if FoundValue is not None: PtDebugPrint(u"xKI.GetYeeshaPageDefs(): The previous value of the SDL variable \"{}\" is {}.".format(SDLVar, FoundValue.getInt()), level=kDebugDumpLevel) state = FoundValue.getInt() % 10 if state != 0: active = 1 if state == 2 or state == 3: active = 0 try: pageDefs += page % (active) except LookupError: pageDefs += "<pb><pb>Bogus page {}".format(SDLVar) else: PtDebugPrint(u"xKI.GetYeeshaPageDefs(): Trying to access the Chronicle psnlSDL failed: psnlSDL = \"{}\".".format(psnlSDL), level=kErrorLevel) else: PtDebugPrint(u"xKI.GetYeeshaPageDefs(): Trying to access the Vault failed, can't access YeeshaPageChanges Chronicle.", level=kErrorLevel) return pageDefs ## Turns on and off the Yeesha pages' SDL values. def ToggleYeeshaPageSDL(self, varName, on): vault = ptVault() if vault is not None: psnlSDL = vault.getPsnlAgeSDL() if psnlSDL: ypageSDL = psnlSDL.findVar(varName) if ypageSDL: size, state = divmod(ypageSDL.getInt(), 10) value = None if state == 1 and not on: value = 3 elif state == 3 and on: value = 1 elif state == 2 and on: value = 4 elif state == 4 and not on: value = 2 if value is not None: PtDebugPrint(u"xKI.ToggleYeeshaPageSDL(): Setting {} to {}.".format(varName, value), level=kDebugDumpLevel) ypageSDL.setInt((size * 10) + value) vault.updatePsnlAgeSDL(psnlSDL) #~~~~~~~~~~~# # Censoring # #~~~~~~~~~~~# ## Sets the censor level. # By default, it's set at PG, but it fetches the real value from the # chronicle. If it is not found in the chronicle, it will set it to PG. def DetermineCensorLevel(self): self.censorLevel = xCensor.xRatedPG vault = ptVault() entry = vault.findChronicleEntry(kChronicleCensorLevel) if entry is None: vault.addChronicleEntry(kChronicleCensorLevel, kChronicleCensorLevelType, str(self.censorLevel)) else: self.censorLevel = int(entry.chronicleGetValue()) PtDebugPrint(u"xKI.DetermineCensorLevel(): The censor level is {}.".format(self.censorLevel), level=kWarningLevel) def GetCensorLevel(self): return self.censorLevel #~~~~~~~# # Fonts # #~~~~~~~# ## Sets the current font size from the Chronicle. def DetermineFontSize(self): fontSize = self.GetFontSize() vault = ptVault() entry = vault.findChronicleEntry(kChron.FontSize) if entry is None: # Not found, add the current size to the Chronicle. vault.addChronicleEntry(kChron.FontSize, kChron.FontSizeType, str(fontSize)) else: fontSize = int(entry.chronicleGetValue()) self.SetFontSize(fontSize) PtDebugPrint(u"xKI.DetermineFontSize(): The saved font size is {}.".format(fontSize), level=kWarningLevel) ## Saves the current font size to the Chronicle. def SaveFontSize(self): fontSize = self.GetFontSize() vault = ptVault() entry = vault.findChronicleEntry(kChron.FontSize) if entry is not None: entry.chronicleSetValue(str(fontSize)) entry.save() else: vault.addChronicleEntry(kChron.FontSize, kChron.FontSizeType, str(fontSize)) PtDebugPrint(u"xKI.SaveFontSize(): Saving font size of {}.".format(fontSize), level=kWarningLevel) ## Returns the font size currently applied to the KI. def GetFontSize(self): if self.KILevel < kNormalKI: mKIdialog = KIMicro.dialog else: mKIdialog = KIMini.dialog miniChatArea = ptGUIControlMultiLineEdit(mKIdialog.getControlFromTag(kGUI.ChatDisplayArea)) return miniChatArea.getFontSize() ## Applies the specified font size. def SetFontSize(self, fontSize): PtDebugPrint(u"xKI.SetFontSize(): Setting font size to {}.".format(fontSize), level=kWarningLevel) if self.KILevel < kNormalKI: mKIdialog = KIMicro.dialog else: mKIdialog = KIMini.dialog miniChatArea = ptGUIControlMultiLineEdit(mKIdialog.getControlFromTag(kGUI.ChatDisplayArea)) miniChatArea.setFontSize(fontSize) miniChatArea.refresh() microChatArea = ptGUIControlMultiLineEdit(mKIdialog.getControlFromTag(kGUI.ChatDisplayArea)) microChatArea.setFontSize(fontSize) microChatArea.refresh() noteArea = ptGUIControlMultiLineEdit(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNNote)) noteArea.setFontSize(fontSize) noteArea.refresh() ownerNotes = ptGUIControlMultiLineEdit(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerDescription)) ownerNotes.setFontSize(fontSize) ownerNotes.refresh() ## Changes the font size currently in effect. def ChangeFontSize(self, new): size = self.GetFontSize() if new == 1: fontRange = range(len(kChat.FontSizeList) - 1) elif new == -1: fontRange = range(len(kChat.FontSizeList) - 1, 0, -1) for i in fontRange: if size <= kChat.FontSizeList[i] and new == 1: size = kChat.FontSizeList[i + 1] break size = kChat.FontSizeList[i - 1] break self.SetFontSize(size) self.SaveFontSize() self.RefreshKISettings() #~~~~~~~~# # Fading # #~~~~~~~~# ## Gets the current fading time from the Chronicle. def DetermineFadeTime(self): vault = ptVault() entry = vault.findChronicleEntry(kChron.FadeTime) if entry is None: # Not found, add the current fade time to the Chronicle. vault.addChronicleEntry(kChron.FadeTime, kChron.FadeTimeType, str(self.chatMgr.ticksOnFull)) else: self.chatMgr.ticksOnFull = int(entry.chronicleGetValue()) if self.chatMgr.ticksOnFull == kChat.FadeTimeMax: # Disable the fade altogether. self.chatMgr.fadeEnableFlag = False self.KillFadeTimer() PtDebugPrint(u"xKI.DetermineFadeTime(): Fade time disabled.", level=kWarningLevel) else: self.chatMgr.fadeEnableFlag = True PtDebugPrint(u"xKI.DetermineFadeTime(): The saved fade time is {}.".format(self.chatMgr.ticksOnFull), level=kWarningLevel) ## Saves the current fading time to the Chronicle. def SaveFadeTime(self): vault = ptVault() entry = vault.findChronicleEntry(kChron.FadeTime) if entry is not None: entry.chronicleSetValue(str(self.chatMgr.ticksOnFull)) entry.save() else: vault.addChronicleEntry(kChron.FadeTime, kChron.FadeTimeType, str(self.chatMgr.ticksOnFull)) PtDebugPrint(u"xKI.SaveFadeTime(): Saving Fade Time of {}.".format(self.chatMgr.ticksOnFull), level=kWarningLevel) ## Start the fade timer. # This gets called each time the user does something in relation to the # chat to keep it alive. def StartFadeTimer(self): if not self.chatMgr.fadeEnableFlag: return if not BigKI.dialog.isEnabled(): if self.chatMgr.fadeMode in (kChat.FadeNotActive, kChat.FadeDone): PtAtTimeCallback(self.key, kChat.FullTickTime, kTimers.Fade) self.chatMgr.fadeMode = kChat.FadeFullDisp self.currentFadeTick = self.chatMgr.ticksOnFull ## End the currently-active timer. def KillFadeTimer(self): if self.KILevel < kNormalKI: mKIdialog = KIMicro.dialog else: mKIdialog = KIMini.dialog # Optimization: only do this if we are fading or have faded if self.chatMgr.fadeMode in (kChat.FadeDoingFade, kChat.FadeDone, kChat.FadeNotActive): mKIdialog.setForeColor(-1, -1, -1, self.originalForeAlpha) mKIdialog.setSelectColor(-1, -1, -1, self.originalSelectAlpha) if self.KILevel == kNormalKI: playerlist = ptGUIControlListBox(mKIdialog.getControlFromTag(kGUI.PlayerList)) playerlist.show() chatArea = ptGUIControlMultiLineEdit(mKIdialog.getControlFromTag(kGUI.ChatDisplayArea)) chatArea.enableScrollControl() mKIdialog.refreshAllControls() # Toggle state if self.chatMgr.fadeMode not in (kChat.FadeNotActive, kChat.FadeDone): self.chatMgr.fadeMode = kChat.FadeStopping self.currentFadeTick = self.chatMgr.ticksOnFull def ResetFadeState(self, force=False): """This turns the chat fade OFF and resets it if the user is not chatting. Use this instead of calling `KillFadeTimer()` and `StartFadeTimer()` to toggle the state. Use `force` to disable checking of the chatting status (why would you do that?) """ # I'm cheating. self.KillFadeTimer() if not self.chatMgr.isChatting or force: self.StartFadeTimer() ## Make the miniKI lists completely faded out. def FadeCompletely(self): if self.KILevel < kNormalKI: mKIdialog = KIMicro.dialog else: mKIdialog = KIMini.dialog # If the BigKI is enabled, make the chat opaque once more. if BigKI.dialog.isEnabled(): mKIdialog.setForeColor(-1, -1, -1, self.originalForeAlpha) mKIdialog.setSelectColor(-1, -1, -1, self.originalSelectAlpha) mKIdialog.refreshAllControls() # Otherwise, add full transparency and hide everything. else: mKIdialog.setForeColor(-1, -1, -1, 0) mKIdialog.setSelectColor(-1, -1, -1, 0) mKIdialog.refreshAllControls() if self.KILevel == kNormalKI: playerlist = ptGUIControlListBox(mKIdialog.getControlFromTag(kGUI.PlayerList)) playerlist.hide() self.chatMgr.fadeMode = kChat.FadeDone #~~~~~~# # Ages # #~~~~~~# ## Determines whether or not the player can invite visitors to an Age. def CanAgeInviteVistors(self, ageInfo, link): # Make sure it's not a special Age. try: for Age in kAges.NoInvite: if Age == ageInfo.getAgeFilename(): return False except AttributeError: pass # Make sure that the Age has not been deleted. if link.getVolatile(): return False # Make sure the player has a default link to this Age. # If not, the Age has not yet been finished. spawnPoints = link.getSpawnPoints() for spawnlink in spawnPoints: if spawnlink.getTitle() == "Default": return True return False ## Determines if the Age is the player's Neighborhood. def IsAgeMyNeighborhood(self, ageInfo): try: hoodGUID = ptVault().getLinkToMyNeighborhood().getAgeInfo().getAgeInstanceGuid() if not isinstance(hoodGUID, str) or not hoodGUID: PtDebugPrint(u"xKI.IsAgeMyNeighborhood(): Neighborhood GUID not valid.", level=kWarningLevel) # Can't trust this test, try a different one. if ageInfo.getAgeFilename() == "Neighborhood": return True else: if ageInfo.getAgeInstanceGuid() == hoodGUID: return True except AttributeError: pass return False #~~~~~~~~~~~# # Age Names # #~~~~~~~~~~~# ## Returns the formatted and filtered name of an Age instance. def GetAgeInstanceName(self, ageInfo=None): if ageInfo is None: ageInfo = PtGetAgeInfo() if ageInfo is not None: if ageInfo.getAgeInstanceName() == "D'ni-Rudenna": sdl = xPsnlVaultSDL() if sdl["TeledahnPoleState"][0] > 5 or sdl["KadishPoleState"][0] > 5 or sdl["GardenPoleState"][0] > 5 or sdl["GarrisonPoleState"][0] > 5: pass else: return "Unknown" if ageInfo.getAgeInstanceName() == "Ae'gura": return "D'ni-Ae'gura" return FilterAgeName(ageInfo.getAgeInstanceName()) else: return "?UNKNOWN?" ## Returns the file name of the specified Age. def GetAgeFileName(self, ageInfo=None): if ageInfo is None: ageInfo = PtGetAgeInfo() if ageInfo is not None: return ageInfo.getAgeFilename() else: return "?UNKNOWN?" #~~~~~~~~# # Limits # #~~~~~~~~# ## Update the used-up space on the KI. def UpdateKIUsage(self): usage = ptVault().getKIUsage() self.numberOfPictures = usage[0] self.numberOfNotes = usage[1] self.numberOfMarkerFolders = usage[2] try: self.numberOfMarkers = self.markerGameManager.marker_total except: self.numberOfMarkers = -1 ## Check if the player has reached his limit of picture space. def CanTakePicture(self): self.UpdateKIUsage() if kLimits.MaxPictures == -1 or self.numberOfPictures < kLimits.MaxPictures: return True return False ## Check if the player has reached his limit of journal notes space. def CanMakeNote(self): self.UpdateKIUsage() if kLimits.MaxNotes == -1 or self.numberOfNotes < kLimits.MaxNotes: return True return False ## Check if the player has reached his limit of Marker Games. def CanMakeMarkerGame(self): self.UpdateKIUsage() if kLimits.MaxMarkerFolders == -1 or self.numberOfMarkerFolders < kLimits.MaxMarkerFolders: return True return False ## Check if the player has reached his limit of markers for a Marker Game. def CanMakeMarker(self): self.UpdateKIUsage() if kLimits.MaxMarkers == -1 or self.numberOfMarkers < kLimits.MaxMarkers: return True return False #~~~~~~~~# # Errors # #~~~~~~~~# ## Displays a OK dialog-based error message to the player. def ShowKIFullErrorMsg(self, msg): self.YNWhatReason = kGUI.YNKIFull reasonField = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID)) reasonField.setStringW(msg) yesButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesButtonID)) yesButton.hide() yesBtnText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesButtonTextID)) yesBtnText.hide() noBtnText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.NoButtonTextID)) noBtnText.setStringW(PtGetLocalizedString("KI.YesNoDialog.OKButton")) KIYesNo.dialog.show() ## Display an error message in the SendTo field. def SetSendToErrorMessage(self, message): self.BKPlayerSelected = None sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine)) sendToField.setStringW(U"<" + unicode(message) + U">") sendToButton = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKIToPlayerButton)) sendToButton.hide() #~~~~~~~~~~~~~# # Invitations # #~~~~~~~~~~~~~# ## Invite another player to visit the player's Age. def InviteToVisit(self, playerID, ageInfo): whereToLink = ptAgeLinkStruct() whereToLink.setAgeInfo(ageInfo.asAgeInfoStruct()) ptVault().invitePlayerToAge(whereToLink, playerID) self.SendInviteRevoke(playerID, ageInfo.getDisplayName(), "KI.Invitation.VisitTitle", "KI.Invitation.VisitBody") ## Send an invitation or a revocation to another player. def SendInviteRevoke(self, playerID, ageName, title, message): localPlayer = PtGetLocalPlayer() invite = ptVaultTextNoteNode(0) invite.noteSetText(PtGetLocalizedString(message, [ageName, localPlayer.getPlayerName()])) invite.noteSetTitle(PtGetLocalizedString(title, [ageName])) invite.sendTo(playerID) #~~~~~~~~~~~~~~~~~# # New Item Alerts # #~~~~~~~~~~~~~~~~~# ## Check the Inbox for unseen messages. def CheckInboxForUnseen(self): inFolder = ptVault().getInbox() if inFolder is not None: inRefList = inFolder.getChildNodeRefList() for inRef in inRefList: if not inRef.beenSeen(): self.AlertKIStart() ## Start the KI Alert if it's not already active. def AlertKIStart(self): if self.KILevel >= kNormalKI: PtFlashWindow() if not self.alertTimerActive: PtDebugPrint(u"xKI.AlertKIStart(): Show KI alert.", level=kDebugDumpLevel) NewItemAlert.dialog.show() KIAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertKIAlert)) self.alertTimeToUse = kAlertTimeDefault KIAlert.show() ## Start the Book Alert if it's not already active. def AlertBookStart(self, time=kAlertTimeDefault): if not self.alertTimerActive: PtDebugPrint(u"xKI.AlertBookStart(): Show Book Alert.", level=kDebugDumpLevel) NewItemAlert.dialog.show() bookAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertBookAlert)) self.alertTimeToUse = time bookAlert.show() ## Stop all alerts, by hiding their dialogs. def AlertStop(self): self.alertTimerActive = False NewItemAlert.dialog.hide() KIAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertKIAlert)) KIAlert.hide() bookAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertBookAlert)) bookAlert.hide() ## Starts the alert timer if it's not already active. def AlertStartTimer(self): if not self.alertTimerActive: self.alertTimerActive = True PtAtTimeCallback(self.key, self.alertTimeToUse, kTimers.AlertHide) #~~~~~~~~~~~~~# # Player List # #~~~~~~~~~~~~~# ## Tries to scroll up the list of players. def ScrollPlayerList(self, direction): if self.KILevel == kMicroKI: return elif self.KILevel == kMicroKI: mKIdialog = KIMicro.dialog else: mKIdialog = KIMini.dialog control = ptGUIControlListBox(KIMini.dialog.getControlFromTag(kGUI.PlayerList)) currPos = control.getScrollPos() if direction == 1: if currPos < control.getScrollRange(): PtDebugPrint(u"xKI.ScrollPlayerList(): Scrolling player list up from {} to {}.".format(currPos, currPos + 1), level=kDebugDumpLevel) control.setScrollPos(currPos + 1) else: PtDebugPrint(u"xKI.ScrollPlayerList(): Not scrolling player list up from {}.".format(currPos), level=kDebugDumpLevel) else: if currPos > 0: PtDebugPrint(u"xKI.ScrollPlayerList(): Scrolling player list down from {} to {}.".format(currPos, currPos - 1), level=kDebugDumpLevel) control.setScrollPos(currPos - 1) else: PtDebugPrint(u"xKI.ScrollPlayerList(): Not scrolling player list down from {}.".format(currPos), level=kDebugDumpLevel) self.CheckScrollButtons() mKIdialog.refreshAllControls() self.ResetFadeState() ## Checks to see if the player list scroll buttons should be visible. def CheckScrollButtons(self): if self.KILevel == kMicroKI: return elif self.KILevel == kMicroKI: mKIdialog = KIMicro.dialog else: mKIdialog = KIMini.dialog control = ptGUIControlListBox(KIMini.dialog.getControlFromTag(kGUI.PlayerList)) currentPos = control.getScrollPos() PtDebugPrint(u"xKI.CheckScrollButtons(): Current position = {} and range = {}.".format(currentPos, control.getScrollRange()), level=kDebugDumpLevel) try: dbtn = ptGUIControlButton(mKIdialog.getControlFromTag(kGUI.miniPlayerListDown)) if currentPos == 0: dbtn.hide() else: dbtn.show() ubtn = ptGUIControlButton(mKIdialog.getControlFromTag(kGUI.miniPlayerListUp)) if currentPos >= control.getScrollRange(): ubtn.hide() else: ubtn.show() except KeyError: pass ## Reloads the player list with the latest values and displays them. def RefreshPlayerList(self, forceSmall=False): PtDebugPrint(u"xKI.RefreshPlayerList(): Refreshing.", level=kDebugDumpLevel) playerlist = ptGUIControlListBox(KIMini.dialog.getControlFromTag(kGUI.PlayerList)) select = playerlist.getSelection() if select >= 0 and select < len(self.BKPlayerList): self.previouslySelectedPlayer = self.BKPlayerList[select] # Vault node refs change frequently, so get the unique ID instead. if isinstance(self.previouslySelectedPlayer, ptVaultNodeRef): PtDebugPrint(u"xKI.RefreshPlayerList(): Getting the vault node ID of the selected player.", level=kDebugDumpLevel) self.previouslySelectedPlayer = self.previouslySelectedPlayer.getChild().getID() else: self.previouslySelectedPlayer = None self.BKPlayerList = [] vault = ptVault() # Age Players ageMembers = KIFolder(PtVaultStandardNodes.kAgeMembersFolder) if ageMembers is not None: self.BKPlayerList.append(ageMembers) self.BKPlayerList += PtGetPlayerListDistanceSorted() else: self.BKPlayerList.append("?NOAgeMembers?") # Buddies List buddies = vault.getBuddyListFolder() if buddies is not None: self.BKPlayerList.append(buddies) self.BKPlayerList += self.RemoveOfflinePlayers(buddies.getChildNodeRefList()) else: self.BKPlayerList.append("?NOBuddies?") # Neighbors List neighbors = GetNeighbors() if neighbors is not None: self.BKPlayerList.append(neighbors) onlinePlayers = self.RemoveOfflinePlayers(neighbors.getChildNodeRefList()) FilterPlayerInfoList(onlinePlayers) self.BKPlayerList += onlinePlayers else: self.BKPlayerList.append("NEIGHBORS") # All Players (INTERNAL CLIENT ONLY) if PtIsInternalRelease(): allPlayers = vault.getAllPlayersFolder() if allPlayers: self.BKPlayerList.append(allPlayers) onlinePlayers = self.RemoveOfflinePlayers(allPlayers.getChildNodeRefList()) FilterPlayerInfoList(onlinePlayers) self.BKPlayerList += onlinePlayers # don't append a dummy -- we don't care if our vault doesn't have a copy of AllPlayers # Age Devices if self.folderOfDevices and BigKI.dialog.isEnabled() and not forceSmall: self.BKPlayerList.append(self.folderOfDevices) for device in self.folderOfDevices: self.BKPlayerList.append(device) # Pass the new value to the chat manager. self.chatMgr.BKPlayerList = self.BKPlayerList # Refresh the display. self.RefreshPlayerListDisplay() ## Removes the offline players in a list of players. def RemoveOfflinePlayers(self, playerlist): onlineList = [] ignores = ptVault().getIgnoreListFolder() for plyr in playerlist: if isinstance(plyr, ptVaultNodeRef): PLR = plyr.getChild() PLR = PLR.upcastToPlayerInfoNode() if PLR is not None and PLR.getType() == PtVaultNodeTypes.kPlayerInfoNode: if PLR.playerIsOnline(): if not ignores.playerlistHasPlayer(PLR.playerGetID()): onlineList.append(plyr) return onlineList ## Refresh the display of the player list. def RefreshPlayerListDisplay(self): playerlist = ptGUIControlListBox(KIMini.dialog.getControlFromTag(kGUI.PlayerList)) scrollPos = playerlist.getScrollPos() playerlist.lock() playerlist.clearAllElements() newSelection = -1 # Assume no selection. idx = 0 for plyr in self.BKPlayerList: if isinstance(plyr, DeviceFolder): playerlist.closeBranch() playerlist.addBranchW(plyr.name.upper(), 1) elif isinstance(plyr, Device): playerlist.addStringWithColor(plyr.name, kColors.DniSelectable, kSelectUseGUIColor) elif isinstance(plyr, ptVaultNodeRef): PLR = plyr.getChild() PLR = PLR.upcastToPlayerInfoNode() if PLR is not None and PLR.getType() == PtVaultNodeTypes.kPlayerInfoNode: if PLR.playerIsOnline(): playerlist.addStringWithColor(PLR.playerGetName(), kColors.DniSelectable, kSelectUseGUIColor) else: playerlist.addStringWithColor(PLR.playerGetName(), kColors.AgenBlueDk,kSelectDetermined) else: PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Unknown player element type {}.".format(PLR.getType()), level=kErrorLevel) elif isinstance(plyr, ptPlayer): preText = " " postText = " " if plyr.getPlayerID() != 0: if plyr.getDistanceSq() < PtMaxListenDistSq(): preText = ">" postText = "<" if plyr.getPlayerName() != "": playerlist.addStringWithColor(preText + plyr.getPlayerName() + postText, kColors.DniSelectable, kSelectUseGUIColor) else: if plyr.getPlayerID() != 0: playerlist.addStringWithColor(preText + "[ID:{:08d}]".format(plyr.getPlayerID()) + postText, kColors.DniSelectable, kSelectDetermined) else: playerlist.addStringWithColor(preText + "?unknown user?" + postText, kColors.DniSelectable, kSelectDetermined) elif isinstance(plyr, KIFolder): playerlist.closeBranch() playerlist.addBranchW(plyr.name.upper(), 1) elif isinstance(plyr, ptVaultPlayerInfoListNode): # It's a player list, display its name. fldrType = plyr.folderGetType() if fldrType == PtVaultStandardNodes.kAgeOwnersFolder: fldrType = PtVaultStandardNodes.kHoodMembersFolder playerlist.closeBranch() playerlist.addBranchW(xLocTools.FolderIDToFolderName(fldrType).upper(), 1) elif isinstance(plyr, ptVaultMarkerGameNode): # its a marker list, display its name playerlist.closeBranch() playerlist.addBranchW(plyr.folderGetName(), 1) elif isinstance(plyr, str): playerlist.closeBranch() playerlist.addBranchW(plyr, 1) else: PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Unknown list type ", plyr, level=kErrorLevel) # Is it the selected player? if self.previouslySelectedPlayer is not None: PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): A previously selected player.", self.previouslySelectedPlayer, level=kDebugDumpLevel) # Fix for vaultNodeRef comparisons (which no longer work). if isinstance(self.previouslySelectedPlayer, long) and isinstance(plyr, ptVaultNodeRef): plyr = plyr.getChild().getID() # Set to the ID; let the testing begin. # Was it the same class? if self.previouslySelectedPlayer.__class__ == plyr.__class__: PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Previous player matches class.", level=kDebugDumpLevel) # And finally, was it the same object? if self.previouslySelectedPlayer == plyr: PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Previous player matches object, setting to {}.".format(idx), level=kDebugDumpLevel) newSelection = idx # Found him, stop looking. self.previouslySelectedPlayer = None else: PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Previous player does not match object.", level=kDebugDumpLevel) else: PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Previous player does not match class.", level=kDebugDumpLevel) idx += 1 # Is there no selection? if newSelection == -1: # Select the first item in the list. newSelection = 0 # Put the caret back to the regular prompt. caret = ptGUIControlTextBox(KIMini.dialog.getControlFromTag(kGUI.ChatCaretID)) caret.setString(">") PtDebugPrint(u"xKI.RefreshPlayerListDisplay(): Setting new selection to {}.".format(newSelection), level=kDebugDumpLevel) playerlist.setSelection(newSelection) self.previouslySelectedPlayer = None # Re-establish the selection the player had before. playerlist.setScrollPos(scrollPos) playerlist.unlock() self.CheckScrollButtons() # Set the SendTo button. sendToButton = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKIToPlayerButton)) if self.BKPlayerSelected is None: sendToButton.hide() else: # Make sure that the person is still here (this shouldn't happen). if isinstance(self.BKPlayerSelected, DeviceFolder): self.BKPlayerSelected = None sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine)) sendToField.setString(" ") sendToButton.hide() # Otherwise see if the device is still in range. elif isinstance(self.BKPlayerSelected, Device): try: self.folderOfDevices.index(self.BKPlayerSelected) except ValueError: # No longer in the list of devices; remove it. self.BKPlayerSelected = None sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine)) sendToField.setString(" ") sendToButton.hide() #~~~~~~~~~~# # Settings # #~~~~~~~~~~# ## Refresh the KI configuration settings to match the current values. def RefreshKISettings(self): fontSizeSlider = ptGUIControlKnob(KISettings.dialog.getControlFromTag(kGUI.BKIKIFontSize)) fontSize = self.GetFontSize() # Find font size in font table. whichFont = 0 for fs in kChat.FontSizeList: if fontSize <= fs: break whichFont += 1 if whichFont >= len(kChat.FontSizeList): whichFont = len(kChat.FontSizeList) - 1 slidePerFont = float(fontSizeSlider.getMax() - fontSizeSlider.getMin() + 1.0) / float(len(kChat.FontSizeList)) FSslider = int(slidePerFont * whichFont + 0.25) fontSizeSlider.setValue(FSslider) fadeTimeSlider = ptGUIControlKnob(KISettings.dialog.getControlFromTag(kGUI.BKIKIFadeTime)) slidePerTime = float(fadeTimeSlider.getMax() - fadeTimeSlider.getMin()) / float(kChat.FadeTimeMax) if not self.chatMgr.fadeEnableFlag: self.chatMgr.ticksOnFull = kChat.FadeTimeMax FTslider = slidePerTime * self.chatMgr.ticksOnFull fadeTimeSlider.setValue(FTslider) onlyPMCheckbox = ptGUIControlCheckBox(KISettings.dialog.getControlFromTag(kGUI.BKIKIOnlyPM)) onlyPMCheckbox.setChecked(self.onlyGetPMsFromBuddies) ## Refresh the volume settings to match the current values. def RefreshVolumeSettings(self): audio = ptAudioControl() soundFX = ptGUIControlValue(KIVolumeExpanded.dialog.getControlFromTag(kGUI.BKISoundFXVolSlider)) setting = audio.getSoundFXVolume() soundFX.setValue(setting * 10) music = ptGUIControlValue(KIVolumeExpanded.dialog.getControlFromTag(kGUI.BKIMusicVolSlider)) setting = audio.getMusicVolume() music.setValue(setting * 10) voice = ptGUIControlValue(KIVolumeExpanded.dialog.getControlFromTag(kGUI.BKIVoiceVolSlider)) setting = audio.getVoiceVolume() voice.setValue(setting * 10) ambience = ptGUIControlValue(KIVolumeExpanded.dialog.getControlFromTag(kGUI.BKIAmbienceVolSlider)) setting = audio.getAmbienceVolume() ambience.setValue(setting * 10) miclevel = ptGUIControlValue(KIVolumeExpanded.dialog.getControlFromTag(kGUI.BKIMicLevelSlider)) setting = audio.getMicLevel() miclevel.setValue(setting * 10) guivolume = ptGUIControlValue(KIVolumeExpanded.dialog.getControlFromTag(kGUI.BKIGUIVolSlider)) setting = audio.getGUIVolume() guivolume.setValue(setting * 10) ## Refresh the Age Owner settings to match the current values. def RefreshAgeOwnerSettings(self): # Is it actually going to display, or is it just an update? if BigKI.dialog.isEnabled() and self.BKRightSideMode == kGUI.BKAgeOwnerExpanded: try: # Get the selected Age config setting. myAge = self.BKConfigFolderDict[self.BKConfigListOrder[self.BKFolderSelected]] except LookupError: myAge = None if myAge is not None: title = ptGUIControlTextBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleTB)) title.setString(GetAgeName(myAge)) titlebtn = ptGUIControlButton(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleBtn)) titlebtn.enable() titleEdit = ptGUIControlEditBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleEditbox)) titleEdit.hide() status = ptGUIControlTextBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerStatusTB)) visitors = myAge.getCanVisitFolder() owners = myAge.getAgeOwnersFolder() numvisitors = visitors.getChildNodeCount() numowners = owners.getChildNodeCount() vsess = "s" if numvisitors == 1: vsess = "" osess = "s" if numowners == 1: osess = "" # For now, Ages can be made public/private only through the Nexus. makepublicTB = ptGUIControlTextBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerMakePublicTB)) makepublicBtn = ptGUIControlButton(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerMakePublicBtn)) makepublicBtn.disable() makepublicTB.hide() makepublicTB.setString(" ") status.setStringW(PtGetLocalizedString("KI.Neighborhood.AgeOwnedStatus", [str(numowners), str(osess), str(numvisitors), str(vsess)])) descript = ptGUIControlMultiLineEdit(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerDescription)) encoded = buffer(myAge.getAgeDescription()) descript.setEncodedBuffer(encoded) #~~~~~~~~# # miniKI # #~~~~~~~~# ## Refresh the display of the miniKI indicator bars. def RefreshMiniKIMarkerDisplay(self): PtDebugPrint(u"xKI.RefreshMiniKIMarkerDisplay(): Refreshing {}:{}.".format(self.gMarkerGottenNumber, self.gMarkerToGetNumber), level=kDebugDumpLevel) if self.KILevel > kMicroKI: if self.gMarkerGottenNumber == self.gMarkerToGetNumber and (self.gMarkerToGetNumber % 25) == 0: xMyMaxMarkers = self.gMarkerToGetNumber xMyGotMarkers = self.gMarkerGottenNumber else: xMyGotMarkers = self.gMarkerGottenNumber % 25 if self.gMarkerGottenNumber >= math.floor((self.gMarkerToGetNumber / 25)) * 25: xMyMaxMarkers = self.gMarkerToGetNumber % 25 else: xMyMaxMarkers = 25 for mcbID in range(kGUI.miniMarkerIndicator01, kGUI.miniMarkerIndicatorLast + 1): mcb = ptGUIControlProgress(KIMini.dialog.getControlFromTag(mcbID)) markerNumber = mcbID - kGUI.miniMarkerIndicator01 + 1 try: if not self.gKIMarkerLevel or markerNumber > xMyMaxMarkers: mcb.setValue(kGUI.miniMarkerColors["off"]) elif markerNumber <= xMyMaxMarkers and markerNumber > xMyGotMarkers: mcb.setValue(kGUI.miniMarkerColors[self.gMarkerToGetColor]) else: mcb.setValue(kGUI.miniMarkerColors[self.gMarkerGottenColor]) except LookupError: PtDebugPrint(u"xKI.RefreshMiniKIMarkerDisplay(): Couldn't find color, defaulting to off.", level=kWarningLevel) mcb.setValue(kGUI.miniMarkerColors["off"]) btnmtDrip = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZDrip)) btnmtActive = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZActive)) btnmtPlaying = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZMarkerGameActive)) btnmtInRange = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZMarkerInRange)) btnmgNewMarker = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGNewMarker)) btnmgNewGame = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGNewGame)) btnmgInactive = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGInactive)) if self.gKIMarkerLevel: btnmtDrip.hide() if self.gMarkerToGetNumber > self.gMarkerGottenNumber: if self.gGZMarkerInRange: btnmtInRange.show() btnmtPlaying.hide() btnmtActive.hide() else: btnmtInRange.hide() btnmtPlaying.show() btnmtActive.hide() else: btnmtPlaying.hide() btnmtInRange.hide() btnmtActive.show() else: btnmtDrip.hide() btnmtActive.hide() btnmtPlaying.hide() btnmtInRange.hide() # Should the Marker Game GUI be displayed? if self.gKIMarkerLevel >= kKIMarkerNormalLevel and not self.markerGameManager.is_cgz: btnmtDrip.hide() btnmtActive.hide() btnmtPlaying.hide() btnmtInRange.hide() try: showMarkers = self.markerGameManager.markers_visible except: showMarkers = False try: selectedMarker = self.markerGameManager.selected_marker_id except : selectedMarker = -1 if self.markerGameManager.playing: btnmgNewMarker.hide() btnmgNewGame.hide() btnmgInactive.show() elif showMarkers and selectedMarker < 0: btnmgNewMarker.show() btnmgNewGame.hide() btnmgInactive.hide() else: btnmgNewMarker.hide() btnmgNewGame.show() btnmgInactive.hide() else: btnmgNewMarker.hide() btnmgNewGame.hide() btnmgInactive.hide() ## Toggle between the miniKI and the BigKI. def ToggleKISize(self): if self.KILevel > kMicroKI and (not self.KIDisabled or BigKI.dialog.isEnabled()): if self.KIDisabled and BigKI.dialog.isEnabled(): self.ToggleMiniKI() return if not self.waitingForAnimation: toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID)) if BigKI.dialog.isEnabled(): self.HideBigKI() # Can't be chatting. self.chatMgr.ToggleChatMode(0) KIBlackbar.dialog.show() if self.lastminiKICenter is not None: dragbar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar)) dragbar.setObjectCenter(self.lastminiKICenter) dragbar.unanchor() self.lastminiKICenter = None # Refresh the player list, because it will be the shorter version. self.RefreshPlayerList(True) toggleCB.setChecked(0) else: # If there is nothing showing, just bring up the miniKI. if not KIMini.dialog.isEnabled(): self.chatMgr.ClearBBMini(0) # Bring up the BigKI, then the miniKI. else: self.waitingForAnimation = True KIBlackbar.dialog.hide() KIMini.dialog.hide() # Can't be chatting. self.chatMgr.ToggleChatMode(0) # Show the BigKI. BigKI.dialog.show() # Save current location and snap back to original. if self.originalminiKICenter is not None: dragbar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar)) self.lastminiKICenter = dragbar.getObjectCenter() PtDebugPrint(u"xKI.ToggleKISize(): Distance to original = {}.".format(self.lastminiKICenter.distance(self.originalminiKICenter)), level=kDebugDumpLevel) # If they are close, then snap it to original. if self.lastminiKICenter.distance(self.originalminiKICenter) < 0.027: self.lastminiKICenter = self.originalminiKICenter dragbar.setObjectCenter(self.originalminiKICenter) dragbar.anchor() KIMini.dialog.show() toggleCB.setChecked(1) ## Put away the miniKI (and the BigKI, if up). def ToggleMiniKI(self, forceOpen = 0): if self.KILevel > kMicroKI and (not self.KIDisabled or KIMini.dialog.isEnabled()): if KIMini.dialog.isEnabled(): KIMini.dialog.hide() # Put the miniKI back where it used to be. if self.lastminiKICenter is not None: dragbar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar)) dragbar.setObjectCenter(self.lastminiKICenter) dragbar.unanchor() self.lastminiKICenter = None if BigKI.dialog.isEnabled(): self.HideBigKI() KIBlackbar.dialog.show() self.chatMgr.ClearBBMini(-1) # Put the toggle button back to the miniKI setting. toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID)) toggleCB.setChecked(0) self.sawTheKIAtleastOnce = True else: # If the miniKI is hidden, show it. if forceOpen: self.chatMgr.ClearBBMini(0) ## Take a screenshot through the miniKI. def TakePicture(self): if not self.takingAPicture and not self.waitingForAnimation: # Ignoring the KIDisabled flag here, because screenshots can be # taken even with certain GUIs showing. if self.KILevel > kMicroKI: if self.CanTakePicture(): self.takingAPicture = True if not PtIsGUIModal(): # Hide everything to take a picture. KIBlackbar.dialog.hide() KIMini.dialog.hide() self.HideBigKIMode() BigKI.dialog.hide() # Put the toggle button back to BigKI. toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID)) toggleCB.setChecked(1) # Wait a moment, then take the picture. PtAtTimeCallback(self.key, 0.25, kTimers.TakeSnapShot) else: # Put up an error message. self.ShowKIFullErrorMsg(PtGetLocalizedString("KI.Messages.FullImages")) ## Create a new Journal entry through the miniKI. def MiniKICreateJournalNote(self): if self.takingAPicture or self.waitingForAnimation: return if self.KILevel > kMicroKI and not self.KIDisabled: if self.CanMakeNote(): KIBlackbar.dialog.hide() # Put the toggle button back to BigKI. toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID)) toggleCB.setChecked(1) # Create the actual journal entry. self.BigKICreateJournalNote() # Make sure that the player is in Journal mode. modeselector = ptGUIControlRadioGroup(BigKI.dialog.getControlFromTag(kGUI.BKRadioModeID)) modeselector.setValue(0) # Set things up so that when the BigKI shows, it goes into edit mode. if self.BKRightSideMode != kGUI.BKJournalExpanded: self.HideBigKIMode() self.BKRightSideMode = kGUI.BKJournalExpanded # Reset the top line and selection. self.BigKIRefreshFolderDisplay() self.BigKIDisplayJournalEntry() # Setup to edit the caption of the note. self.BigKIEnterEditMode(kGUI.BKEditFieldJRNTitle) if BigKI.dialog.isEnabled(): self.ShowBigKIMode() else: # Put the miniKI on top. KIMini.dialog.hide() BigKI.dialog.show() KIMini.dialog.show() # Was just the miniKI showing? if self.lastminiKICenter is None: if self.originalminiKICenter is not None: dragbar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar)) self.lastminiKICenter = dragbar.getObjectCenter() dragbar.setObjectCenter(self.originalminiKICenter) dragbar.anchor() else: # Put up an error message. self.ShowKIFullErrorMsg(PtGetLocalizedString("KI.Messages.FullNotes")) #~~~~~~~# # BigKI # #~~~~~~~# ## Open up and show the BigKI. def ShowBigKI(self): self.waitingForAnimation = True curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode() toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID)) toggleCB.disable() if curBrainMode == PtBrainModes.kNonGeneric: PtDebugPrint(u"xKI.ShowBigKI(): Entering LookingAtKI mode.", level=kDebugDumpLevel) PtAvatarEnterLookingAtKI() self.isPlayingLookingAtKIMode = True PtDisableMovementKeys() KIOnResp.run(self.key, netPropagate=0) ## Close and hide the BigKI. def HideBigKI(self): self.waitingForAnimation = True toggleCB = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniToggleBtnID)) toggleCB.disable() self.HideBigKIMode() # Make sure the player was actually looking at the KI. if self.isPlayingLookingAtKIMode: PtDebugPrint(u"xKI.HideBigKI(): Leaving LookingAtKI mode.", level=kDebugDumpLevel) PtAvatarExitLookingAtKI() self.isPlayingLookingAtKIMode = False PtEnableMovementKeys() KIOffResp.run(self.key, netPropagate=0) ## Show a new mode inside the BigKI. # This can be an expanded picture, a player entry, a list... def ShowBigKIMode(self): if BigKI.dialog.isEnabled(): # Hide up/down scroll buttons. upbtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKLMUpButton)) upbtn.hide() dwnbtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKLMDownButton)) dwnbtn.hide() if self.BKRightSideMode == kGUI.BKListMode: KIListModeDialog.dialog.show() self.BigKIOnlySelectedToButtons() self.BKCurrentContent = None self.BKGettingPlayerID = False elif self.BKRightSideMode == kGUI.BKJournalExpanded: KIJournalExpanded.dialog.show() if self.IsContentMutable(self.BKCurrentContent): self.BigKIInvertToFolderButtons() else: self.BigKIOnlySelectedToButtons() self.BKGettingPlayerID = False elif self.BKRightSideMode == kGUI.BKPictureExpanded: KIPictureExpanded.dialog.show() if self.IsContentMutable(self.BKCurrentContent): self.BigKIInvertToFolderButtons() else: self.BigKIOnlySelectedToButtons() self.BKGettingPlayerID = False elif self.BKRightSideMode == kGUI.BKPlayerExpanded: KIPlayerExpanded.dialog.show() # If the expanded player is ourselves, then no move buttons. localPlayer = PtGetLocalPlayer() if self.BKCurrentContent is not None: if isinstance(self.BKCurrentContent, ptPlayer): if self.BKCurrentContent.getPlayerID() == localPlayer.getPlayerID(): self.BigKIOnlySelectedToButtons() return # Otherwise assume that it's a plVaultNodeRef. else: elem = self.BKCurrentContent.getChild() if elem.getType() == PtVaultNodeTypes.kPlayerInfoNode: elem = elem.upcastToPlayerInfoNode() if elem.playerGetID() == localPlayer.getPlayerID(): self.BigKIOnlySelectedToButtons() return self.BigKIInvertToFolderButtons() elif self.BKRightSideMode == kGUI.BKVolumeExpanded: KIVolumeExpanded.dialog.show() self.BigKIOnlySelectedToButtons() self.BKCurrentContent = None self.BKGettingPlayerID = False elif self.BKRightSideMode == kGUI.BKKIExpanded: KISettings.dialog.show() self.BigKIOnlySelectedToButtons() self.BKCurrentContent = None self.BKGettingPlayerID = False elif self.BKRightSideMode == kGUI.BKAgeOwnerExpanded: KIAgeOwnerExpanded.dialog.show() self.BigKIOnlySelectedToButtons() self.BKCurrentContent = None self.BKGettingPlayerID = False elif self.BKRightSideMode == kGUI.BKMarkerListExpanded: KIMarkerFolderExpanded.dialog.show() if self.IsContentMutable(self.BKCurrentContent): self.BigKIInvertToFolderButtons() else: self.BigKIOnlySelectedToButtons() self.BKGettingPlayerID = False ## Hide an open mode in the BigKI. def HideBigKIMode(self): if self.BKRightSideMode == kGUI.BKListMode: KIListModeDialog.dialog.hide() elif self.BKRightSideMode == kGUI.BKJournalExpanded: KIJournalExpanded.dialog.hide() elif self.BKRightSideMode == kGUI.BKPictureExpanded: KIPictureExpanded.dialog.hide() elif self.BKRightSideMode == kGUI.BKPlayerExpanded: KIPlayerExpanded.dialog.hide() elif self.BKRightSideMode == kGUI.BKVolumeExpanded: KIVolumeExpanded.dialog.hide() elif self.BKRightSideMode == kGUI.BKKIExpanded: KISettings.dialog.hide() elif self.BKRightSideMode == kGUI.BKAgeOwnerExpanded: KIAgeOwnerExpanded.dialog.hide() elif self.BKRightSideMode == kGUI.BKMarkerListExpanded: KIMarkerFolderExpanded.dialog.hide() ## Switch to a new mode in the BigKI. # This hides the old mode and displays the new one, or just refreshes # the content list if it's a selection change. def ChangeBigKIMode(self, newMode): # Is the player switching to a new mode? if newMode != self.BKRightSideMode: self.HideBigKIMode() self.BKRightSideMode = newMode self.ShowBigKIMode() # Or is he changing the selection? elif newMode == kGUI.BKListMode: self.BigKIOnlySelectedToButtons() ## Set the SendTo buttons appropriately. # This will set all the little glowing arrows next to items in accordance # with the currently displayed mode. def SetBigKIToButtons(self): if self.BKRightSideMode == kGUI.BKListMode: self.BigKIOnlySelectedToButtons() elif self.BKRightSideMode == kGUI.BKJournalExpanded: if self.IsContentMutable(self.BKCurrentContent): self.BigKIInvertToFolderButtons() else: self.BigKIOnlySelectedToButtons() elif self.BKRightSideMode == kGUI.BKPictureExpanded: if self.IsContentMutable(self.BKCurrentContent): self.BigKIInvertToFolderButtons() else: self.BigKIOnlySelectedToButtons() elif self.BKRightSideMode == kGUI.BKPlayerExpanded: localPlayer = PtGetLocalPlayer() if self.BKCurrentContent is not None: if isinstance(self.BKCurrentContent, ptPlayer): if self.BKCurrentContent.getPlayerID() == localPlayer.getPlayerID(): self.BigKIOnlySelectedToButtons() return # Otherwise assume that it's a plVaultNodeRef. else: elem = self.BKCurrentContent.getChild() if elem.getType() == PtVaultNodeTypes.kPlayerInfoNode: elem = elem.upcastToPlayerInfoNode() if elem.playerGetID() == localPlayer.getPlayerID(): self.BigKIOnlySelectedToButtons() return self.BigKIInvertToFolderButtons() elif self.BKRightSideMode == kGUI.BKVolumeExpanded: self.BigKIOnlySelectedToButtons() elif self.BKRightSideMode == kGUI.BKKIExpanded: self.BigKIOnlySelectedToButtons() elif self.BKRightSideMode == kGUI.BKAgeOwnerExpanded: self.BigKIOnlySelectedToButtons() elif self.BKRightSideMode == kGUI.BKMarkerListExpanded: if self.MFdialogMode not in (kGames.MFEditing, kGames.MFEditingMarker) and self.IsContentMutable(self.BKCurrentContent): self.BigKIInvertToFolderButtons() else: self.BigKIOnlySelectedToButtons() ## Show only the selected SendTo buttons. def BigKIOnlySelectedToButtons(self): toPlayerBtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKIToPlayerButton)) toPlayerBtn.hide() self.BigKIRefreshFolderDisplay() # Hide all the buttons. for ID in range(kGUI.BKIToIncomingButton, kGUI.BKIToFolderButtonLast + 1): toFolder = ptGUIControlButton(BigKI.dialog.getControlFromTag(ID)) toFolder.hide() self.BigKINewContentList() ## Determines if the selected content can be sent to someone. def BigKICanShowSendToPlayer(self): # Make sure that there is a selected player. if self.BKPlayerSelected is None: return False # Make sure that it's something that can be sent to a player. if self.BKRightSideMode == kGUI.BKPlayerExpanded or self.BKRightSideMode == kGUI.BKVolumeExpanded or self.BKRightSideMode == kGUI.BKAgeOwnerExpanded: return False # Make sure that it's not the player. if isinstance(self.BKPlayerSelected, ptVaultNodeRef): plyrElement = self.BKPlayerSelected.getChild() if plyrElement is not None and plyrElement.getType() == PtVaultNodeTypes.kPlayerInfoNode: plyrElement = plyrElement.upcastToPlayerInfoNode() if plyrElement.playerGetID() == PtGetLocalClientID(): return False return True ## Hides or shows the ToPlayer buttons. def BigKIInvertToFolderButtons(self): # Setup ToPlayer button. toPlayerBtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKIToPlayerButton)) if self.BigKICanShowSendToPlayer(): toPlayerBtn.show() else: toPlayerBtn.hide() # Add the ToPlayer button to the elements. selectedButton = self.BKFolderSelected - self.BKFolderTopLine + kGUI.BKIToIncomingButton for ID in range(kGUI.BKIToIncomingButton, kGUI.BKIToFolderButtonLast + 1): toFolder = ptGUIControlButton(BigKI.dialog.getControlFromTag(ID)) if ID == selectedButton: toFolder.hide() else: # Don't show on elements that are not there or immutable. if ID - kGUI.BKIToIncomingButton <= len(self.BKFolderListOrder) - 1 - self.BKFolderTopLine: try: if self.IsFolderContentMutable(self.BKFolderLineDict[self.BKFolderListOrder[ID - kGUI.BKIToIncomingButton + self.BKFolderTopLine]]): toFolder.show() else: toFolder.hide() except LookupError: toFolder.hide() else: toFolder.hide() ## Check incoming content for the sender, and set the SendTo field. def CheckContentForSender(self, content): folder = content.getParent() if folder: folder = folder.upcastToFolderNode() if folder is not None and folder.folderGetType() == PtVaultStandardNodes.kInboxFolder: sender = content.getSaver() if sender is not None and sender.getType() == PtVaultNodeTypes.kPlayerInfoNode: sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine)) curSendTo = sendToField.getString().strip() if not curSendTo: self.BKPlayerSelected = sender sendToField.setString(sender.playerGetName()) #~~~~~~~~~~~~~~~# # BigKI Content # #~~~~~~~~~~~~~~~# ## Determines whether the specified folder can be modified. def IsFolderContentMutable(self, folder): # Make sure there is a real folder there to play with. if folder is None or not isinstance(folder, ptVaultNode): return False # If it's not really a folder but an AgeInfoNode, then it's for the canVisit player list. if folder.getType() == PtVaultNodeTypes.kAgeInfoNode: return True if folder.getType() != PtVaultNodeTypes.kPlayerInfoListNode and folder.getType() != PtVaultNodeTypes.kFolderNode: return False # Check for the incoming folder. if folder.folderGetType() == PtVaultStandardNodes.kInboxFolder: return False # Check against the AgeMembers folder. if folder.folderGetType() == PtVaultStandardNodes.kAgeMembersFolder: return False # Check for the neighborhood members folder. if folder.folderGetType() == PtVaultStandardNodes.kHoodMembersFolder: return False # Oh hayll no, you can't change AllPlayers if folder.folderGetType() == PtVaultStandardNodes.kAllPlayersFolder: return False # Check for neighborhood CanVisit folder (actually half-mutable, they can delete). if folder.folderGetType() == PtVaultStandardNodes.kAgeOwnersFolder: return False # It's not a special folder, so it's mutable. return True ## Determines whether this is a hidden folder. def IsFolderHidden(self, ageFolder): if ageFolder.folderGetName() == "Hidden": return True return False ## Determines whether the content Node Reference is mutable. def IsContentMutable(self, nodeRef): # Get its parent folder. if isinstance(nodeRef, ptVaultNodeRef): folder = self.BKCurrentContent.getParent() if folder: folder = folder.upcastToFolderNode() if folder: if folder.folderGetType() == PtVaultStandardNodes.kGlobalInboxFolder: return False return True #~~~~~~~~~~~~~~# # BigKI Values # #~~~~~~~~~~~~~~# ## Sets some global values for the KI should never change. def BigKISetStatics(self): ageText = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKICurAgeNameID)) ageName = GetAgeName().replace("(null)", "").strip() PtDebugPrint(u"xKI.BigKISetStatics(): Displaying age name of {}.".format(ageName), level=kDebugDumpLevel) ageText.setStringW(ageName) playerText = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKPlayerName)) IDText = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKPlayerID)) localPlayer = PtGetLocalPlayer() playerText.setString(localPlayer.getPlayerName()) IDText.setString("[ID:{:08d}]".format(localPlayer.getPlayerID())) self.UpdatePelletScore() self.BigKIRefreshHoodStatics() ## Sets some Neighborhood-specific values for the KI that won't change. def BigKIRefreshHoodStatics(self, neighborhood=None): neighborText = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKNeighborhoodAndID)) # If a neighborhood was not specified, get the one from the player's Vault. if not neighborhood: neighborhood = GetNeighborhood() if neighborhood is not None: neighborName = xLocTools.LocalizeAgeName(neighborhood.getDisplayName()) if neighborName == U"": neighborName = PtGetLocalizedString("KI.Neighborhood.NoName") neighborText.setStringW(PtGetLocalizedString("KI.Neighborhood.BottomLine", [xLocTools.MemberStatusString(), neighborName])) else: neighborText.setStringW(PtGetLocalizedString("KI.Neighborhood.None")) ## Sets some global changing values for the KI. def BigKISetChanging(self): # Use the D'ni time for this Age. dniTime = PtGetDniTime() if dniTime: tupTime = time.gmtime(dniTime) if self.timeBlinker: curTime = unicode(time.strftime(PtGetLocalizedString("Global.Formats.DateTime"), tupTime)) self.timeBlinker = False else: curTime = unicode(time.strftime(PtGetLocalizedString("Global.Formats.DateTime"), tupTime)) self.timeBlinker = True else: curTime = PtGetLocalizedString("KI.Errors.TimeBroke") if curTime != self.previousTime: timeText = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKICurTimeID)) timeText.setStringW(curTime) self.previousTime = curTime # Set the D'ni GPS coordinates. gps1 = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIGPS1TextID)) gps2 = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIGPS2TextID)) gps3 = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIGPS3TextID)) self.dniCoords.update() if self.gKIMarkerLevel == kKIMarkerNormalLevel: sdl = xPsnlVaultSDL() if sdl["GPSEnabled"][0]: gps1.setString(str(self.dniCoords.getTorans())) gps2.setString(str(self.dniCoords.getHSpans())) gps3.setString(str(self.dniCoords.getVSpans())) else: gps1.setString("0") gps2.setString("0") gps3.setString("0") else: gps1.setString("0") gps2.setString("0") gps3.setString("0") PtAtTimeCallback(self.key, 5, kTimers.BKITODCheck) #~~~~~~~~~~~~~~~~~~# # BigKI Refreshing # #~~~~~~~~~~~~~~~~~~# ## Check to see if a folder needs to be refreshed. def BigKICheckFolderRefresh(self, folder=None): if folder is not None: if folder.getType() == PtVaultNodeTypes.kPlayerInfoListNode: self.RefreshPlayerList() # Otherwise, check everything just in case. else: self.RefreshPlayerList() # Check content refresh only if using the BigKI. if self.KILevel > kMicroKI: self.BigKIRefreshContentList() self.BigKIRefreshContentListDisplay() ## Check to see if the current content has changed since. def BigKICheckContentRefresh(self, content): if self.BKCurrentContent is not None and content == self.BKCurrentContent: if self.BKRightSideMode == kGUI.BKListMode: self.BigKIRefreshContentListDisplay() elif self.BKRightSideMode == kGUI.BKJournalExpanded: self.BigKIDisplayJournalEntry() elif self.BKRightSideMode == kGUI.BKPictureExpanded: self.BigKIDisplayPicture() elif self.BKRightSideMode == kGUI.BKPlayerExpanded: self.BigKIDisplayPlayerEntry() elif self.BKRightSideMode == kGUI.BKMarkerListExpanded: self.BigKIDisplayMarkerGame() ## Check to see if the current content element has changed since. def BigKICheckElementRefresh(self, element): if self.BKCurrentContent is not None: if isinstance(self.BKCurrentContent,ptVaultNodeRef) and element == self.BKCurrentContent.getChild(): if self.BKRightSideMode == kGUI.BKListMode: self.BigKIRefreshContentListDisplay() elif self.BKRightSideMode == kGUI.BKJournalExpanded: self.BigKIDisplayJournalEntry() elif self.BKRightSideMode == kGUI.BKPictureExpanded: self.BigKIDisplayPicture() elif self.BKRightSideMode == kGUI.BKPlayerExpanded: self.BigKIDisplayPlayerEntry() elif self.BKRightSideMode == kGUI.BKMarkerListExpanded: self.BigKIDisplayMarkerGame() ## Refresh the list of folders for the Inbox and Age Journal folders. def BigKIRefreshFolderList(self): # Remember selected and what position in the list the player is at. vault = ptVault() # Get Journal folder information. if xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kInboxFolder) not in self.BKJournalFolderDict: inFolder = vault.getInbox() if inFolder is not None: self.BKJournalListOrder.insert(0, xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kInboxFolder)) self.BKJournalFolderDict[xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kInboxFolder)] = inFolder # Get the Age Journal folders and add any new ones. masterAgeFolder = vault.getAgeJournalsFolder() if masterAgeFolder is not None: ageFolderRefs = masterAgeFolder.getChildNodeRefList() for ageFolderRef in ageFolderRefs: ageFolder = ageFolderRef.getChild() ageFolder = ageFolder.upcastToFolderNode() if ageFolder is not None: if not self.IsFolderHidden(ageFolder): ageFolderName = ageFolder.folderGetName() if ageFolderName == "": ageFolderName = "[invalid]" ageFolderName = FilterAgeName(ageFolderName) if ageFolderName in kAges.Hide: continue if ageFolderName not in self.BKJournalFolderDict: # New Age folder, add it. self.BKJournalListOrder.append(ageFolderName) self.BKJournalFolderDict[ageFolderName] = ageFolder # Make sure the current Age is at the top of the list. try: line = self.BKJournalListOrder.index(self.GetAgeInstanceName()) if line != 1: # It's not at the top of the list, so put it at the top. self.BKJournalListOrder.remove(self.GetAgeInstanceName()) self.BKJournalListOrder.insert(1, self.GetAgeInstanceName()) # If the player is looking at a Journal entry then switch to list mode. if self.BKRightSideMode == kGUI.BKJournalExpanded or self.BKRightSideMode == kGUI.BKPictureExpanded or self.BKRightSideMode == kGUI.BKMarkerListExpanded: self.ChangeBigKIMode(kGUI.BKListMode) except ValueError: # Create a folder for most Ages. ageName = self.GetAgeFileName().lower() if ageName != "startup" and ageName != "avatarcustomization" and ageName != "unknown age" and self.GetAgeInstanceName() != "?unknown?": entry = vault.findChronicleEntry("CleftSolved") cleftSolved = False if entry is not None: if entry.chronicleGetValue() == "yes": cleftSolved = True if self.GetAgeInstanceName() != "D'ni-Riltagamin" or cleftSolved: instAgeName = self.GetAgeInstanceName() createAgeFolder = True ageFolderRefs = masterAgeFolder.getChildNodeRefList() for ageFolderRef in ageFolderRefs: ageFolder = ageFolderRef.getChild() ageFolder = ageFolder.upcastToFolderNode() if ageFolder is not None and ageFolder.getFolderNameW() == instAgeName: createAgeFolder = False break if instAgeName and createAgeFolder: nFolder = ptVaultFolderNode(0) if nFolder is not None: nFolder.setFolderNameW(self.GetAgeInstanceName()) nFolder.folderSetType(PtVaultStandardNodes.kAgeTypeJournalFolder) # Add to the master Age folder folder. masterAgeFolder.addNode(nFolder) else: PtDebugPrint(u"xKI.BigKIRefreshFolderList(): Could not create folder for {}.".format(self.GetAgeInstanceName()), level=kErrorLevel) else: PtDebugPrint(u"xKI.BigKIRefreshFolderList(): Could not find the Master Age jounal folder.", level=kErrorLevel) # Get the player lists. self.BKPlayerFolderDict.clear() self.BKPlayerListOrder = [] ageMembers = KIFolder(PtVaultStandardNodes.kAgeMembersFolder) if ageMembers is not None: if xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kAgeMembersFolder) not in self.BKPlayerFolderDict: # Add the new player folder. self.BKPlayerListOrder.append(xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kAgeMembersFolder)) self.BKPlayerFolderDict[xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kAgeMembersFolder)] = ageMembers PtDebugPrint(u"xKI.BigKIRefreshFolderList(): Updating ageMembers.", level=kDebugDumpLevel) else: PtDebugPrint(u"xKI.BigKIRefreshFolderList(): AgeMembers folder is missing.", level=kWarningLevel) buddies = vault.getBuddyListFolder() if buddies is not None: if xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kBuddyListFolder) not in self.BKPlayerFolderDict: # Add the new player folder. self.BKPlayerListOrder.append(xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kBuddyListFolder)) self.BKPlayerFolderDict[xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kBuddyListFolder)] = buddies else: PtDebugPrint(u"xKI.BigKIRefreshFolderList(): Buddies folder is missing.", level=kWarningLevel) # Update the neighborhood folder. self.BigKIRefreshNeighborFolder() # Update the Recent people folder. PIKA = vault.getPeopleIKnowAboutFolder() if PIKA is not None: if xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kPeopleIKnowAboutFolder) not in self.BKPlayerFolderDict: # Add the new player folder. self.BKPlayerListOrder.append(xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kPeopleIKnowAboutFolder)) self.BKPlayerFolderDict[xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kPeopleIKnowAboutFolder)] = PIKA else: PtDebugPrint(u"xKI.BigKIRefreshFolderList(): PeopleIKnowAbout folder is missing.", level=kWarningLevel) ignores = vault.getIgnoreListFolder() if ignores is not None: if xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kIgnoreListFolder) not in self.BKPlayerFolderDict: # Add the new player folder. self.BKPlayerListOrder.append(xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kIgnoreListFolder)) self.BKPlayerFolderDict[xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kIgnoreListFolder)] = ignores else: PtDebugPrint(u"xKI.BigKIRefreshFolderList(): IgnoreList folder is missing.", level=kWarningLevel) # All Players if PtIsInternalRelease(): ap = vault.getAllPlayersFolder() if ap: name = xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kAllPlayersFolder) if name not in self.BKPlayerFolderDict: # Add the new player folder. self.BKPlayerListOrder.append(name) self.BKPlayerFolderDict[name] = ap # Age Visitors. visSep = SeparatorFolder(PtGetLocalizedString("KI.Folders.VisLists")) self.BKPlayerListOrder.append(visSep.name) self.BKPlayerFolderDict[visSep.name] = visSep self.BigKIRefreshAgeVisitorFolders() # Age Owners. self.BigKIRefreshAgesOwnedFolder() ## Refresh the Neighbors folder. def BigKIRefreshNeighborFolder(self): neighborhood = GetNeighborhood() try: neighbors = neighborhood.getAgeOwnersFolder() if xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kHoodMembersFolder) not in self.BKPlayerFolderDict: # Add the new Neighbors folder. self.BKPlayerListOrder.append(xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kHoodMembersFolder)) PtDebugPrint(u"xKI.BigKIRefreshNeighborFolder(): Got the neighbors player folder.", level=kDebugDumpLevel) self.BKPlayerFolderDict[xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kHoodMembersFolder)] = neighbors except AttributeError: PtDebugPrint(u"xKI.BigKIRefreshNeighborFolder(): Neighbors folder is missing.", level=kWarningLevel) ## Refresh the Age Visitors folders for Ages the player owns. def BigKIRefreshAgeVisitorFolders(self): vault = ptVault() try: myAgesFolder = vault.getAgesIOwnFolder() listOfMyAgeLinks = myAgesFolder.getChildNodeRefList() for myAgeLinkRef in listOfMyAgeLinks: myAgeLink = myAgeLinkRef.getChild() myAgeLink = myAgeLink.upcastToAgeLinkNode() myAge = myAgeLink.getAgeInfo() if myAge is not None: if self.CanAgeInviteVistors(myAge, myAgeLink) and myAge.getAgeFilename() not in kAges.Hide: PtDebugPrint(u"xKI.BigKIRefreshAgeVisitorFolders(): Refreshing visitor list for {}.".format(GetAgeName(myAge)), level=kDebugDumpLevel) folderName = xCensor.xCensor(PtGetLocalizedString("KI.Config.OwnerVisitors", [GetAgeName(myAge)]), self.censorLevel) if folderName not in self.BKPlayerFolderDict: # Add the new Age Visitors folder. PtDebugPrint(u"xKI.BigKIRefreshAgeVisitorFolders(): Adding visitor list for {}.".format(GetAgeName(myAge)), level=kDebugDumpLevel) self.BKPlayerListOrder.append(folderName) self.BKPlayerFolderDict[folderName] = myAge else: PtDebugPrint(u"xKI.BigKIRefreshAgeVisitorFolders(): Age info for {} is not ready yet.".format(myAgeLink.getUserDefinedName()), level=kErrorLevel) except AttributeError: PtDebugPrint(u"xKI.BigKIRefreshAgeVisitorFolders(): Error finding Age Visitors folder.", level=kErrorLevel) ## Refresh the configuration folder listing for owned Ages. # This is currently only used for Neighborhoods. def BigKIRefreshAgesOwnedFolder(self): # First, get rid of all the Age config entries, in case one of them got deleted. self.BKConfigFolderDict.clear() self.BKConfigListOrder = [] for config in self.BKConfigDefaultListOrder: self.BKConfigListOrder.append(config) vault = ptVault() try: myAgesFolder = vault.getAgesIOwnFolder() listOfMyAgeLinks = myAgesFolder.getChildNodeRefList() for myAgeLinkRef in listOfMyAgeLinks: myAgeLink = myAgeLinkRef.getChild() myAgeLink = myAgeLink.upcastToAgeLinkNode() myAge = myAgeLink.getAgeInfo() if myAge is not None: if myAge.getAgeFilename() == "Neighborhood": PtDebugPrint(u"xKI.BigKIRefreshAgesOwnedFolder(): Refreshing owner configuration for Age {}.".format(GetAgeName(myAge)), level=kDebugDumpLevel) configName = xCensor.xCensor(PtGetLocalizedString("KI.Config.OwnerConfig", [GetAgeName(myAge)]), self.censorLevel) if configName not in self.BKConfigFolderDict: # Add the new Age configuration. PtDebugPrint(u"xKI: adding owner config for Age {}.".format(GetAgeName(myAge)), level=kDebugDumpLevel) self.BKConfigListOrder.append(configName) self.BKConfigFolderDict[configName] = myAge else: PtDebugPrint(u"xKI.BigKIRefreshAgesOwnedFolder(): Age info for {} is not ready yet.".format(myAgeLink.getUserDefinedName()), level=kErrorLevel) except AttributeError: PtDebugPrint(u"xKI.BigKIRefreshAgesOwnedFolder(): Error finding Age folder.", level=kErrorLevel) ## Reget the contents of the selected content list. def BigKINewContentList(self): try: folderName = self.BKFolderListOrder[self.BKFolderSelected] folder = self.BKFolderLineDict[folderName] if folder is not None: if isinstance(folder, ptVaultNode): if folder.getType() == PtVaultNodeTypes.kAgeInfoNode: try: self.BKContentList = folder.getCanVisitFolder().getChildNodeRefList() except AttributeError: self.BKContentList = [] else: self.BKContentList = folder.getChildNodeRefList() self.BigKIProcessContentList(True) if self.BKFolderSelectChanged: self.BKContentListTopLine = 0 elif isinstance(folder, KIFolder): self.BKContentList = PtGetPlayerListDistanceSorted() self.BigKIProcessContentList(True) if self.BKFolderSelectChanged: self.BKContentListTopLine = 0 else: # Shouldn't happen because the player can't click on these. self.BKContentList = [] except (IndexError, KeyError): self.BKContentList = [] self.BigKIRefreshContentListDisplay() ## Refreshes the contents of the selected content list. def BigKIRefreshContentList(self): try: folderName = self.BKFolderListOrder[self.BKFolderSelected] folder = self.BKFolderLineDict[folderName] if folder is not None: if isinstance(folder, ptVaultNode): if folder.getType() == PtVaultNodeTypes.kAgeInfoNode: try: self.BKContentList = folder.getCanVisitFolder().getChildNodeRefList() except AttributeError: self.BKContentList = [] else: self.BKContentList = folder.getChildNodeRefList() self.BigKIProcessContentList() elif isinstance(folder, KIFolder): self.BKContentList = PtGetPlayerListDistanceSorted() self.BigKIProcessContentList() else: self.BKContentList = [] except LookupError: pass #~~~~~~~~~~~~~~~~~~~~~~~~~~# # BigKI Display Refreshing # #~~~~~~~~~~~~~~~~~~~~~~~~~~# ## Refresh the display of the folders and the selection. def BigKIRefreshFolderDisplay(self): # Refresh the display of the folders. ID = kGUI.BKIIncomingLine if self.BKFolderListOrder: # Make sure that it is a valid index. if self.BKFolderTopLine >= len(self.BKFolderListOrder): self.BKFolderTopLine = len(self.BKFolderListOrder) - 1 # If the selected is off the screen, go to the top then (only in list mode). ## @todo Note when the self.BKFolderSelected has changed, refresh the content display. if self.BKRightSideMode == kGUI.BKListMode: if self.BKFolderSelected < self.BKFolderTopLine: self.BKFolderSelected = self.BKFolderTopLine if self.BKFolderSelected > self.BKFolderTopLine + (kGUI.BKIFolderLineLast - kGUI.BKIIncomingLine): self.BKFolderSelected = self.BKFolderTopLine + (kGUI.BKIFolderLineLast - kGUI.BKIIncomingLine) if self.BKFolderSelected > self.BKFolderTopLine + len(self.BKFolderListOrder[self.BKFolderTopLine:]) - 1: self.BKFolderSelected = self.BKFolderTopLine + len(self.BKFolderListOrder[self.BKFolderTopLine]) - 1 selectedFolder = self.BKFolderSelected - self.BKFolderTopLine + kGUI.BKIIncomingLine for folderName in self.BKFolderListOrder[self.BKFolderTopLine:]: folderField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(ID)) longFolderField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(ID + 500)) buttonID = ID - kGUI.BKIFolderLine01+kGUI.BKIFolderLineBtn01 folderButton = ptGUIControlButton(BigKI.dialog.getControlFromTag(buttonID)) # Make sure it's not a separator folder. if folderName in self.BKFolderLineDict and isinstance(self.BKFolderLineDict[folderName], SeparatorFolder): # This button can't be clicked. folderButton.hide() folderField.setStringJustify(kLeftJustify) folderField.setForeColor(kColors.DniStatic) else: folderButton.show() folderField.setStringJustify(kRightJustify) if ID == selectedFolder: folderField.setForeColor(kColors.DniSelected) longFolderField.setForeColor(kColors.DniSelected) else: folderField.setForeColor(kColors.DniSelectable) longFolderField.setForeColor(kColors.DniSelectable) folderField.setStringW(folderName) longFolderField.setStringW(folderName) ID += 1 if ID > kGUI.BKIFolderLineLast: break # Set the up and down buttons, if needed. upbtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKFolderUpLine)) if self.BKFolderTopLine > 0: upbtn.show() else: upbtn.hide() dwnbtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKFolderDownLine)) # Has the listbox been filled up? if ID > kGUI.BKIFolderLineLast: dwnbtn.show() else: dwnbtn.hide() # If there are more folder lines, fill them out to be blank and disable # their button fields. for tagID in range(ID, kGUI.BKIFolderLineLast + 1): folderField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(tagID)) folderField.setForeColor(kColors.DniSelectable) folderField.setString(" ") buttonID = tagID - kGUI.BKIFolderLine01 + kGUI.BKIFolderLineBtn01 folderButton = ptGUIControlButton(BigKI.dialog.getControlFromTag(buttonID)) folderButton.hide() ## Do some extra processing on the content list. def BigKIProcessContentList(self, removeInboxStuff=False): # Start with nothing in the removeList (remove from current content list). removeList = [] # If it's a player list. if self.BKFolderLineDict is self.BKPlayerFolderDict: ignores = ptVault().getIgnoreListFolder() # Make sure there are some players to process. if len(self.BKContentList) > 0: # If this is a ptPlayer. if isinstance(self.BKContentList[0], ptPlayer): # Sort the list of Age players. try: self.BKContentList.sort(lambda a, b: cmp(a.getPlayerName().lower(), b.getPlayerName().lower())) except: PtDebugPrint(u"xKI.BigKIProcessContentList(): Unable to sort Age players, but don't break the list.", level=kErrorLevel) for idx in range(len(self.BKContentList)): player = self.BKContentList[idx] if isinstance(player, ptPlayer): if ignores.playerlistHasPlayer(player.getPlayerID()): # Remove ignored player. removeList.insert(0, idx) else: # Not a player, remove from the list. removeList.insert(0, idx) else: # Sort the list of players, online first. self.BKContentList.sort(CMPplayerOnline) # Remove all the unnamed players and ignored people. for idx in range(len(self.BKContentList)): ref = self.BKContentList[idx] elem = ref.getChild() if elem is not None: if elem.getType() == PtVaultNodeTypes.kPlayerInfoNode: elem = elem.upcastToPlayerInfoNode() if elem.playerGetName() == "": # Put them in reverse order in the removeList. removeList.insert(0, idx) # Check if they are in the ignore list. elif ignores.playerlistHasPlayer(elem.playerGetID()): # Get parent; in some folders the player has to be still visible. parent = ref.getParent() if parent: parent = parent.upcastToFolderNode() if parent is None: # Make sure this is not the IgnoreList. if parent.folderGetType() != PtVaultStandardNodes.kIgnoreListFolder: # Put in them in reverse order in the removeList. removeList.insert(0, idx) else: removeList.insert(0, idx) else: removeList.insert(0, idx) elif self.BKFolderListOrder[self.BKFolderSelected] == xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kInboxFolder): # Look for KI-Mail from non-Buddies if the player only wants KI-Mail from Buddies. vault = ptVault() inbox = vault.getInbox() buddies = vault.getBuddyListFolder() ignores = vault.getIgnoreListFolder() for idx in range(len(self.BKContentList)): ref = self.BKContentList[idx] if ref is not None: if ref.getSaver() is None or ref.getSaverID() == 0: continue if (self.onlyGetPMsFromBuddies and not buddies.playerlistHasPlayer(ref.getSaverID())) or ignores.playerlistHasPlayer(ref.getSaverID()): PtDebugPrint(u"xKI.BigKIProcessContentList(): Remove from inbox because it's from {}.".format(ref.getSaver().playerGetName()), level=kWarningLevel) # Remove from the list. removeList.insert(0, idx) # Only remove from inbox if specified. if removeInboxStuff: PtDebugPrint(u"xKI.BigKIProcessContentList(): Really removed from inbox because it's from {}, this time.".format(ref.getSaver().playerGetName()), level=kWarningLevel) # Remove from inbox (how will this work?). element = ref.getChild() inbox.removeNode(element) if removeList: PtDebugPrint(u"xKI.BigKIProcessContentList(): Removing {} contents from being displayed.".format(len(removeList)), level=kWarningLevel) for removeidx in removeList: del self.BKContentList[removeidx] if self.BKFolderListOrder[self.BKFolderSelected] == xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kInboxFolder): self.BKContentList = self.markerJoinRequests + self.BKContentList # Also add in the GlobalInbox stuff here. vault = ptVault() gInbox = vault.getGlobalInbox() if gInbox is not None: self.BKContentList = gInbox.getChildNodeRefList() + self.BKContentList self.BKContentList.sort(CMPNodeDate) removeList = [] for contentidx in range(len(self.BKContentList)): content = self.BKContentList[contentidx] if isinstance(content, ptVaultNodeRef): element = content.getChild() if element is not None: if element.getType() == PtVaultNodeTypes.kFolderNode or element.getType() == PtVaultNodeTypes.kChronicleNode: removeList.insert(0, contentidx) for removeidx in removeList: del self.BKContentList[removeidx] ## Refresh the display of the selected content list. def BigKIRefreshContentListDisplay(self): if self.BKRightSideMode == kGUI.BKListMode: createField = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(kGUI.BKILMTitleCreateLine)) createBtn = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(kGUI.BKIListModeCreateBtn)) try: if self.BKFolderLineDict is self.BKPlayerFolderDict: if self.BKFolderListOrder[self.BKFolderSelected] == xLocTools.FolderIDToFolderName(PtVaultStandardNodes.kBuddyListFolder): createField.setStringW(PtGetLocalizedString("KI.Player.CreateBuddyTitle")) createBtn.show() else: createField.setString(" ") createBtn.hide() else: createField.setString(" ") createBtn.hide() except IndexError: createField.setString(" ") createBtn.hide() if len(self.BKFolderListOrder) != 0: PtDebugPrint(u"xKI.BigKIRefreshContentListDisplay(): Index error: self.BKFolderSelected = {} and list = {}.".format(self.BKFolderSelected, self.BKFolderListOrder), level=kWarningLevel) return ID = kGUI.BKILMOffsetLine01 if len(self.BKContentList) != 0: if self.BKContentListTopLine >= len(self.BKContentList): self.BKContentListTopLine = len(self.BKContentList) - 1 for content in self.BKContentList[self.BKContentListTopLine:]: if content is not None: # Add the new line. contentIconJ = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(ID + kGUI.BKILMIconJournalOffset)) contentIconAva = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(ID + kGUI.BKILMIconPersonOffset)) contentIconP = ptGUIControlDynamicText(KIListModeDialog.dialog.getControlFromTag(ID + kGUI.BKILMIconPictureOffset)) contentTitle = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(ID + kGUI.BKILMTitleOffset)) contentDate = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(ID + kGUI.BKILMDateOffset)) contentFrom = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(ID + kGUI.BKILMFromOffset)) if isinstance(content, ptPlayer): contentIconAva.show() contentIconJ.hide() contentIconP.hide() contentTitle.setForeColor(kColors.DniSelectable) contentTitle.setString(xCensor.xCensor(content.getPlayerName(), self.censorLevel)) contentTitle.show() contentDate.hide() contentFrom.setForeColor(kColors.DniSelectable) contentFrom.setFontSize(10) contentFrom.setString(GetAgeName()) contentFrom.show() # Find the button to enable it. lmButton = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(((ID - 100) / 10) + kGUI.BKIListModeCreateBtn)) lmButton.show() ID += 10 if ID > kGUI.BKILMOffsetLineLast: break else: element = content.getChild() if element is not None: if element.getType() == PtVaultNodeTypes.kTextNoteNode: element = element.upcastToTextNoteNode() contentIconJ.show() contentIconP.hide() contentIconAva.hide() elif element.getType() == PtVaultNodeTypes.kImageNode: element = element.upcastToImageNode() contentIconJ.hide() contentIconAva.hide() if contentIconP.getNumMaps() > 0: dynMap = contentIconP.getMap(0) image = element.imageGetImage() dynMap.clearToColor(ptColor(.1, .1, .1, .1)) if image is not None: dynMap.drawImage(kGUI.BKIImageStartX, kGUI.BKIImageStartY, image, 0) dynMap.flush() contentIconP.show() elif element.getType() == PtVaultNodeTypes.kPlayerInfoNode: element = element.upcastToPlayerInfoNode() contentIconAva.show() contentIconJ.hide() contentIconP.hide() elif element.getType() == PtVaultNodeTypes.kMarkerGameNode: element = element.upcastToMarkerGameNode() # No icon for Marker Game. contentIconAva.hide() contentIconJ.hide() contentIconP.hide() elif element.getType() == PtVaultNodeTypes.kFolderNode: continue else: contentIconAva.hide() contentIconJ.hide() contentIconP.hide() if isinstance(element, ptVaultPlayerInfoNode): # If it's a player, use the title for the player name. contentTitle.setForeColor(kColors.DniSelectable) contentTitle.setString(xCensor.xCensor(element.playerGetName(), self.censorLevel)) contentTitle.show() contentDate.hide() contentFrom.setForeColor(kColors.DniSelectable) contentFrom.setFontSize(10) if element.playerIsOnline(): contentFrom.setString(FilterAgeName(element.playerGetAgeInstanceName())) else: contentFrom.setString(" ") contentFrom.show() else: # Otherwise it's an image or a text note. if content.getSaverID() == 0: # Must be from the DRC. contentTitle.setForeColor(kColors.DniStatic) contentDate.setForeColor(kColors.DniStatic) else: contentTitle.setForeColor(kColors.DniSelectable) contentDate.setForeColor(kColors.DniSelectable) if isinstance(element, ptVaultImageNode): contentTitle.setString(xCensor.xCensor(element.imageGetTitle(), self.censorLevel)) elif isinstance(element, ptVaultTextNoteNode): contentTitle.setString(xCensor.xCensor(element.noteGetTitle(), self.censorLevel)) elif isinstance(element, ptVaultMarkerGameNode): contentTitle.setString(xCensor.xCensor(element.getGameName(), self.censorLevel)) else: # Probably still downloading because of lag. contentTitle.setString("--[Downloading]--") contentTitle.setForeColor(kColors.DniYellow) PtDebugPrint(u"xKI.BigKIRefreshContentListDisplay(): Unknown data type in content list: type = {}.".format(element.getType()), level=kErrorLevel) contentTitle.show() try: tupTime = time.gmtime(PtGMTtoDniTime(element.getModifyTime())) curTime = time.strftime(PtGetLocalizedString("Global.Formats.Date"), tupTime) except: curTime = "" contentDate.setString(curTime) contentDate.show() sender = content.getSaver() # See if the saver was the player. localPlayer = PtGetLocalPlayer() if sender is not None and localPlayer.getPlayerID() != sender.playerGetID(): if content.getSaverID() == 0: # Must be from the DRC. contentFrom.setForeColor(kColors.DniStatic) contentFrom.setFontSize(13) contentFrom.setString("DRC") else: contentFrom.setForeColor(kColors.DniSelectable) contentFrom.setFontSize(10) contentFrom.setString(sender.playerGetName()) contentFrom.show() else: if content.getSaverID() == 0: # Must be from the DRC. contentFrom.setString("DRC") contentFrom.show() else: contentFrom.setString(" ") contentFrom.hide() # Find the button to enable it. lmButton = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(((ID - 100) / 10) + kGUI.BKIListModeCreateBtn)) lmButton.show() ID += 10 if ID > kGUI.BKILMOffsetLineLast: break else: PtDebugPrint(u"xKI.BigKIRefreshContentListDisplay: No element inside the content.", level=kErrorLevel) else: PtDebugPrint(u"xKI.BigKIRefreshContentListDisplay: No content, even though the folder said there was.", level=kErrorLevel) # Set the up and down buttons if needed. upBtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKLMUpButton)) if self.BKContentListTopLine > 0: upBtn.show() else: upBtn.hide() dwnBtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKLMDownButton)) # Has the ListBox been filled up? if ID > kGUI.BKILMOffsetLineLast: dwnBtn.show() else: dwnBtn.hide() # If there are more content lines, fill them out to be blank # and disable the button fields. for tagID in range(ID,kGUI.BKILMOffsetLineLast + 10, 10): iconPic = ptGUIControlDynamicText(KIListModeDialog.dialog.getControlFromTag(tagID + kGUI.BKILMIconPictureOffset)) iconPic.hide() iconJrn = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(tagID + kGUI.BKILMIconJournalOffset)) iconJrn.hide() iconAva = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(tagID + kGUI.BKILMIconPersonOffset)) iconAva.hide() titleField = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(tagID + kGUI.BKILMTitleOffset)) titleField.hide() dateField = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(tagID + kGUI.BKILMDateOffset)) dateField.hide() fromField = ptGUIControlTextBox(KIListModeDialog.dialog.getControlFromTag(tagID + kGUI.BKILMFromOffset)) fromField.hide() # Find the button to disable it. lmButton = ptGUIControlButton(KIListModeDialog.dialog.getControlFromTag(((tagID - 100) / 10) + kGUI.BKIListModeCreateBtn)) lmButton.hide() #~~~~~~~~~~~~~~~~~~~~~~~# # BigKI Content Display # #~~~~~~~~~~~~~~~~~~~~~~~# ## Display a text Journal entry in the KI. def BigKIDisplayJournalEntry(self): jrnAgeName = ptGUIControlTextBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNAgeName)) jrnAgeName.hide() jrnDate = ptGUIControlTextBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNDate)) jrnDate.hide() jrnTitle = ptGUIControlTextBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNTitle)) jrnTitle.hide() jrnNote = ptGUIControlMultiLineEdit(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNNote)) jrnNote.hide() jrnNote.setBufferLimit(kLimits.JournalTextSize) jrnDeleteBtn = ptGUIControlButton(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNDeleteButton)) jrnDeleteBtn.hide() jrnTitleBtn = ptGUIControlButton(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKIJRNTitleButton)) if self.BKCurrentContent is None: PtDebugPrint(u"xKI.BigKIDisplayJournalEntry(): self.BKCurrentContent is None.", level=kErrorLevel) return if self.IsContentMutable(self.BKCurrentContent): jrnDeleteBtn.show() jrnNote.unlock() if not self.BKInEditMode or self.BKEditField != kGUI.BKEditFieldJRNTitle: jrnTitleBtn.show() else: jrnNote.lock() jrnTitleBtn.hide() element = self.BKCurrentContent.getChild() if element is None: PtDebugPrint(u"xKI.BigKIDisplayJournalEntry(): Element is None.", level=kErrorLevel) return dataType = element.getType() if dataType != PtVaultNodeTypes.kTextNoteNode: PtDebugPrint(u"xKI.BigKIDisplayJournalEntry(): Wrong element type {}.".format(dataType), level=kErrorLevel) return element = element.upcastToTextNoteNode() # Display the content on the screen. jrnAgeName.setString(FilterAgeName(xCensor.xCensor(element.getCreateAgeName(), self.censorLevel))) jrnAgeName.show() tupTime = time.gmtime(PtGMTtoDniTime(element.getModifyTime())) curTime = time.strftime(PtGetLocalizedString("Global.Formats.Date"), tupTime) jrnDate.setString(curTime) jrnDate.show() if not self.BKInEditMode or self.BKEditField != kGUI.BKEditFieldJRNTitle: jrnTitle.setString(xCensor.xCensor(element.noteGetTitle(), self.censorLevel)) jrnTitle.show() if not self.BKInEditMode or self.BKEditField != kGUI.BKEditFieldJRNNote: encoded = buffer(xCensor.xCensor(element.noteGetText(), self.censorLevel)) jrnNote.setEncodedBuffer(encoded) jrnNote.show() self.BigKISetSeen(self.BKCurrentContent) # If it came from someone else, add them to the SendTo field. self.CheckContentForSender(self.BKCurrentContent) ## Create and display a new note in the Journal. def BigKICreateJournalNote(self): PtDebugPrint(u"xKI.BigKICreateJournalNote(): Create text note message.", level=kDebugDumpLevel) # If there is no folder list, then make one. if not self.BKFolderListOrder: self.BigKIRefreshFolderList() try: journal = self.BKJournalFolderDict[self.GetAgeInstanceName()] if journal is not None: # Make sure that the age folder is selected. self.BKFolderTopLine = self.BKJournalFolderTopLine = 0 # Scroll back to the top. self.BKFolderSelected = self.BKJournalFolderSelected = self.BKJournalListOrder.index(self.GetAgeInstanceName()) # Create the note. note = ptVaultTextNoteNode(0) note.setTextW(PtGetLocalizedString("KI.Journal.InitialMessage")) note.setTitleW(PtGetLocalizedString("KI.Journal.InitialTitle")) self.BKCurrentContent = journal.addNode(note) return self.BKCurrentContent else: PtDebugPrint(u"xKI.BigKICreateJournalNote(): Journal not ready.", level=kErrorLevel) return None except KeyError: PtDebugPrint(u"xKI.BigKICreateJournalNote(): Could not find journal for this Age: {}.".format(self.GetAgeInstanceName()), level=kErrorLevel) ## Display a KI Picture in the KI. def BigKIDisplayPicture(self): picAgeName = ptGUIControlTextBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKIPICAgeName)) picAgeName.hide() picDate = ptGUIControlTextBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKIPICDate)) picDate.hide() picTitle = ptGUIControlTextBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKIPICTitle)) picTitle.hide() picImage = ptGUIControlDynamicText(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKIPICImage)) picImage.hide() picDeleteBtn = ptGUIControlButton(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKIPICDeleteButton)) picDeleteBtn.hide() picTitleBtn = ptGUIControlButton(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKIPICTitleButton)) if self.BKCurrentContent is None: PtDebugPrint(u"xKI.BigKIDisplayPicture(): self.BKCurrentContent is None.", level=kErrorLevel) return if self.IsContentMutable(self.BKCurrentContent): picDeleteBtn.show() if not self.BKInEditMode or self.BKEditField != kGUI.BKEditFieldPICTitle: picTitleBtn.show() else: picTitleBtn.hide() element = self.BKCurrentContent.getChild() if element is None: PtDebugPrint(u"xKI.BigKIDisplayPicture(): Element is None.", level=kErrorLevel) return dataType = element.getType() if dataType != PtVaultNodeTypes.kImageNode: PtDebugPrint(u"xKI.BigKIDisplayPicture(): Wrong element type {}.".format(dataType), level=kErrorLevel) return element = element.upcastToImageNode() # Display the content on the screen. picAgeName.setString(FilterAgeName(xCensor.xCensor(element.getCreateAgeName(), self.censorLevel))) picAgeName.show() tupTime = time.gmtime(PtGMTtoDniTime(element.getModifyTime())) curTime = time.strftime(PtGetLocalizedString("Global.Formats.Date"), tupTime) picDate.setString(curTime) picDate.show() if not self.BKInEditMode or self.BKEditField != kGUI.BKEditFieldPICTitle: picTitle.setString(xCensor.xCensor(element.imageGetTitle(), self.censorLevel)) picTitle.show() if picImage.getNumMaps() > 0: dynMap = picImage.getMap(0) image = element.imageGetImage() dynMap.clearToColor(ptColor(.1, .1, .1, .3)) if image is not None: dynMap.drawImage(kGUI.BKIImageStartX, kGUI.BKIImageStartY, image, 0) else: dynMap.fillRect(kGUI.BKIImageStartX, kGUI.BKIImageStartY, kGUI.BKIImageStartX + 800, kGUI.BKIImageStartY + 600, ptColor(.2, .2, .2, .1)) dynMap.flush() picImage.show() self.BigKISetSeen(self.BKCurrentContent) # If it came from someone else, add them to the SendTo field. self.CheckContentForSender(self.BKCurrentContent) ## Create and display a new KI Picture in the Journal. def BigKICreateJournalImage(self, image, useScreenShot=False): PtDebugPrint(u"xKI.BigKICreateJournalImage(): Create a KI Picture from {}.".format(image), level=kDebugDumpLevel) # If there is no folder list, then make one. if not self.BKFolderListOrder: self.BigKIRefreshFolderList() try: journal = self.BKJournalFolderDict[self.GetAgeInstanceName()] if journal is not None: # Make sure that the age folder is selected. self.BKFolderTopLine = self.BKJournalFolderTopLine = 0 # Scroll back to the top. self.BKFolderSelected = self.BKJournalFolderSelected = self.BKJournalListOrder.index(self.GetAgeInstanceName()) # Create the image entry. imgElem = ptVaultImageNode(0) if useScreenShot: imgElem.setImageFromScrShot() else: imgElem.imageSetImage(image) imgElem.setTitleW(PtGetLocalizedString("KI.Image.InitialTitle")) self.BKCurrentContent = journal.addNode(imgElem) return self.BKCurrentContent else: PtDebugPrint(u"xKI.BigKICreateJournalImage(): Journal not ready.", level=kErrorLevel) return None except KeyError: PtDebugPrint(u"xKI.BigKICreateJournalImage(): Could not find journal for this Age: {}.".format(self.GetAgeInstanceName()), level=kErrorLevel) ## Display a player entry. def BigKIDisplayPlayerEntry(self): plyName = ptGUIControlTextBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYName)) plyName.hide() plyID = ptGUIControlTextBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYID)) plyID.hide() plyIDedit = ptGUIControlEditBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYPlayerIDEditBox)) plyIDedit.hide() plyDetail = ptGUIControlTextBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYDetail)) plyDetail.hide() plyDeleteBtn = ptGUIControlButton(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYDeleteButton)) plyDeleteBtn.hide() # Is the player asking for a player ID number? if self.BKGettingPlayerID: plyName.setStringW(PtGetLocalizedString("KI.Player.EnterID")) plyName.show() plyIDedit.setString("") plyIDedit.show() plyIDedit.focus() KIPlayerExpanded.dialog.setFocus(plyIDedit.getKey()) return if self.BKCurrentContent is None: PtDebugPrint(u"xKI.BigKIDisplayPlayerEntry(): self.BKCurrentContent is None.", level=kErrorLevel) return if isinstance(self.BKCurrentContent, ptPlayer): # Display the content on the screen. plyName.setString(xCensor.xCensor(self.BKCurrentContent.getPlayerName(), self.censorLevel)) plyName.show() IDText = "{:08d}".format(self.BKCurrentContent.getPlayerID()) plyID.setString(IDText) plyID.show() plyDetail.setStringW(PtGetLocalizedString("KI.Player.InAge", [GetAgeName()])) plyDetail.show() sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine)) self.BKPlayerSelected = self.BKCurrentContent sendToField.setString(self.BKCurrentContent.getPlayerName()) return element = self.BKCurrentContent.getChild() if element is None: PtDebugPrint(u"xKI.BigKIDisplayPlayerEntry(): Element is None.", level=kErrorLevel) return dataType = element.getType() if dataType != PtVaultNodeTypes.kPlayerInfoNode: PtDebugPrint(u"xKI.BigKIDisplayPlayerEntry(): Wrong element type {}.".format(dataType), level=kErrorLevel) return element = element.upcastToPlayerInfoNode() # Display the content on the screen. plyName.setString(xCensor.xCensor(element.playerGetName(), self.censorLevel)) plyName.show() IDText = "{:08d}".format(element.playerGetID()) plyID.setString(IDText) plyID.show() if element.playerIsOnline(): if element.playerGetAgeInstanceName() == "Cleft": plyDetail.setStringW(PtGetLocalizedString("KI.Player.InCleft")) elif element.playerGetAgeInstanceName() == "AvatarCustomization": plyDetail.setStringW(PtGetLocalizedString("KI.Player.InCloset")) else: plyDetail.setStringW(PtGetLocalizedString("KI.Player.InAge", [FilterAgeName(element.playerGetAgeInstanceName())])) else: plyDetail.setStringW(PtGetLocalizedString("KI.Player.Offline")) plyDetail.show() # Determine if this player can be removed from this folder. folder = self.BKCurrentContent.getParent() if folder: folder = folder.upcastToFolderNode() if folder and self.IsFolderContentMutable(folder): plyDeleteBtn.show() sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine)) self.BKPlayerSelected = self.BKCurrentContent sendToField.setString(element.playerGetName()) ## Save after a player was edited. def BigKICheckSavePlayer(self): if self.BKGettingPlayerID: # Create and save a player element into Buddies. self.BKGettingPlayerID = False plyIDedit = ptGUIControlEditBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYPlayerIDEditBox)) if not plyIDedit.wasEscaped(): ID = self.chatMgr.commandsProcessor.GetPID(plyIDedit.getString()) if ID: localPlayer = PtGetLocalPlayer() if ID != localPlayer.getPlayerID(): vault = ptVault() buddies = vault.getBuddyListFolder() if buddies is not None: if buddies.playerlistHasPlayer(ID): plyDetail = ptGUIControlTextBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYDetail)) plyDetail.setStringW(PtGetLocalizedString("KI.Player.AlreadyAdded")) plyDetail.show() self.BKGettingPlayerID = True else: buddies.playerlistAddPlayer(ID) self.chatMgr.DisplayStatusMessage(PtGetLocalizedString("KI.Player.Added")) if not self.BKGettingPlayerID: self.ChangeBigKIMode(kGUI.BKListMode) else: plyDetail = ptGUIControlTextBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYDetail)) plyDetail.setStringW(PtGetLocalizedString("KI.Player.NotYourself")) plyDetail.show() self.BKGettingPlayerID = True else: plyDetail = ptGUIControlTextBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYDetail)) plyDetail.setStringW(PtGetLocalizedString("KI.Player.NumberOnly")) plyDetail.show() self.BKGettingPlayerID = True else: # Nothing here, just go back to list mode. self.ChangeBigKIMode(kGUI.BKListMode) ## Prepares the display of a marker game, as it may be loading. def BigKIDisplayMarkerGame(self): # Make sure that the player can view this game. if self.gKIMarkerLevel < kKIMarkerNormalLevel: self.BigKIDisplayMarkerGameMessage(PtGetLocalizedString("KI.MarkerGame.pendingActionUpgradeKI")) return # Save some typing. mgr = self.markerGameManager getControl = KIMarkerFolderExpanded.dialog.getControlFromTag # Initialize the markerGameDisplay to the currently selected game. # But first, ensure that the player meets all the necessary criteria. if self.BKCurrentContent is None: PtDebugPrint(u"xKI.BigKIDisplayMarkerGame(): Could not find the current selected content selected.", level=kErrorLevel) return element = self.BKCurrentContent.getChild() if element is None: PtDebugPrint(u"xKI.BigKIDisplayMarkerGame(): Could not find the current content's child node.", level=kErrorLevel) return dataType = element.getType() if dataType != PtVaultNodeTypes.kMarkerGameNode: PtDebugPrint(u"xKI.BigKIDisplayMarkerGame(): Cannot process this node, wrong data type: {}.".format(element.getType()), level=kErrorLevel) return element = element.upcastToMarkerGameNode() PtDebugPrint(u"xKI.BigKIDisplayMarkerGame(): Starting Marker Game KI Display Manager, loading game: {}.".format(element.getGameName()), level=kDebugDumpLevel) ## This was previously BigKIFinishDisplayMarkerGame() questGameFinished = False # A game is in progress, restrict access. if mgr.AmIPlaying(element): self.MFdialogMode = kGames.MFPlaying # Are we editing this game? If so, how? elif mgr.IsActive(element) and mgr.edit_mode: if mgr.selected_marker_id != -1: self.MFdialogMode = kGames.MFEditingMarker else: self.MFdialogMode = kGames.MFEditing # Whatever. else: self.MFdialogMode = kGames.MFOverview # Refresh miniKI. self.RefreshMiniKIMarkerDisplay() self.SetBigKIToButtons() # Hide the invite buttons controls. ptGUIControlButton(getControl(kGUI.MarkerFolderInvitePlayer)).hide() mtbInvitePlayer = ptGUIControlTextBox(getControl(kGUI.MarkerFolderInvitePlayerTB)) mtbInvitePlayer.setForeColor(kColors.Clear) mtbInvitePlayer.setString(" ") mbtnEditStart = ptGUIControlButton(getControl(kGUI.MarkerFolderEditStartGame)) mbtnPlayEnd = ptGUIControlButton(getControl(kGUI.MarkerFolderPlayEndGame)) mrkfldOwner = ptGUIControlTextBox(getControl(kGUI.MarkerFolderOwner)) mtbEditStart = ptGUIControlTextBox(getControl(kGUI.MarkerFolderEditStartGameTB)) mtbPlayEnd = ptGUIControlTextBox(getControl(kGUI.MarkerFolderPlayEndGameTB)) mrkfldStatus = ptGUIControlTextBox(getControl(kGUI.MarkerFolderStatus)) mrkfldTitle = ptGUIControlTextBox(getControl(kGUI.MarkerFolderTitleText)) mrkfldTitleBtn = ptGUIControlButton(getControl(kGUI.MarkerFolderTitleBtn)) mbtnDelete = ptGUIControlButton(getControl(kGUI.MarkerFolderDeleteBtn)) mbtnGameTimePullD = ptGUIControlButton(getControl(kGUI.MarkerFolderTimePullDownBtn)) mtbGameType = ptGUIControlTextBox(getControl(kGUI.MarkerFolderGameTypeTB)) mbtnGameTypePullD = ptGUIControlButton(getControl(kGUI.MarkerFolderTypePullDownBtn)) mbtnGameTypePullD.hide() mbtnGameTimeArrow = ptGUIControlButton(getControl(kGUI.MarkerFolderTimeArrow)) mbtnGameTypeArrow = ptGUIControlButton(getControl(kGUI.MarkerFolderTypeArrow)) mbtnGameTypeArrow.hide() mtbGameTime = ptGUIControlTextBox(getControl(kGUI.MarkerFolderGameTimeTB)) mtbGameTimeTitle = ptGUIControlTextBox(getControl(kGUI.MarkerFolderGameTimeTitleTB)) mtbGameTimeTitle.setStringW(PtGetLocalizedString("KI.MarkerGame.Time")) mlbMarkerList = ptGUIControlListBox(getControl(kGUI.MarkerFolderMarkListbox)) mlbMarkerTextTB = ptGUIControlTextBox(getControl(kGUI.MarkerFolderMarkerTextTB)) mbtnMarkerText = ptGUIControlTextBox(getControl(kGUI.MarkerFolderMarkerTextBtn)) mbtnToran = ptGUIControlButton(getControl(kGUI.MarkerFolderToranIcon)) mbtnToran.disable() mbtnHSpan = ptGUIControlButton(getControl(kGUI.MarkerFolderHSpanIcon)) mbtnHSpan.disable() mbtnVSpan = ptGUIControlButton(getControl(kGUI.MarkerFolderVSpanIcon)) mbtnVSpan.disable() mtbToran = ptGUIControlTextBox(getControl(kGUI.MarkerFolderToranTB)) mtbHSPan = ptGUIControlTextBox(getControl(kGUI.MarkerFolderHSpanTB)) mtbVSpan = ptGUIControlTextBox(getControl(kGUI.MarkerFolderVSpanTB)) ## FIXME: non quest game types mtbGameType.setStringW(PtGetLocalizedString("KI.MarkerGame.NameQuest").title()) mbtnEditStart.show() mbtnPlayEnd.show() # Is the player merely looking at a Marker Game? if self.MFdialogMode == kGames.MFOverview: mrkfldTitleBtn.disable() mbtnDelete.show() mbtnGameTimePullD.hide() mbtnGameTimeArrow.hide() if element.getCreatorNodeID() == PtGetLocalClientID(): mbtnEditStart.show() mtbEditStart.setForeColor(kColors.DniShowBtn) else: mbtnEditStart.hide() mtbEditStart.setForeColor(kColors.DniGhostBtn) mtbEditStart.setStringW(PtGetLocalizedString("KI.MarkerGame.EditButton")) mtbEditStart.show() mbtnPlayEnd.show() mtbPlayEnd.setForeColor(kColors.DniShowBtn) mtbPlayEnd.setString(PtGetLocalizedString("KI.MarkerGame.PlayButton")) mtbPlayEnd.show() mlbMarkerList.hide() mlbMarkerTextTB.hide() mbtnToran.hide() mbtnHSpan.hide() mbtnVSpan.hide() mtbToran.hide() mtbHSPan.hide() mtbVSpan.hide() mbtnMarkerText.disable() # Is the player editing a Marker Game? elif self.MFdialogMode == kGames.MFEditing or self.MFdialogMode == kGames.MFEditingMarker: mrkfldTitleBtn.enable() mbtnDelete.hide() mbtnGameTimePullD.hide() mbtnGameTimeArrow.hide() mbtnEditStart.show() mtbEditStart.setForeColor(kColors.DniShowBtn) mbtnPlayEnd.show() mtbPlayEnd.setForeColor(kColors.DniShowBtn) # Is the player editing the entire game? if self.MFdialogMode == kGames.MFEditing: mtbEditStart.setStringW(PtGetLocalizedString("KI.MarkerGame.DoneEditButton")) mtbEditStart.show() mtbPlayEnd.setStringW(PtGetLocalizedString("KI.MarkerGame.AddMarkerButton")) mtbPlayEnd.show() mlbMarkerList.clearAllElements() mlbMarkerList.show() # Add the Markers to the list. for idx, age, pos, desc in mgr.markers: coord = ptDniCoordinates() coord.fromPoint(pos) torans = coord.getTorans() hSpans = coord.getHSpans() vSpans = coord.getVSpans() mlbMarkerList.addStringW(u"[{}:{},{},{}] {}".format(FilterAgeName(age), torans, hSpans, vSpans, xCensor.xCensor(desc, self.censorLevel))) mlbMarkerTextTB.hide() mbtnToran.hide() mbtnHSpan.hide() mbtnVSpan.hide() mtbToran.hide() mtbHSPan.hide() mtbVSpan.hide() mbtnMarkerText.disable() # Or just editing one of the Markers? else: selectedMarker = mgr.selected_marker if selectedMarker is not None: idx, age, pos, desc = selectedMarker # Must be editing a Marker. mtbEditStart.setStringW(PtGetLocalizedString("KI.MarkerGame.MarkerListButton")) mtbEditStart.show() mtbPlayEnd.setStringW(PtGetLocalizedString("KI.MarkerGame.RemoveMarkerButton")) mtbPlayEnd.show() mlbMarkerList.hide() mlbMarkerTextTB.show() # don't censor here... we don't want censored stuff saved to the vault mlbMarkerTextTB.setStringW(desc) mbtnToran.show() mbtnHSpan.show() mbtnVSpan.show() mtbToran.show() mtbHSPan.show() mtbVSpan.show() # Get the selected Marker's coordinates. coord = ptDniCoordinates() coord.fromPoint(pos) mtbToran.setString(str(coord.getTorans())) mtbHSPan.setString(str(coord.getHSpans())) mtbVSpan.setString(str(coord.getVSpans())) mbtnMarkerText.show() mbtnMarkerText.enable() else: # Error... PtDebugPrint(u"xKI.BigKIFinishDisplayMarkerGame(): Could not find selected marker.", level=kErrorLevel) mtbEditStart.setStringW(PtGetLocalizedString("KI.MarkerGame.GoBackButton")) mtbEditStart.show() mtbPlayEnd.setString(" ") mtbPlayEnd.show() mlbMarkerList.hide() mlbMarkerTextTB.show() mlbMarkerTextTB.setString("?Unknown Marker?") mbtnToran.hide() mbtnHSpan.hide() mbtnVSpan.hide() mtbToran.hide() mtbHSPan.hide() mtbVSpan.hide() # Is the player currently playing a Marker Game? elif self.MFdialogMode == kGames.MFPlaying: mrkfldTitleBtn.disable() mbtnDelete.hide() mbtnGameTimePullD.hide() mbtnGameTimeArrow.hide() mbtnToran.hide() mbtnHSpan.hide() mbtnVSpan.hide() mtbToran.hide() mtbHSPan.hide() mtbVSpan.hide() mbtnMarkerText.disable() mbtnEditStart.show() mtbEditStart.setForeColor(kColors.DniShowBtn) mtbEditStart.setString(PtGetLocalizedString("KI.MarkerGame.StopPlayingButton")) mtbEditStart.show() mbtnPlayEnd.show() mtbPlayEnd.setForeColor(kColors.DniShowBtn) mtbPlayEnd.setString(PtGetLocalizedString("KI.MarkerGame.ResetGameButton")) mtbPlayEnd.show() mlbMarkerList.clearAllElements() mlbMarkerList.show() # Assume that the game is finished, unless an unseen Marker is still left. questGameFinished = True # Add the Markers into the list. for idx, age, pos, desc in mgr.markers: if mgr.IsMarkerCaptured(idx): coord = ptDniCoordinates() coord.fromPoint(pos) torans = coord.getTorans() hSpans = coord.getHSpans() vSpans = coord.getVSpans() mlbMarkerList.addStringW(u"[{}:{},{},{}] {}".format(FilterAgeName(age), torans, hSpans, vSpans, xCensor.xCensor(desc, self.censorLevel))) else: questGameFinished = False mlbMarkerTextTB.hide() # Refresh the text of the buttons (color changed). mtbEditStart.refresh() mtbPlayEnd.refresh() # Display the content on the screen. mrkfldTitle.setStringW(xCensor.xCensor(element.getGameName(), self.censorLevel)) mrkfldTitle.show() # Enable the editable Title. mrkfldTitleBtn.show() mrkfldTitleBtn.enable() count = mgr.marker_total if self.MFdialogMode == kGames.MFEditing or self.MFdialogMode == kGames.MFEditingMarker: if count == 0: statusLine = PtGetLocalizedString("KI.MarkerGame.StatusNoMarkers") elif count == 1: statusLine = PtGetLocalizedString("KI.MarkerGame.StatusOneMarker") else: statusLine = PtGetLocalizedString("KI.MarkerGame.StatusNMarkers", [str(count)]) else: if questGameFinished: statusLine = PtGetLocalizedString("KI.MarkerGame.StatusAllFound") else: statusLine = PtGetLocalizedString("KI.MarkerGame.StatusNotAllFound") mrkfldStatus.setStringW(statusLine) mrkfldStatus.show() creatorID = element.getCreatorNodeID() tempNode = ptVaultPlayerInfoNode() tempNode.playerSetID(creatorID) try: vault = ptVault() creatorName = vault.findNode(tempNode).upcastToPlayerInfoNode().playerGetName() except: creatorName = "" mrkfldOwner.setStringW(PtGetLocalizedString("KI.MarkerGame.OwnerTitle") + U" {} [ID:{:08d}]".format(creatorName, creatorID)) mrkfldOwner.show() # TODO: time limit mtbGameTime.hide() mtbGameTimeTitle.hide() def BigKIDisplayMarkerGameMessage(self, msg): """Displays some message in the Marker Folder subdialog""" # Save some typing. getControl = KIMarkerFolderExpanded.dialog.getControlFromTag # Disable all controls until we need them. mrkfldTitle = ptGUIControlTextBox(getControl(kGUI.MarkerFolderTitleText)) mrkfldTitle.hide() ptGUIControlTextBox(getControl(kGUI.MarkerFolderStatus)).hide() ptGUIControlTextBox(getControl(kGUI.MarkerFolderOwner)).hide() # Hide the scroll buttons for the Marker list; the scroll control will turn them back on. ptGUIControlButton(getControl(kGUI.MarkerFolderMarkerListUpBtn)).hide() ptGUIControlButton(getControl(kGUI.MarkerFolderMarkerListDownBtn)).hide() ptGUIControlButton(getControl(kGUI.MarkerFolderInvitePlayer)).hide() ptGUIControlButton(getControl(kGUI.MarkerFolderEditStartGame)).hide() ptGUIControlButton(getControl(kGUI.MarkerFolderPlayEndGame)).hide() ptGUIControlTextBox(getControl(kGUI.MarkerFolderInvitePlayerTB)).hide() ptGUIControlTextBox(getControl(kGUI.MarkerFolderEditStartGameTB)).hide() ptGUIControlTextBox(getControl(kGUI.MarkerFolderPlayEndGameTB)).hide() ptGUIControlButton(getControl(kGUI.MarkerFolderTitleBtn)).hide() ptGUIControlButton(getControl(kGUI.MarkerFolderDeleteBtn)).hide() ptGUIControlButton(getControl(kGUI.MarkerFolderTimePullDownBtn)).hide() ptGUIControlButton(getControl(kGUI.MarkerFolderTypePullDownBtn)).hide() ptGUIControlButton(getControl(kGUI.MarkerFolderTypePullDownBtn)).disable() ptGUIControlButton(getControl(kGUI.MarkerFolderTimeArrow)).hide() ptGUIControlButton(getControl(kGUI.MarkerFolderTypeArrow)).hide() ptGUIControlTextBox(getControl(kGUI.MarkerFolderGameTimeTB)).hide() ptGUIControlTextBox(getControl(kGUI.MarkerFolderGameTimeTitleTB)).hide() ptGUIControlTextBox(getControl(kGUI.MarkerFolderGameTypeTB)).hide() ptGUIControlListBox(getControl(kGUI.MarkerFolderMarkListbox)).hide() ptGUIControlTextBox(getControl(kGUI.MarkerFolderMarkerTextTB)).hide() ptGUIControlTextBox(getControl(kGUI.MarkerFolderMarkerTextBtn)).hide() ptGUIControlButton(getControl(kGUI.MarkerFolderToranIcon)).disable() ptGUIControlButton(getControl(kGUI.MarkerFolderHSpanIcon)).disable() ptGUIControlButton(getControl(kGUI.MarkerFolderVSpanIcon)).disable() ptGUIControlTextBox(getControl(kGUI.MarkerFolderToranTB)).hide() ptGUIControlTextBox(getControl(kGUI.MarkerFolderHSpanTB)).hide() ptGUIControlTextBox(getControl(kGUI.MarkerFolderVSpanTB)).hide() # Show the status. mrkfldTitle.setStringW(msg) mrkfldTitle.show() mrkfldTitle.refresh() ## Show the selected configuration screen. def ShowSelectedConfig(self): if self.BKConfigListOrder[self.BKFolderSelected] == PtGetLocalizedString("KI.Config.Settings"): self.ChangeBigKIMode(kGUI.BKKIExpanded) elif self.BKConfigListOrder[self.BKFolderSelected] == PtGetLocalizedString("KI.Config.Volume"): self.ChangeBigKIMode(kGUI.BKVolumeExpanded) else: # Is the dialog hidden? if self.BKRightSideMode != kGUI.BKAgeOwnerExpanded: self.ChangeBigKIMode(kGUI.BKAgeOwnerExpanded) # Otherwise, refresh it. else: self.RefreshAgeOwnerSettings() self.BigKIOnlySelectedToButtons() ## Enter edit mode for a particular field. def BigKIEnterEditMode(self, whichField): # Can't be in chatting mode. self.chatMgr.ToggleChatMode(0) # If the player was already in edit mode, save the values before re-entering. if self.BKInEditMode: self.BigKISaveEdit() if whichField == kGUI.BKEditFieldJRNTitle: textBox = ptGUIControlTextBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[whichField][kGUI.BKEditIDtextbox])) button = ptGUIControlButton(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[whichField][kGUI.BKEditIDbutton])) editBox = ptGUIControlEditBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[whichField][kGUI.BKEditIDeditbox])) elif whichField == kGUI.BKEditFieldPICTitle: textBox = ptGUIControlTextBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[whichField][kGUI.BKEditIDtextbox])) button = ptGUIControlButton(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[whichField][kGUI.BKEditIDbutton])) editBox = ptGUIControlEditBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[whichField][kGUI.BKEditIDeditbox])) editBox.setStringSize(56) else: textBox = None button = None editBox = None # Make sure it is a valid field to edit. if textBox is not None: if self.BKCurrentContent is not None: edElement = self.BKCurrentContent.getChild() else: edElement = None if edElement is not None: self.BKInEditMode = True self.BKEditContent = self.BKCurrentContent self.BKEditField = whichField # Hide the TextBox and the button. textBox.hide() button.hide() # Set the edit box and display it. if self.BKEditField == kGUI.BKEditFieldJRNTitle: edElement = edElement.upcastToTextNoteNode() editBox.setString(xCensor.xCensor(edElement.noteGetTitle(), self.censorLevel)) KIJournalExpanded.dialog.setFocus(editBox.getKey()) elif self.BKEditField == kGUI.BKEditFieldPICTitle: edElement = edElement.upcastToImageNode() editBox.setString(xCensor.xCensor(edElement.imageGetTitle(), self.censorLevel)) KIPictureExpanded.dialog.setFocus(editBox.getKey()) else: editBox.setString("") editBox.end() editBox.show() editBox.focus() if whichField == kGUI.BKEditFieldJRNTitle or whichField == kGUI.BKEditFieldJRNNote: KIJournalExpanded.dialog.refreshAllControls() elif whichField == kGUI.BKEditFieldPICTitle: KIPictureExpanded.dialog.refreshAllControls() else: PtDebugPrint(u"xKI.BigKIEnterEditMode(): Content has no element to edit.", level=kErrorLevel) else: # Is it for the journal edit? if whichField == kGUI.BKEditFieldJRNNote: # If so, then it's sort of automatically in edit mode. self.BKInEditMode = True self.BKEditContent = self.BKCurrentContent self.BKEditField = whichField ## Save what the player was editing to the right place. def BigKISaveEdit(self, noExitEditMode=False): if self.BKInEditMode: if self.BKEditField == kGUI.BKEditFieldJRNTitle: textBox = ptGUIControlTextBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDtextbox])) button = ptGUIControlButton(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDbutton])) editBox = ptGUIControlEditBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDeditbox])) elif self.BKEditField == kGUI.BKEditFieldJRNNote: textBox = ptGUIControlMultiLineEdit(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDtextbox])) button = None editBox = None elif self.BKEditField == kGUI.BKEditFieldPICTitle: textBox = ptGUIControlTextBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDtextbox])) button = ptGUIControlButton(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDbutton])) editBox = ptGUIControlEditBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDeditbox])) else: textBox = None button = None editBox = None # Make sure that it can be edited. if textBox is not None: if self.BKEditContent is not None: edElement = self.BKEditContent.getChild() if edElement is not None: if editBox is not None: if not editBox.wasEscaped(): textBox.setString(editBox.getString()) if self.BKEditField == kGUI.BKEditFieldJRNTitle: edElement = edElement.upcastToTextNoteNode() jTitle = editBox.getStringW() if jTitle[:len(PtGetLocalizedString("KI.Journal.InitialTitle"))] == PtGetLocalizedString("KI.Journal.InitialTitle"): # Make sure that the player actually added something (so as not to get a blank title). if jTitle != PtGetLocalizedString("KI.Journal.InitialTitle"): jTitle = jTitle[len(PtGetLocalizedString("KI.Journal.InitialTitle")):] edElement.setTitleW(jTitle) elif self.BKEditField == kGUI.BKEditFieldPICTitle: edElement = edElement.upcastToImageNode() pTitle = editBox.getStringW() if pTitle[:len(PtGetLocalizedString("KI.Image.InitialTitle"))] == PtGetLocalizedString("KI.Image.InitialTitle"): # Make sure that the player actually added something (so as not to get a blank title). if pTitle != PtGetLocalizedString("KI.Image.InitialTitle"): pTitle = pTitle[len(PtGetLocalizedString("KI.Image.InitialTitle")):] edElement.setTitleW(pTitle) edElement.save() else: if self.BKEditField == kGUI.BKEditFieldJRNNote: buf = textBox.getEncodedBufferW() if buf[:len(PtGetLocalizedString("KI.Journal.InitialMessage"))] == PtGetLocalizedString("KI.Journal.InitialMessage"): buf = buf[len(PtGetLocalizedString("KI.Journal.InitialMessage")):] edElement = edElement.upcastToTextNoteNode() edElement.setTextW(buf) edElement.save() if self.BKEditField != kGUI.BKEditFieldJRNNote: # Put the fields back into no-edit mode. textBox.show() button.show() editBox.hide() if not noExitEditMode: # Stop editing. self.BKInEditMode = False self.BKEditContent = None self.BKEditField = -1 ## If the focus has changed, check to see if editing should be stopped. def BigKICheckFocusChange(self): if self.BKInEditMode: if self.BKEditField == kGUI.BKEditFieldJRNTitle: editBox = ptGUIControlEditBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDeditbox])) elif self.BKEditField == kGUI.BKEditFieldPICTitle: editBox = ptGUIControlEditBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[self.BKEditField][kGUI.BKEditIDeditbox])) else: editBox = None if editBox is not None: if editBox.isFocused(): return self.BigKISaveEdit() ## Mark a content as seen (unimplemented) in the BigKI. def BigKISetSeen(self, content): if BigKI.dialog.isEnabled(): content.setSeen() #~~~~~~~~~~~~~~# # BigKI Saving # #~~~~~~~~~~~~~~# ## Save the player-editted name of an Age. def SaveAgeNameFromEdit(self, control): newTitle = "" try: # Get the selected Age config setting. myAge = self.BKConfigFolderDict[self.BKConfigListOrder[self.BKFolderSelected]] if not control.wasEscaped(): # Set the new title. myAge.setAgeUserDefinedName(control.getStringW()) myAge.save() PtDebugPrint(u"xKI.SaveAgeNameFromEdit(): Updating title to \"{}\".".format(control.getStringW()), level=kDebugDumpLevel ) else: PtDebugPrint(u"xKI.SaveAgeNameFromEdit(): Escape hit.", level=kDebugDumpLevel ) newTitle = myAge.getDisplayName() except LookupError: PtDebugPrint(u"xKI.SaveAgeNameFromEdit(): The current Age could not be found.", level=kDebugDumpLevel ) myAge = None control.hide() # Re-enable the button and text. title = ptGUIControlTextBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleTB)) title.setStringW(newTitle) title.show() titlebtn = ptGUIControlButton(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleBtn)) titlebtn.enable() ## Save the new name of the Marker Game. # This saves it both in the Vault and on the Game Server. def SaveMarkerGameNameFromEdit(self, control): title = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderTitleText)) if self.BKCurrentContent is not None: element = self.BKCurrentContent.getChild() if element is not None: dataType = element.getType() if dataType == PtVaultNodeTypes.kMarkerGameNode: element = element.upcastToMarkerGameNode() if element is not None: if not control.wasEscaped() and control.getString() != "": # Set the new title. newText = xCensor.xCensor(control.getStringW(), self.censorLevel) element.setGameName(control.getStringW()) title.setString(control.getStringW()) element.save() PtDebugPrint(u"xKI.SaveMarkerGameNameFromEdit(): Updating title to \"{}\".".format(newText), level=kDebugDumpLevel) self.RefreshPlayerList() else: PtDebugPrint(u"xKI.SaveMarkerGameNameFromEdit(): Escape hit.", level=kDebugDumpLevel) control.hide() # Re-enable the button and text. titlebtn = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderTitleBtn)) titlebtn.enable() title.show() ## Save the text of a Marker on the Game Server. def SaveMarkerTextFromEdit(self, control): title = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderMarkerTextTB)) if self.BKCurrentContent is not None: element = self.BKCurrentContent.getChild() if element is not None: dataType = element.getType() if dataType == PtVaultNodeTypes.kMarkerGameNode: element = element.upcastToMarkerGameNode() if element is not None: name = control.getStringW() if not control.wasEscaped() and name: self.markerGameManager.selected_marker_name = name else: PtDebugPrint(u"xKI.SaveMarkerTextFromEdit(): escape hit!", level=kDebugDumpLevel ) control.hide() # Re-enable the button and text. titlebtn = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderMarkerTextBtn)) titlebtn.enable() title.show() #~~~~~~~~~~~~~~~~~~~# # GUI Notifications # #~~~~~~~~~~~~~~~~~~~# ## Process notifications originating from the Blackbar. # This handles objects like the Yeesha book icon, the quitting icon, the # options menu icon and the miniKI icon, when the KI has been obtained. def ProcessNotifyBlackbar(self, control, event): if event == kDialogLoaded: pass elif event == kAction or event == kValueChanged: bbID = control.getTagID() if bbID == kGUI.MiniMaximizeRGID: if control.getValue() == 0: if PtIsDialogLoaded("KIMini"): KIMini.dialog.show() elif control.getValue() == -1: if PtIsDialogLoaded("KIMini"): KIMini.dialog.hide() elif bbID == kGUI.ExitButtonID: yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID)) yesText.setStringW(PtGetLocalizedString("KI.Messages.LeaveGame")) self.LocalizeDialog(0) logoutText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutTextID)) logoutText.show() logoutButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutButtonID)) logoutButton.show() KIYesNo.dialog.show() elif bbID == kGUI.PlayerBookCBID: if control.isChecked(): curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode() if self.isEntireYeeshaBookEnabled and (curBrainMode == PtBrainModes.kNonGeneric or curBrainMode == PtBrainModes.kAFK or curBrainMode == PtBrainModes.kSit): if not self.waitingForAnimation: self.ShowYeeshaBook() else: control.setChecked(0) else: control.setChecked(0) elif bbID == kGUI.OptionsMenuButtonID: PtShowDialog("OptionsMenuGUI") else: PtDebugPrint(u"xKI.ProcessNotifyBlackbar(): Don't know this control bbID = {}.".format(bbID), level=kDebugDumpLevel) elif event == kInterestingEvent: plybkCB = ptGUIControlCheckBox(KIBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID)) try: curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode() if self.isEntireYeeshaBookEnabled and (curBrainMode == PtBrainModes.kNonGeneric or curBrainMode == PtBrainModes.kAFK or curBrainMode == PtBrainModes.kSit): PtDebugPrint(u"xKI.ProcessNotifyBlackbar(): Show PlayerBook.", level=kDebugDumpLevel) plybkCB.show() else: PtDebugPrint(u"xKI.ProcessNotifyBlackbar(): On ladder, hide PlayerBook.", level=kDebugDumpLevel) plybkCB.hide() except NameError: if self.isEntireYeeshaBookEnabled: PtDebugPrint(u"xKI.ProcessNotifyBlackbar(): Show PlayerBook.", level=kDebugDumpLevel) plybkCB.show() else: PtDebugPrint(u"xKI.ProcessNotifyBlackbar(): On ladder, hide PlayerBook.", level=kDebugDumpLevel) plybkCB.hide() ## Process notifications originating from the microKI's Blackbar. # This takes care of the same duties at the Blackbar processor, with the # sole difference that it is used only while the user does not yet possess # a full KI from Gahreesen (thus there is no miniKI icon). def ProcessNotifyMicroBlackbar(self, control, event): if event == kDialogLoaded: rollBtn = ptGUIControlButton(KIMicroBlackbar.dialog.getControlFromTag(kGUI.RolloverLeftID)) rollBtn.setNotifyOnInteresting(1) rollBtn = ptGUIControlButton(KIMicroBlackbar.dialog.getControlFromTag(kGUI.RolloverRightID)) rollBtn.setNotifyOnInteresting(1) elif event == kAction or event == kValueChanged: bbID = control.getTagID() if bbID == kGUI.ExitButtonID: yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID)) yesText.setStringW(PtGetLocalizedString("KI.Messages.LeaveGame")) self.LocalizeDialog(0) logoutText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutTextID)) logoutText.show() logoutButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutButtonID)) logoutButton.show() KIYesNo.dialog.show() elif bbID == kGUI.PlayerBookCBID: if control.isChecked(): curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode() if self.isEntireYeeshaBookEnabled and (curBrainMode == PtBrainModes.kNonGeneric or curBrainMode == PtBrainModes.kAFK or curBrainMode == PtBrainModes.kSit): if not self.waitingForAnimation: self.ShowYeeshaBook() else: control.setChecked(0) else: control.setChecked(0) elif bbID == kGUI.OptionsMenuButtonID: PtShowDialog("OptionsMenuGUI") else: PtDebugPrint(u"xKI.ProcessNotifyMicroBlackbar(): Don't know this control bbID = {}.".format(bbID), level=kDebugDumpLevel) elif event == kInterestingEvent: plybkCB = ptGUIControlCheckBox(KIMicroBlackbar.dialog.getControlFromTag(kGUI.PlayerBookCBID)) try: curBrainMode = PtGetLocalAvatar().avatar.getCurrentMode() if self.isEntireYeeshaBookEnabled and (curBrainMode == PtBrainModes.kNonGeneric or curBrainMode == PtBrainModes.kAFK or curBrainMode == PtBrainModes.kSit): PtDebugPrint(u"xKI.ProcessNotifyMicroBlackbar(): Show PlayerBook.", level=kDebugDumpLevel) plybkCB.show() else: PtDebugPrint(u"xKI.ProcessNotifyMicroBlackbar(): On ladder, hide PlayerBook.", level=kDebugDumpLevel) plybkCB.hide() except NameError: if self.isEntireYeeshaBookEnabled: PtDebugPrint(u"xKI.ProcessNotifyMicroBlackbar(): Show PlayerBook.", level=kDebugDumpLevel) plybkCB.show() else: PtDebugPrint(u"xKI.ProcessNotifyMicroBlackbar(): On ladder, hide PlayerBook.", level=kDebugDumpLevel) plybkCB.hide() ## Process notifications originating from the microKI. # These notifications get called when using the basic chat mode available # only until the user obtains a real KI from Gahreesen (thus the name, # microKI). def ProcessNotifyMicro(self, control, event): if event == kDialogLoaded: # Fill in the listbox so that the test is near the enter box. chatArea = ptGUIControlMultiLineEdit(KIMicro.dialog.getControlFromTag(kGUI.ChatDisplayArea)) chatArea.lock() # Make the chat display immutable. chatArea.unclickable() # Make the chat display non-clickable. chatArea.moveCursor(PtGUIMultiLineDirection.kBufferEnd) chatArea.disableScrollControl() btnUp = ptGUIControlButton(KIMicro.dialog.getControlFromTag(kGUI.miniChatScrollUp)) btnUp.show() btnUp.hide() # Set the edit box buffer size to something larger. chatedit = ptGUIControlEditBox(KIMicro.dialog.getControlFromTag(kGUI.ChatEditboxID)) chatedit.setStringSize(500) chatedit.setChatMode(1) elif event == kShowHide: if control.isEnabled(): if not self.chatMgr.isChatting: self.FadeCompletely() elif event == kAction or event == kValueChanged: ctrlID = control.getTagID() if ctrlID == kGUI.ChatEditboxID: if not control.wasEscaped() and control.getStringW() != "": self.chatMgr.SendMessage(control.getStringW()) self.chatMgr.ToggleChatMode(0) elif ctrlID == kGUI.ChatDisplayArea: self.ResetFadeState() elif event == kFocusChange: # If they are chatting, get the focus back. if self.chatMgr.isChatting: KIMicro.dialog.setFocus(KIMicro.dialog.getControlFromTag(kGUI.ChatEditboxID)) elif event == kSpecialAction: ctrlID = control.getTagID() if ctrlID == kGUI.ChatEditboxID: self.Autocomplete(control) ## Process notifications originating from the miniKI. # The miniKI is the display in the top-left corner of the screen (by # default); these notifications are triggered through interaction with the # various buttons on it. It also takes care of the floating player list. def ProcessNotifyMini(self, control, event): if event == kDialogLoaded: # Get the original position of the miniKI. dragbar = ptGUIControlDragBar(KIMini.dialog.getControlFromTag(kGUI.miniDragBar)) self.originalminiKICenter = dragbar.getObjectCenter() # Retreive the original alpha. fore = control.getForeColor() self.originalForeAlpha = fore.getAlpha() sel = control.getSelectColor() self.originalSelectAlpha = sel.getAlpha() # Fill in the listbox so that the test is near the enter box. chatArea = ptGUIControlMultiLineEdit(KIMini.dialog.getControlFromTag(kGUI.ChatDisplayArea)) chatArea.lock() # Make the chat display immutable. chatArea.unclickable() # Make the chat display non-clickable. chatArea.moveCursor(PtGUIMultiLineDirection.kBufferEnd) # Hide the chat scroll buttons (should be nothing in chat area yet anyhow). chatArea.disableScrollControl() btnUp = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniChatScrollUp)) btnUp.show() privateChbox = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniPrivateToggle)) privateChbox.disable() # Set the edit box buffer size to something larger. chatedit = ptGUIControlEditBox(KIMini.dialog.getControlFromTag(kGUI.ChatEditboxID)) chatedit.setStringSize(500) chatedit.setChatMode(1) # Default the marker tag stuff to be off. btnmt = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZDrip)) btnmt.hide() btnmt = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZActive)) btnmt.hide() btnmt = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZMarkerGameActive)) btnmt.hide() btnmt = ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniGZMarkerInRange)) btnmt.hide() ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGNewMarker)).hide() ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGNewGame)).hide() ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGInactive)).hide() ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.miniMGInactive)).disable() ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.PelletScoreButton)).hide() # Set the color to the off color. for mcbID in range(kGUI.miniMarkerIndicator01, kGUI.miniMarkerIndicatorLast + 1): mcb = ptGUIControlProgress(KIMini.dialog.getControlFromTag(mcbID)) mcb.setValue(kGUI.miniMarkerColors["off"]) elif event == kShowHide: if control.isEnabled(): if self.pelletImager != "": ptGUIControlButton(KIMini.dialog.getControlFromTag(kGUI.PelletScoreButton)).show() if self.miniKIFirstTimeShow: # Set the font size and fade time. self.DetermineFontSize() self.DetermineFadeTime() # If we are chatting then just let it happen. if not self.chatMgr.isChatting: self.chatMgr.ToggleChatMode(0) self.FadeCompletely() self.miniKIFirstTimeShow = False self.RefreshPlayerList() self.RefreshMiniKIMarkerDisplay() else: self.chatMgr.ToggleChatMode(0) self.chatMgr.ClearBBMini() elif event == kAction or event == kValueChanged: ctrlID = control.getTagID() if ctrlID == kGUI.ChatEditboxID: if not control.wasEscaped() and control.getStringW() != u"": self.chatMgr.SendMessage(control.getStringW()) self.chatMgr.ToggleChatMode(0) self.StartFadeTimer() elif ctrlID == kGUI.PlayerList: # Make sure they don't click outside what's there. plyrsel = control.getSelection() if plyrsel >= control.getNumElements(): control.setSelection(0) plyrsel = 0 # Place selected player in SendTo textbox. sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine)) caret = ptGUIControlTextBox(KIMini.dialog.getControlFromTag(kGUI.ChatCaretID)) caret.setString(">") privateChbox = ptGUIControlCheckBox(KIMini.dialog.getControlFromTag(kGUI.miniPrivateToggle)) privateChbox.setChecked(0) if plyrsel == -1: self.BKPlayerSelected = None else: self.BKPlayerSelected = self.BKPlayerList[plyrsel] # Is it a Device Folder or just a string? if isinstance(self.BKPlayerSelected, DeviceFolder) or isinstance(self.BKPlayerSelected, str): # Can't be sent to. pass elif isinstance(self.BKPlayerSelected, Device): sendToField.setString(self.BKPlayerSelected.name) # Is it a specific player info node? elif isinstance(self.BKPlayerSelected, ptVaultNodeRef): plyrInfoNode = self.BKPlayerSelected.getChild() plyrInfo = plyrInfoNode.upcastToPlayerInfoNode() if plyrInfo is not None: sendToField.setString(plyrInfo.playerGetName()) # Set private caret. caret.setStringW(PtGetLocalizedString("KI.Chat.TOPrompt") + unicode(plyrInfo.playerGetName()) + U" >") privateChbox.setChecked(1) else: self.BKPlayerSelected = None # Is it a specific player? elif isinstance(self.BKPlayerSelected, ptPlayer): sendToField.setString(self.BKPlayerSelected.getPlayerName()) caret.setStringW(PtGetLocalizedString("KI.Chat.TOPrompt") + unicode(self.BKPlayerSelected.getPlayerName()) + U" >") privateChbox.setChecked(1) # Is it a list of players? elif isinstance(self.BKPlayerSelected, ptVaultPlayerInfoListNode): fldrType = self.BKPlayerSelected.folderGetType() # Is it not the All Players folder? if fldrType != PtVaultStandardNodes.kAgeMembersFolder: # If it's a list of age owners, it's a list of neighbors. if fldrType == PtVaultStandardNodes.kAgeOwnersFolder: fldrType = PtVaultStandardNodes.kHoodMembersFolder caret.setStringW(PtGetLocalizedString("KI.Chat.TOPrompt") + xLocTools.FolderIDToFolderName(fldrType) + U" >") # It's not private and no player is selected. privateChbox.setChecked(0) self.BKPlayerSelected = None if self.BKPlayerSelected is None: sendToField.setString(" ") self.SetBigKIToButtons() # No need to keep the focus. if self.chatMgr.isChatting: chatedit = ptGUIControlEditBox(KIMini.dialog.getControlFromTag(kGUI.ChatEditboxID)) KIMini.dialog.setFocus(chatedit.getKey()) # They're playing with the player list, so reset the fade. self.ResetFadeState() elif ctrlID == kGUI.miniPutAwayID: self.ToggleMiniKI() elif ctrlID == kGUI.miniToggleBtnID: self.ToggleKISize() elif ctrlID == kGUI.miniTakePicture: self.TakePicture() elif ctrlID == kGUI.miniCreateJournal: self.MiniKICreateJournalNote() elif ctrlID == kGUI.miniMuteAll: # Hit the mute button, and set mute depending on control. audio = ptAudioControl() if control.isChecked(): audio.muteAll() else: audio.unmuteAll() elif ctrlID == kGUI.miniPlayerListUp: # Scroll the player list up one line. self.ScrollPlayerList(1) elif ctrlID == kGUI.miniPlayerListDown: # Scroll the player list down one line. self.ScrollPlayerList(-1) elif ctrlID == kGUI.miniGZMarkerInRange: self.CaptureGZMarker() self.RefreshMiniKIMarkerDisplay() elif ctrlID == kGUI.ChatDisplayArea: self.ResetFadeState() elif ctrlID == kGUI.miniMGNewMarker: self.CreateAMarker() elif ctrlID == kGUI.miniMGNewGame: self.CreateMarkerGame() elif ctrlID == kJalakMiniIconBtn: if PtGetAgeName() == "Jalak": self.JalakGUIToggle() else: ptGUIControlButton(KIMini.dialog.getControlFromTag(kJalakMiniIconBtn)).disable() elif ctrlID == kGUI.PelletScoreButton: self.UploadPelletScore() elif event == kFocusChange: # If they are chatting, get the focus back. if self.chatMgr.isChatting: # If the bigKI is up then let the focus go where it wants. # Otherwise put the focus back to the chat line. if not BigKI.dialog.isEnabled(): KIMini.dialog.setFocus(KIMini.dialog.getControlFromTag(kGUI.ChatEditboxID)) else: if not self.BKInEditMode: KIMini.dialog.setFocus(KIMini.dialog.getControlFromTag(kGUI.ChatEditboxID)) elif event == kSpecialAction: ctrlID = control.getTagID() if ctrlID == kGUI.ChatEditboxID: self.Autocomplete(control) # Up or Down key to scroll in the chat history elif event == kMessageHistoryUp: ctrlID = control.getTagID() if ctrlID == kGUI.ChatEditboxID: self.MessageHistory(control, "up") elif event == kMessageHistoryDown: ctrlID = control.getTagID() if ctrlID == kGUI.ChatEditboxID: self.MessageHistory(control, "down") ## Process notifications originating from the BigKI itself. # This does not process notifications specific to an expanded view - each # view gets its own function, to avoid bloat. This rather deals with # controls such as the scroll button, the mode switcher, etc., anything # related to the navigation interface. def ProcessNotifyBigKI(self, control, event): if event == kDialogLoaded: self.BKInEditMode = False # Put animation at off position, so there is no pop when the animation plays. KIOnAnim.animation.skipToTime(1.5) pdisable = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKDisabledPeopleButton)) pdisable.disable() gdisable = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKDisabledGearButton)) gdisable.disable() for ID in range(kGUI.BKIIncomingBtn, kGUI.BKIFolderLineBtnLast): overBtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(ID)) overBtn.setNotifyOnInteresting(1) elif event == kShowHide: if control.isEnabled(): # Hide the long folder names. for ID in range(kGUI.LONGBKIIncomingLine,kGUI.LONGBKIFolderLineLast+1): longTB = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(ID)) longTB.hide() self.BigKISetStatics() self.BigKISetChanging() self.RefreshPlayerList() self.KillFadeTimer() self.BigKIRefreshFolderList() self.BigKIRefreshFolderDisplay() self.ShowBigKI() else: self.StartFadeTimer() elif event == kAction or event == kValueChanged: bkID = control.getTagID() # Is it one of the folder buttons? if bkID >= kGUI.BKIIncomingBtn and bkID <= kGUI.BKIFolderLineBtnLast: if self.BKFolderLineDict is self.BKConfigFolderDict: self.BKFolderSelected = bkID - kGUI.BKIIncomingBtn + self.BKFolderTopLine self.ShowSelectedConfig() else: oldselect = self.BKFolderSelected self.BKFolderSelected = bkID - kGUI.BKIIncomingBtn + self.BKFolderTopLine if oldselect != self.BKFolderSelected: self.BKFolderSelectChanged = True else: self.BKFolderSelectChanged = False self.ChangeBigKIMode(kGUI.BKListMode) # Is it the scroll folder up button? elif bkID == kGUI.BKFolderUpLine: if self.BKFolderTopLine > 0: self.BKFolderTopLine -= 1 self.BigKIRefreshFolderDisplay() self.SetBigKIToButtons() # Is it the scroll folder down button? elif bkID == kGUI.BKFolderDownLine: self.BKFolderTopLine += 1 self.BigKIRefreshFolderDisplay() self.SetBigKIToButtons() elif bkID == kGUI.BKLMUpButton: if self.BKRightSideMode == kGUI.BKListMode: if self.BKContentListTopLine > 0: self.BKContentListTopLine -= kContentListScrollSize if self.BKContentListTopLine < 0: self.BKContentListTopLine = 0 self.BigKIRefreshContentListDisplay() elif bkID == kGUI.BKLMDownButton: if self.BKRightSideMode == kGUI.BKListMode: self.BKContentListTopLine += kContentListScrollSize self.BigKIRefreshContentListDisplay() elif bkID >= kGUI.BKIToIncomingButton and bkID <= kGUI.BKIToFolderButtonLast: toFolderNum = bkID - kGUI.BKIToFolderButton01 + self.BKFolderTopLine + 1 # If they are in an expanded mode, then they can move the element to another folder. if self.BKRightSideMode != kGUI.BKListMode and self.BKCurrentContent is not None: # Move the current content to the selected folder. if isinstance(self.BKCurrentContent, ptPlayer): # Add to new folder. try: newFolderName = self.BKFolderListOrder[toFolderNum] newFolder = self.BKFolderLineDict[newFolderName] playerID = self.BKCurrentContent.getPlayerID() localPlayerID = PtGetLocalPlayer().getPlayerID() if newFolder is not None and playerID != localPlayerID: if newFolder.getType() == PtVaultNodeTypes.kAgeInfoNode: self.InviteToVisit(playerID, newFolder) elif newFolder.getType() == PtVaultNodeTypes.kPlayerInfoListNode: newFolder.playerlistAddPlayer(playerID) except (IndexError, KeyError): # If there was an error, display whatever was already selected. toFolderNum = self.BKFolderSelected else: oldFolder = self.BKCurrentContent.getParent() theElement = self.BKCurrentContent.getChild() if theElement is not None: # Add to new folder. try: newFolderName = self.BKFolderListOrder[toFolderNum] newFolder = self.BKFolderLineDict[newFolderName] localPlayerID = PtGetLocalPlayer().getPlayerID() if newFolder is not None: if newFolder.getType() == PtVaultNodeTypes.kAgeInfoNode: theElement = theElement.upcastToPlayerInfoNode() if theElement is not None and theElement.playerGetID() != localPlayerID: self.InviteToVisit(theElement.playerGetID(), newFolder) elif newFolder.getType() == PtVaultNodeTypes.kPlayerInfoListNode: theElement = theElement.upcastToPlayerInfoNode() if theElement is not None and theElement.playerGetID() != localPlayerID: theElement = theElement.upcastToPlayerInfoNode() newFolder.playerlistAddPlayer(theElement.playerGetID()) else: self.BKCurrentContent = newFolder.addNode(theElement) if oldFolder is not None: oldFolder.removeNode(theElement) except (IndexError, KeyError): # If there was an error, display whatever was already selected. toFolderNum = self.BKFolderSelected # Leave it at the folder they are on. self.BKFolderSelectChanged = True self.ChangeBigKIMode(kGUI.BKListMode) # They could have copied a player, so refresh list. self.RefreshPlayerList() elif bkID == kGUI.BKRadioModeID: # Save the previous selected and top line. if self.BKFolderLineDict is self.BKJournalFolderDict: self.BKJournalFolderSelected = self.BKFolderSelected self.BKJournalFolderTopLine = self.BKFolderTopLine elif self.BKFolderLineDict is self.BKPlayerFolderDict: self.BKPlayerFolderSelected = self.BKFolderSelected self.BKPlayerFolderTopLine = self.BKFolderTopLine elif self.BKFolderLineDict is self.BKConfigFolderDict: self.BKConfigFolderSelected = self.BKFolderSelected self.BKConfigFolderTopLine = self.BKFolderTopLine modeselect = control.getValue() # Is it journal mode? if modeselect == 0: self.BKFolderLineDict = self.BKJournalFolderDict self.BKFolderListOrder = self.BKJournalListOrder self.BKFolderSelected = self.BKJournalFolderSelected self.BKFolderTopLine = self.BKJournalFolderTopLine # Is it player list mode? elif modeselect == 1: self.BKFolderLineDict = self.BKPlayerFolderDict self.BKFolderListOrder = self.BKPlayerListOrder self.BKFolderSelected = self.BKPlayerFolderSelected self.BKFolderTopLine = self.BKPlayerFolderTopLine # It is configuration mode. else: self.BKFolderLineDict = self.BKConfigFolderDict self.BKFolderListOrder = self.BKConfigListOrder self.BKFolderSelected = self.BKConfigFolderSelected self.BKFolderTopLine = self.BKConfigFolderTopLine # Reset the top line and selection. self.BigKIRefreshFolderDisplay() if modeselect == 0 and (self.BKRightSideMode == kGUI.BKPictureExpanded or self.BKRightSideMode == kGUI.BKJournalExpanded or self.BKRightSideMode == kGUI.BKMarkerListExpanded): # The player is taking a picture. self.BigKIInvertToFolderButtons() else: # Is the player switching to configuration mode? if modeselect == 2: self.ShowSelectedConfig() # Otherwise, make sure the player is in list mode. else: self.ChangeBigKIMode(kGUI.BKListMode) elif bkID == kGUI.BKIToPlayerButton: if self.BKCurrentContent is not None and self.BKPlayerSelected is not None: sendElement = self.BKCurrentContent.getChild() toPlayerBtn = ptGUIControlButton(BigKI.dialog.getControlFromTag(kGUI.BKIToPlayerButton)) if sendElement is not None: if isinstance(self.BKPlayerSelected, DeviceFolder): pass elif isinstance(self.BKPlayerSelected, Device): if self.BKPlayerSelected.name in self.imagerMap: sName = "Upload={}".format(self.BKPlayerSelected.name) SendNote(self.key, self.imagerMap[self.BKPlayerSelected.name], sName, sendElement.getID()) toPlayerBtn.hide() elif isinstance(self.BKPlayerSelected, ptVaultNode): if self.BKPlayerSelected.getType() == PtVaultNodeTypes.kPlayerInfoListNode: plyrRefList = self.BKPlayerSelected.getChildNodeRefList() for plyrRef in plyrRefList: plyr = plyrRef.getChild() plyr = plyr.upcastToPlayerInfoNode() if plyr is not None: sendElement.sendTo(plyr.playerGetID()) elif self.BKPlayerSelected.getType() == PtVaultNodeTypes.kPlayerInfoNode: sendElement.sendTo(self.BKPlayerSelected.playerGetID()) else: self.SetSendToErrorMessage(PtGetLocalizedString("KI.Errors.CantSend")) toPlayerBtn.hide() elif isinstance(self.BKPlayerSelected, ptVaultNodeRef): plyrElement = self.BKPlayerSelected.getChild() if plyrElement is not None and plyrElement.getType() == PtVaultNodeTypes.kPlayerInfoNode: plyrElement = plyrElement.upcastToPlayerInfoNode() sendElement.sendTo(plyrElement.playerGetID()) else: self.SetSendToErrorMessage(PtGetLocalizedString("KI.Errors.PlayerNotFound")) toPlayerBtn.hide() elif isinstance(self.BKPlayerSelected, ptPlayer): sendElement.sendTo(self.BKPlayerSelected.getPlayerID()) toPlayerBtn.hide() else: self.SetSendToErrorMessage(PtGetLocalizedString("KI.Errors.UnknownPlayerType")) else: self.SetSendToErrorMessage(PtGetLocalizedString("KI.Errors.BadJournalElement")) elif event == kInterestingEvent: if control is not None: shortTB = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(control.getTagID() + 21)) longTB = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(control.getTagID() + 521)) if shortTB.getStringJustify() == kRightJustify and control.isInteresting(): # Switch to long versions. longTB.setForeColor(shortTB.getForeColor()) longTB.setString(shortTB.getString()) shortTB.hide() longTB.show() else: shortTB.show() longTB.hide() ## Process notifications originating from a list mode in the BigKI. # Handles navigation from a list mode (like a list of players or notes) to # the specified content (a picture, a note, a marker game...). Also takes # care of creating a new entry when asked. def ProcessNotifyListMode(self, control, event): if event == kAction or event == kValueChanged: lmID = control.getTagID() if lmID >= kGUI.BKIListModeLineBtn01 and lmID <= kGUI.BKIListModeLineBtnLast: # Find out which button was clicked and its associated content. whichOne = lmID - kGUI.BKIListModeLineBtn01 + self.BKContentListTopLine if whichOne < len(self.BKContentList): theContent = self.BKContentList[whichOne] if theContent is not None: self.BKCurrentContent = theContent if isinstance(self.BKCurrentContent, ptPlayer): nextMode = kGUI.BKPlayerExpanded self.ChangeBigKIMode(nextMode) else: theElement = theContent.getChild() if theElement is not None: dataType = theElement.getType() if dataType == PtVaultNodeTypes.kTextNoteNode: nextMode = kGUI.BKJournalExpanded elif dataType == PtVaultNodeTypes.kImageNode: nextMode = kGUI.BKPictureExpanded elif dataType == PtVaultNodeTypes.kPlayerInfoNode: nextMode = kGUI.BKPlayerExpanded elif dataType == PtVaultNodeTypes.kMarkerGameNode: nextMode = kGUI.BKMarkerListExpanded else: self.BKCurrentContent = None nextMode = kGUI.BKListMode self.ChangeBigKIMode(nextMode) else: PtDebugPrint(u"xKI.ProcessNotifyListMode(): List Mode: content is None for element!", level=kErrorLevel) elif lmID == kGUI.BKIListModeCreateBtn: if self.BKFolderLineDict is self.BKPlayerFolderDict: self.BKGettingPlayerID = True self.ChangeBigKIMode(kGUI.BKPlayerExpanded) else: self.BigKICreateJournalNote() self.ChangeBigKIMode(kGUI.BKJournalExpanded) self.BigKIDisplayJournalEntry() self.BigKIEnterEditMode(kGUI.BKEditFieldJRNTitle) ## Process notifications originating from an expanded picture mode in the BigKI. # This essentially deals with the taking of new pictures and the editing of # existing ones, as well as their deletion. def ProcessNotifyPictureExpanded(self, control, event): if event == kDialogLoaded: editBox = ptGUIControlEditBox(KIPictureExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[kGUI.BKEditFieldPICTitle][kGUI.BKEditIDeditbox])) editBox.hide() elif event == kShowHide: if control.isEnabled(): self.BigKIDisplayPicture() elif event == kAction or event == kValueChanged: peID = control.getTagID() if peID == kGUI.BKIPICTitleButton: if self.IsContentMutable(self.BKCurrentContent): self.BigKIEnterEditMode(kGUI.BKEditFieldPICTitle) elif peID == kGUI.BKIPICDeleteButton: self.YNWhatReason = kGUI.YNDelete elem = self.BKCurrentContent.getChild() elem = elem.upcastToImageNode() if elem is not None: picTitle = elem.imageGetTitle() else: picTitle = "<unknown>" yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID)) yesText.setStringW(PtGetLocalizedString("KI.Messages.DeletePicture", [xCensor.xCensor(picTitle, self.censorLevel)])) self.LocalizeDialog(1) KIYesNo.dialog.show() elif peID == kGUI.BKIPICTitleEdit: self.BigKISaveEdit(1) elif event == kFocusChange: if self.IsContentMutable(self.BKCurrentContent): self.BigKICheckFocusChange() ## Process notifications originating from an expanded journal mode in the BigKI. # Handles note creation, editing and deletion. def ProcessNotifyJournalExpanded(self, control, event): if event == kDialogLoaded: editBox = ptGUIControlEditBox(KIJournalExpanded.dialog.getControlFromTag(kGUI.BKEditFieldIDs[kGUI.BKEditFieldJRNTitle][kGUI.BKEditIDeditbox])) editBox.hide() elif event == kShowHide: if control.isEnabled(): self.BigKIDisplayJournalEntry() elif event == kAction or event == kValueChanged: jeID = control.getTagID() # Is it one of the buttons? if jeID == kGUI.BKIJRNTitleButton: if self.IsContentMutable(self.BKCurrentContent): self.BigKIEnterEditMode(kGUI.BKEditFieldJRNTitle) elif jeID == kGUI.BKIJRNNoteButton: if self.IsContentMutable(self.BKCurrentContent): self.BigKIEnterEditMode(kGUI.BKEditFieldJRNNote) elif jeID == kGUI.BKIJRNDeleteButton: self.YNWhatReason = kGUI.YNDelete elem = self.BKCurrentContent.getChild() elem = elem.upcastToTextNoteNode() if elem is not None: jrnTitle = elem.noteGetTitle() else: jrnTitle = "<unknown>" yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID)) yesText.setStringW(PtGetLocalizedString("KI.Messages.DeleteJournal", [xCensor.xCensor(jrnTitle, self.censorLevel)])) self.LocalizeDialog(1) KIYesNo.dialog.show() # Is it one of the editing boxes? elif jeID == kGUI.BKIJRNTitleEdit or jeID == kGUI.BKIJRNNoteEdit: if self.IsContentMutable(self.BKCurrentContent): self.BigKISaveEdit(1) elif event == kFocusChange: if self.IsContentMutable(self.BKCurrentContent): if control is not None: # If the focus is changing to the multiline, the plaer is entering edit mode. jeID = control.getTagID() if jeID == kGUI.BKIJRNNote: self.BigKIEnterEditMode(kGUI.BKEditFieldJRNNote) return self.BigKICheckFocusChange() ## Process notifications originating from an expanded player mode in the BigKI. # Handles deletion of a player's entry. def ProcessNotifyPlayerExpanded(self, control, event): if event == kShowHide: if control.isEnabled(): self.BigKIDisplayPlayerEntry() elif event == kAction or event == kValueChanged: plID = control.getTagID() # Is it one of the buttons? if plID == kGUI.BKIPLYDeleteButton: self.YNWhatReason = kGUI.YNDelete elem = self.BKCurrentContent.getChild() elem = elem.upcastToPlayerInfoNode() if elem is not None: plyrName = elem.playerGetName() else: plyrName = "<unknown>" try: pfldName = self.BKFolderListOrder[self.BKFolderSelected] except LookupError: pfldName = "<unknown>" yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID)) yesText.setStringW(PtGetLocalizedString("KI.Messages.DeletePlayer", [xCensor.xCensor(plyrName, self.censorLevel), pfldName])) self.LocalizeDialog(1) KIYesNo.dialog.show() elif plID == kGUI.BKIPLYPlayerIDEditBox: self.BigKICheckSavePlayer() elif event == kFocusChange: if self.BKGettingPlayerID: if KIPlayerExpanded.dialog.isEnabled(): plyIDedit = ptGUIControlEditBox(KIPlayerExpanded.dialog.getControlFromTag(kGUI.BKIPLYPlayerIDEditBox)) plyIDedit.focus() KIPlayerExpanded.dialog.setFocus(plyIDedit.getKey()) else: self.BKGettingPlayerID = False self.ChangeBigKIMode(kGUI.BKListMode) ## Process notifications originating from an expanded settings mode in the BigKI. # Handles the processing tied to settings modification. def ProcessNotifySettingsExpanded(self, control, event): if event == kShowHide: if control.isEnabled(): tfield = ptGUIControlTextBox(KISettings.dialog.getControlFromTag(kGUI.BKIKISettingsText)) tfield.setStringW(PtGetLocalizedString("KI.Config.Settings")) tfield = ptGUIControlTextBox(KISettings.dialog.getControlFromTag(kGUI.BKIKIFontSizeText)) tfield.setStringW(PtGetLocalizedString("KI.Config.FontSize")) tfield = ptGUIControlTextBox(KISettings.dialog.getControlFromTag(kGUI.BKIKIFadeTimeText)) tfield.setStringW(PtGetLocalizedString("KI.Config.ChatFadeTime")) tfield = ptGUIControlTextBox(KISettings.dialog.getControlFromTag(kGUI.BKIKIOnlyPMText)) tfield.setStringW(PtGetLocalizedString("KI.Config.OnlyBuddies")) self.RefreshKISettings() else: self.SaveFontSize() self.SaveFadeTime() self.SaveKIFlags() elif event == kAction or event == kValueChanged: kiID = control.getTagID() if kiID == kGUI.BKIKIFontSize: slidePerFont = float(control.getMax() - control.getMin() + 1.0) / float(len(kChat.FontSizeList)) fontIndex = int(control.getValue() / slidePerFont + 0.25) if fontIndex >= len(kChat.FontSizeList): fontIndex = len(kChat.FontSizeList) - 1 self.SetFontSize(kChat.FontSizeList[fontIndex]) elif kiID == kGUI.BKIKIFadeTime: slidePerTime = float(control.getMax() - control.getMin()) / float(kChat.FadeTimeMax) self.chatMgr.ticksOnFull = int(control.getValue() / slidePerTime + 0.25) PtDebugPrint(u"xKI.ProcessNotifySettingsExpanded(): FadeTime set to {}.".format(self.chatMgr.ticksOnFull), level=kDebugDumpLevel) if self.chatMgr.ticksOnFull == kChat.FadeTimeMax: self.chatMgr.fadeEnableFlag = False PtDebugPrint(u"KISettings: FadeTime disabled.", level=kDebugDumpLevel) else: self.chatMgr.fadeEnableFlag = True PtDebugPrint(u"KISettings: FadeTime enabled.", level=kDebugDumpLevel) elif kiID == kGUI.BKIKIOnlyPM: self.onlyGetPMsFromBuddies = control.isChecked() elif kiID == kGUI.BKIKIBuddyCheck: self.onlyAllowBuddiesOnRequest = control.isChecked() ## Process notifications originating from an expanded settings mode in the BigKI. # Handles the sound controls from the options menu being modified. def ProcessNotifyVolumeExpanded(self, control, event): if event == kShowHide: if control.isEnabled(): self.RefreshVolumeSettings() elif event == kAction or event == kValueChanged: plID = control.getTagID() audio = ptAudioControl() if plID == kGUI.BKISoundFXVolSlider: setting = control.getValue() PtDebugPrint(u"xKI.ProcessNotifyVolumeExpanded(): SoundFX being changed to {:g} (into {:g}).".format(setting, setting / 10), level=kDebugDumpLevel) audio.setSoundFXVolume(setting / 10) elif plID == kGUI.BKIMusicVolSlider: setting = control.getValue() PtDebugPrint(u"xKI.ProcessNotifyVolumeExpanded(): Music being changed to {:g} (into {:g}).".format(setting, setting / 10), level=kDebugDumpLevel) audio.setMusicVolume(setting / 10) elif plID == kGUI.BKIVoiceVolSlider: setting = control.getValue() PtDebugPrint(u"xKI.ProcessNotifyVolumeExpanded(): Voice being changed to {:g} (into {:g}).".format(setting, setting / 10), level=kDebugDumpLevel) audio.setVoiceVolume(setting / 10) elif plID == kGUI.BKIAmbienceVolSlider: setting = control.getValue() PtDebugPrint(u"xKI.ProcessNotifyVolumeExpanded(): Ambience being changed to {:g} (into {:g}).".format(setting, setting / 10), level=kDebugDumpLevel) audio.setAmbienceVolume(setting / 10) elif plID == kGUI.BKIMicLevelSlider: setting = control.getValue() PtDebugPrint(u"xKI.ProcessNotifyVolumeExpanded(): MicLevel being changed to {:g} (into {:g}).".format(setting, setting / 10), level=kDebugDumpLevel) audio.setMicLevel(setting / 10) elif plID == kGUI.BKIGUIVolSlider: setting = control.getValue() PtDebugPrint(u"xKI.ProcessNotifyVolumeExpanded(): MicLevel being changed to {:g} (into {:g}).".format(setting, setting / 10), level=kDebugDumpLevel) audio.setGUIVolume(setting / 10) ## Process notifications originating from an expanded Age Owner mode in the BigKI. # Processes owned Ages (currently only applies to Neighborhoods). Note that # the public/private feature is currently available only through the Nexus. # This mostly handles description modifications for now. def ProcessNotifyAgeOwnerExpanded(self, control, event): if event == kShowHide: if control.isEnabled(): tField = ptGUIControlTextBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerDescriptionTitle)) tField.setStringW(PtGetLocalizedString("KI.Config.Description")) titleEdit = ptGUIControlEditBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleEditbox)) titleEdit.hide() self.RefreshAgeOwnerSettings() elif event == kAction or event == kValueChanged: plID = control.getTagID() if plID == kGUI.BKAgeOwnerMakePublicBtn: # This feature is not currently available in the BigKI. try: vault = ptVault() myAge = self.BKConfigFolderDict[self.BKConfigListOrder[self.BKFolderSelected]] myAgeStruct = myAge.asAgeInfoStruct() makePublic = 1 if myAge.isPublic(): makePublic = 0 PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Making {} private.".format(myAge.getDisplayName()), level=kDebugDumpLevel) else: PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Making {} public.".format(myAge.getDisplayName()), level=kDebugDumpLevel) vault.setAgePublic(myAgeStruct, makePublic) # Let the refresh re-enable the public button. control.disable() except AttributeError: PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Couldn't toggle public/private.", level=kErrorLevel) elif plID == kGUI.BKAgeOwnerTitleBtn: PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Change title button hit.", level=kDebugDumpLevel) control.disable() title = ptGUIControlTextBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleTB)) title.hide() titleEdit = ptGUIControlEditBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleEditbox)) try: # Get the selected Age config setting. myAge = self.BKConfigFolderDict[self.BKConfigListOrder[self.BKFolderSelected]] titleEdit.setString(myAge.getAgeUserDefinedName()) except LookupError: titleEdit.setString("") titleEdit.show() titleEdit.end() KIAgeOwnerExpanded.dialog.setFocus(titleEdit.getKey()) elif plID == kGUI.BKAgeOwnerTitleEditbox: PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): edit field set.", level=kDebugDumpLevel) self.SaveAgeNameFromEdit(control) elif event == kFocusChange: PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Focus change.", level=kDebugDumpLevel) titleEdit = ptGUIControlEditBox(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerTitleEditbox)) if titleEdit.isVisible(): if control is None or (control.getTagID() != kGUI.BKAgeOwnerTitleEditbox and control.getTagID() != kGUI.BKAgeOwnerTitleBtn): self.SaveAgeNameFromEdit(titleEdit) if control is not None: # Check if the decription was updated. plID = control.getTagID() if plID == kGUI.BKAgeOwnerDescription: self.BKAgeOwnerEditDescription = True PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Start editing description.", level=kDebugDumpLevel) else: if self.BKAgeOwnerEditDescription: descript = ptGUIControlMultiLineEdit(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerDescription)) myAge = self.BKConfigFolderDict[self.BKConfigListOrder[self.BKFolderSelected]] if myAge is not None: PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Age description updated for {}.".format(myAge.getDisplayName()), level=kDebugDumpLevel) myAge.setAgeDescription(descript.getString()) myAge.save() else: PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Neighborhood is None while trying to update description.", level=kDebugDumpLevel) self.BKAgeOwnerEditDescription = False else: if self.BKAgeOwnerEditDescription: descript = ptGUIControlMultiLineEdit(KIAgeOwnerExpanded.dialog.getControlFromTag(kGUI.BKAgeOwnerDescription)) myAge = self.BKConfigFolderDict[self.BKConfigListOrder[self.BKFolderSelected]] if myAge is not None: PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Age description updated for {}.".format(myAge.getDisplayName()), level=kDebugDumpLevel) buff = descript.getEncodedBuffer() myAge.setAgeDescription(str(buff)) myAge.save() else: PtDebugPrint(u"xKI.ProcessNotifyAgeOwnerExpanded(): Neighborhood is None while trying to update description.", level=kDebugDumpLevel) self.BKAgeOwnerEditDescription = False ## Process notifications originating from a YesNo dialog. # Yes/No dialogs are omnipresent throughout Uru. Those processed here are: # - Quitting dialog (quit/logout/cancel). # - Deleting dialog (yes/no); various such dialogs. # - Link offer dialog (yes/no). # - Outside sender dialog (?). # - KI Full dialog (OK); just a notification. def ProcessNotifyYesNo(self, control, event): if event == kAction or event == kValueChanged: ynID = control.getTagID() if self.YNWhatReason == kGUI.YNQuit: if ynID == kGUI.YesButtonID: PtConsole("App.Quit") elif ynID == kGUI.NoButtonID: KIYesNo.dialog.hide() logoutText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutTextID)) logoutText.hide() logoutButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutButtonID)) logoutButton.hide() elif ynID == kGUI.YesNoLogoutButtonID: KIYesNo.dialog.hide() logoutText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutTextID)) logoutText.hide() logoutButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesNoLogoutButtonID)) logoutButton.hide() # Clear out all chat on microKI. chatArea = ptGUIControlMultiLineEdit(KIMicro.dialog.getControlFromTag(kGUI.ChatDisplayArea)) chatArea.setString("") chatArea.moveCursor(PtGUIMultiLineDirection.kBufferStart) KIMicro.dialog.refreshAllControls() # Clear out all chat on miniKI. chatArea = ptGUIControlMultiLineEdit(KIMini.dialog.getControlFromTag(kGUI.ChatDisplayArea)) chatArea.setString("") chatArea.moveCursor(PtGUIMultiLineDirection.kBufferStart) KIMini.dialog.refreshAllControls() linkmgr = ptNetLinkingMgr() ageLink = ptAgeLinkStruct() ageInfo = ptAgeInfoStruct() ageInfo.setAgeFilename("StartUp") spawnPoint = ptSpawnPointInfo() spawnPoint.setName("LinkInPointDefault") ageLink.setAgeInfo(ageInfo) ageLink.setSpawnPoint(spawnPoint) ageLink.setLinkingRules(PtLinkingRules.kBasicLink) linkmgr.linkToAge(ageLink) elif self.YNWhatReason == kGUI.YNDelete: if ynID == kGUI.YesButtonID: # Remove the current element if self.BKCurrentContent is not None: delFolder = self.BKCurrentContent.getParent() delElem = self.BKCurrentContent.getChild() if delFolder is not None and delElem is not None: # Are we removing a visitor from an Age we own? tFolder = delFolder.upcastToFolderNode() if tFolder is not None and tFolder.folderGetType() == PtVaultStandardNodes.kCanVisitFolder: PtDebugPrint(u"xKI.ProcessNotifyYesNo(): Revoking visitor.", level=kDebugDumpLevel) delElem = delElem.upcastToPlayerInfoNode() # Need to refind the folder that has the ageInfo in it. ageFolderName = self.BKFolderListOrder[self.BKFolderSelected] ageFolder = self.BKFolderLineDict[ageFolderName] # Revoke invite. ptVault().unInvitePlayerToAge(ageFolder.getAgeInstanceGuid(), delElem.playerGetID()) # Are we removing a player from a player list? elif delFolder.getType() == PtVaultNodeTypes.kPlayerInfoListNode and delElem.getType() == PtVaultNodeTypes.kPlayerInfoNode: PtDebugPrint(u"xKI.ProcessNotifyYesNo(): Removing player from folder.", level=kDebugDumpLevel) delFolder = delFolder.upcastToPlayerInfoListNode() delElem = delElem.upcastToPlayerInfoNode() delFolder.playerlistRemovePlayer(delElem.playerGetID()) self.BKPlayerSelected = None sendToField = ptGUIControlTextBox(BigKI.dialog.getControlFromTag(kGUI.BKIPlayerLine)) sendToField.setString(" ") # Are we removing a journal entry? else: # See if this is a Marker Game folder that is being deleted. if delElem.getType() == PtVaultNodeTypes.kMarkerGameNode: if self.markerGameManager.IsActive(delElem): self.markerGameManager.StopGame() self.BKCurrentContent = None delFolder.removeNode(delElem) PtDebugPrint(u"xKI.ProcessNotifyYesNo(): Deleting element from folder.", level=kDebugDumpLevel) else: PtDebugPrint(u"xKI.ProcessNotifyYesNo(): Tried to delete bad Vault node or delete from bad folder.", level=kErrorLevel) self.ChangeBigKIMode(kGUI.BKListMode) self.RefreshPlayerList() self.YNWhatReason = kGUI.YNQuit KIYesNo.dialog.hide() elif self.YNWhatReason == kGUI.YNOfferLink: self.YNWhatReason = kGUI.YNQuit KIYesNo.dialog.hide() if ynID == kGUI.YesButtonID: if self.offerLinkFromWho is not None: PtDebugPrint(u"xKI.ProcessNotifyYesNo(): Linking to offered age {}.".format(self.offerLinkFromWho.getDisplayName()), level=kDebugDumpLevel) link = ptAgeLinkStruct() link.setLinkingRules(PtLinkingRules.kBasicLink) link.setAgeInfo(self.offerLinkFromWho) ptNetLinkingMgr().linkToAge(link) self.offerLinkFromWho = None self.offerLinkFromWho = None elif self.YNWhatReason == kGUI.YNOutside: self.YNWhatReason = kGUI.YNQuit KIYesNo.dialog.hide() if self.YNOutsideSender is not None: note = ptNotify(self.key) note.clearReceivers() note.addReceiver(self.YNOutsideSender) note.netPropagate(0) note.netForce(0) # Is it a good return? if ynID == kGUI.YesButtonID: note.setActivate(1) note.addVarNumber("YesNo", 1) # Or a bad return? elif ynID == kGUI.NoButtonID: note.setActivate(0) note.addVarNumber("YesNo", 0) note.send() self.YNOutsideSender = None elif self.YNWhatReason == kGUI.YNKIFull: KIYesNo.dialog.hide() yesButton = ptGUIControlButton(KIYesNo.dialog.getControlFromTag(kGUI.YesButtonID)) yesButton.show() yesBtnText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesButtonTextID)) yesBtnText.show() noBtnText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.NoButtonTextID)) noBtnText.setStringW(PtGetLocalizedString("KI.YesNoDialog.NOButton")) self.YNWhatReason = kGUI.YNQuit else: self.YNWhatReason = kGUI.YNQuit KIYesNo.dialog.hide() self.YNOutsideSender = None elif event == kExitMode: self.YNWhatReason = kGUI.YNQuit KIYesNo.dialog.hide() self.YNOutsideSender = None ## Process notifications originating from a new item alert dialog. # Such alerts make either the KI's icon or the Yeesha Book icon # flash for a while. def ProcessNotifyNewItemAlert(self, control, event): if event == kDialogLoaded: kiAlert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertKIAlert)) kiAlert.disable() kiAlert.hide() bookalert = ptGUIControlButton(NewItemAlert.dialog.getControlFromTag(kAlertBookAlert)) bookalert.disable() bookalert.hide() elif event == kShowHide: if control.isEnabled(): self.AlertStartTimer() ## Process notifications originating from the Marker Game creation GUI. # This gets the values submitted by the player and passes them to the # Marker Game manager. def ProcessNotifyCreateMarkerGameGUI(self, control, event): if control: tagID = control.getTagID() if event == kDialogLoaded: self.markerGameDefaultColor = ptGUIControlTextBox(KICreateMarkerGameGUI.dialog.getControlFromTag(kGUI.MarkerGameLabel1)).getForeColor() self.markerGameSelectedColor = ptGUIControlTextBox(KICreateMarkerGameGUI.dialog.getControlFromTag(kGUI.MarkerGameLabel1)).getSelectColor() elif event == kShowHide: self.InitMarkerGameGUI() PtDebugPrint(u"xKI.ProcessNotifyCreateMarkerGameGUI(): Marker Game dialog is showing or hiding.", level=kDebugDumpLevel) elif event == kAction or event == kValueChanged: if tagID == kGUI.MarkerGameType1 or tagID == kGUI.MarkerGameType2 or tagID == kGUI.MarkerGameType3: self.SelectMarkerType(tagID) elif tagID == kGUI.CreateMarkerGameCancelBT: KIMarkerGameGUIClose.run(self.key, netPropagate=0) elif kGUI.CreateMarkerGameSubmitBT: markerGameNameText = ptGUIControlEditBox(KICreateMarkerGameGUI.dialog.getControlFromTag(kGUI.CreateMarkerGameNameEB)).getStringW() try: markerGameType = kGUI.MarkerGameStates[self.selectedMGType] except: markerGameType = 0 PtDebugPrint(u"xKI.ProcessNotifyCreateMarkerGameGUI(): Couldn't find marker game type, so setting it to Quest Mode.", level=kWarningLevel) self.FinishCreateMarkerGame(markerGameNameText) KIMarkerGameGUIClose.run(self.key, netPropagate=0) ## Processes notifications originating from an expanded Marker Game mode in the BigKI. # This handles the edit buttons, marker saving buttons, deletion buttons, # etc.. def ProcessNotifyMarkerFolderExpanded(self, control, event): mgr = self.markerGameManager if event == kDialogLoaded: typeField = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderGameTimeTB)) typeField.setString(kLoc.MarkerFolderPopupMenu[self.markerGameTimeID][0]) elif event == kShowHide: # Reset the edit text lines. if control.isEnabled(): titleEdit = ptGUIControlEditBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderTitleEB)) titleEdit.hide() markerEdit = ptGUIControlEditBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderMarkerTextEB)) markerEdit.hide() self.BigKIDisplayMarkerGame() elif event == kAction or event == kValueChanged: mFldrID = control.getTagID() if mFldrID == kGUI.MarkerFolderEditStartGame: mgr.LoadGame(self.BKCurrentContent) # Is it the "Edit" button? if self.MFdialogMode == kGames.MFOverview: mgr.BeginEditingMarkers() self.SetWorkingToCurrentMarkerGame() # Is it the "Done Editing" button? elif self.MFdialogMode == kGames.MFEditing: mgr.FinishEditingMarkers() self.ResetWorkingMarkerGame() # Is it the "Stop Game" button? elif self.MFdialogMode == kGames.MFPlaying: mgr.StopGame(reset=False) # Is it the "Save Marker" button? elif self.MFdialogMode == kGames.MFEditingMarker: # Should already be saved, just clear selection for now. mgr.selected_marker_id = -1 self.BigKICheckContentRefresh(self.BKCurrentContent) elif mFldrID == kGUI.MarkerFolderPlayEndGame: mgr.LoadGame(self.BKCurrentContent) # Is it the "Play Game" button? if self.MFdialogMode == kGames.MFOverview: mgr.Play() # Is it the "Add Marker" button? elif self.MFdialogMode == kGames.MFEditing: self.CreateAMarker() # Is it the "Reset Game" button? elif self.MFdialogMode == kGames.MFPlaying: mgr.StopGame(reset=True) # Is it the "Remove Marker" button? elif self.MFdialogMode == kGames.MFEditingMarker: mgr.DeleteMarker(mgr.selected_marker_id) self.BigKICheckContentRefresh(self.BKCurrentContent) elif mFldrID == kGUI.MarkerFolderMarkListbox: mgr.LoadGame(self.BKCurrentContent) if not mgr.playing: # NOTE: We must use selected_marker_index because marker IDs don't necessarily # match up with the indices used in the GUI mgr.selected_marker_index = control.getSelection() self.BigKICheckContentRefresh(self.BKCurrentContent) elif mFldrID == kGUI.MarkerFolderTitleBtn: control.disable() title = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderTitleText)) titleEdit = ptGUIControlEditBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderTitleEB)) titleEdit.setStringW(title.getStringW()) title.hide() titleEdit.show() titleEdit.end() KIMarkerFolderExpanded.dialog.setFocus(titleEdit.getKey()) elif mFldrID == kGUI.MarkerFolderTitleEB: self.SaveMarkerGameNameFromEdit(control) self.BigKICheckContentRefresh(self.BKCurrentContent) elif mFldrID == kGUI.MarkerFolderMarkerTextBtn: control.disable() title = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderMarkerTextTB)) titleEdit = ptGUIControlEditBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderMarkerTextEB)) titleEdit.setStringW(title.getStringW()) title.hide() titleEdit.show() titleEdit.end() KIMarkerFolderExpanded.dialog.setFocus(titleEdit.getKey()) elif mFldrID == kGUI.MarkerFolderMarkerTextEB: self.SaveMarkerTextFromEdit(control) self.BigKICheckContentRefresh(self.BKCurrentContent) elif mFldrID == kGUI.MarkerFolderTimePullDownBtn or mFldrID == kGUI.MarkerFolderTimeArrow: KIMarkerFolderPopupMenu.menu.show() elif mFldrID == kGUI.MarkerFolderDeleteBtn: self.YNWhatReason = kGUI.YNDelete elem = self.BKCurrentContent.getChild() elem = elem.upcastToMarkerGameNode() if elem is not None: mfTitle = elem.getGameName() else: mfTitle = "<unknown>" yesText = ptGUIControlTextBox(KIYesNo.dialog.getControlFromTag(kGUI.YesNoTextID)) yesText.setStringW(PtGetLocalizedString("KI.Messages.DeletePicture", [xCensor.xCensor(mfTitle, self.censorLevel)])) self.LocalizeDialog(1) KIYesNo.dialog.show() elif event == kFocusChange: titleEdit = ptGUIControlEditBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderTitleEB)) # Is the editbox enabled and something other than the button is getting the focus? if titleEdit.isVisible(): if control is None or (control.getTagID() != kGUI.MarkerFolderTitleEB and control.getTagID() != kGUI.MarkerFolderTitleBtn): self.SaveMarkerGameNameFromEdit(titleEdit) if self.MFdialogMode == kGames.MFEditingMarker: titleEdit = ptGUIControlEditBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderMarkerTextEB)) # Is the editbox enabled and something other than the button is getting the focus? if titleEdit.isVisible(): if control is None or (control.getTagID() != kGUI.MarkerFolderMarkerTextEB and control.getTagID() != kGUI.MarkerFolderMarkerTextBtn): self.SaveMarkerTextFromEdit(titleEdit) self.BigKICheckContentRefresh(self.BKCurrentContent) ## Processes notifications originating from the Marker Game popup menu. # (What is this? Is it used?) def ProcessNotifyMarkerFolderPopupMenu(self, control, event): if event == kDialogLoaded: for menuItem in kLoc.MarkerFolderPopupMenu: KIMarkerFolderPopupMenu.menu.addNotifyItem(menuItem[0]) elif event == kAction: menuID = control.getTagID() self.markerGameTimeID = menuID typeField = ptGUIControlTextBox(KIMarkerFolderExpanded.dialog.getControlFromTag(kGUI.MarkerFolderGameTimeTB)) typeField.setString(kLoc.MarkerFolderPopupMenu[self.markerGameTimeID][0]) # Save the current Marker Game to this type of game. if self.BKCurrentContent is not None: element = self.BKCurrentContent.getChild() if element is not None: datatype = element.getType() if datatype == PtVaultNodeTypes.kMarkerGameNode: element = element.upcastToMarkerGameNode() if element: element.setRoundLength(kLoc.MarkerFolderPopupMenu[self.markerGameTimeID][1]) element.save() elif event == kExitMode: if KIMarkerFolderPopupMenu.menu.isEnabled(): KIMarkerFolderPopupMenu.menu.hide() ## Processes notifications originating from the Jalak GUI. # These controls are only used within the Age of Jalak, obviously. def ProcessNotifyJalakGUI(self, control, event): if event == kDialogLoaded: self.JalakGUIInit() elif event == kAction or event == kValueChanged: if control is not None: tagID = control.getTagID() btn = str(tagID) if btn in JalakBtnStates: KIJalakBtnLights.run(self.key, state=btn, netPropagate=0) self.SetJalakGUIButtons(0) #~~~~~~~~~~~~~~~~~~~# # Vault Type Events # #~~~~~~~~~~~~~~~~~~~# ## Handles the passed vault type event. # This is used to react to saved nodes, new nodes, etc. def HandleVaultTypeEvents(self, event, tupData): # Make sure that the BigKI dialog is loaded before trying to update it. if not PtIsDialogLoaded("KIMain"): PtDebugPrint(u"xKI.HandleVaultTypeEvents(): BigKI dialog was not loaded, waiting.", level=kDebugDumpLevel) return if event == PtVaultCallbackTypes.kVaultConnected: PtDebugPrint(u"xKI.HandleVaultTypeEvents(): Connected to the Vault.", level=kDebugDumpLevel) elif event == PtVaultCallbackTypes.kVaultDisconnected: PtDebugPrint(u"xKI.HandleVaultTypeEvents(): Disconnected from the Vault.", level=kDebugDumpLevel) elif event == PtVaultCallbackTypes.kVaultNodeSaved: PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A node is being saved (ID = {}, type = {}).".format(tupData[0].getID(), tupData[0].getType()), level=kDebugDumpLevel) if tupData[0].getType() == PtVaultNodeTypes.kPlayerInfoNode: self.RefreshPlayerList() elif tupData[0].getType() == PtVaultNodeTypes.kAgeInfoNode: self.BigKISetStatics() self.BigKIRefreshFolderList() self.BigKIOnlySelectedToButtons() self.RefreshAgeOwnerSettings() self.BigKIRefreshContentList() self.BigKIRefreshContentListDisplay() elif event == PtVaultCallbackTypes.kVaultNodeInitialized: PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A node has been initalized (ID = {}, type = {}).".format(tupData[0].getID(), tupData[0].getType()), level=kDebugDumpLevel) if self.KILevel > kMicroKI: self.BigKICheckElementRefresh(tupData[0]) elif event == PtVaultCallbackTypes.kVaultNodeAdded: PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A node has been added.", level=kDebugDumpLevel) elif event == PtVaultCallbackTypes.kVaultNodeRefAdded: PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A node reference has been added (childID = {}, parentID = {}).".format(tupData[0].getChildID(), tupData[0].getParentID()), level=kDebugDumpLevel) if self.KILevel > kMicroKI: folder = tupData[0].getParent() folder = folder.upcastToFolderNode() # If the parent of this ref is the Inbox, then it's incoming mail. if folder is not None and folder.folderGetType() == PtVaultStandardNodes.kInboxFolder: self.AlertKIStart() # Note: beenSeen() is not yet implemented. if not tupData[0].beenSeen(): if self.onlyGetPMsFromBuddies: vault = ptVault() buddies = vault.getBuddyListFolder() if buddies.playerlistHasPlayer(tupData[0].getSaverID()): # then show alert self.AlertKIStart() else: self.AlertKIStart() child = tupData[0].getChild() child = child.upcastToFolderNode() if child is not None: PtDebugPrint(u"xKI.HandleVaultTypeEvents(): Adding a folder, refresh folder list.", level=kDebugDumpLevel) self.BigKIRefreshFolderList() self.BigKICheckFolderRefresh(folder) elif event == PtVaultCallbackTypes.kVaultRemovingNodeRef: PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A node reference is being removed (childID = {}, parentID = {}).".format(tupData[0].getChildID(), tupData[0].getParentID()), level=kDebugDumpLevel) elif event == PtVaultCallbackTypes.kVaultNodeRefRemoved: PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A node reference has been removed (childID, parentID): ", tupData, level=kDebugDumpLevel) if self.KILevel > kMicroKI: if self.BKRightSideMode == kGUI.BKMarkerListExpanded: self.BigKIDisplayMarkerGame() self.BigKICheckFolderRefresh() elif event == PtVaultCallbackTypes.kVaultOperationFailed: PtDebugPrint(u"xKI.HandleVaultTypeEvents(): A Vault operation failed (operation, resultCode): ", tupData, level=kDebugDumpLevel) else: PtDebugPrint(u"xKI.HandleVaultTypeEvents(): Unknown Vault event: {}.".format(event), level=kWarningLevel)
unknown
codeparrot/codeparrot-clean
import numpy as np from metaworld.policies.action import Action from metaworld.policies.policy import Policy, assert_fully_parsed, move class SawyerDrawerOpenV1Policy(Policy): @staticmethod @assert_fully_parsed def _parse_obs(obs): return { 'hand_pos': obs[:3], 'drwr_pos': obs[3:6], 'unused_info': obs[6:], } def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({ 'delta_pos': np.arange(3), 'grab_effort': 3 }) # NOTE this policy looks different from the others because it must # modify its p constant part-way through the task pos_curr = o_d['hand_pos'] pos_drwr = o_d['drwr_pos'] # align end effector's Z axis with drawer handle's Z axis if np.linalg.norm(pos_curr[:2] - pos_drwr[:2]) > 0.06: to_pos = pos_drwr + np.array([0., 0., 0.3]) action['delta_pos'] = move(o_d['hand_pos'], to_pos, p=4.) # drop down to touch drawer handle elif abs(pos_curr[2] - pos_drwr[2]) > 0.04: to_pos = pos_drwr action['delta_pos'] = move(o_d['hand_pos'], to_pos, p=4.) # push toward a point just behind the drawer handle # also increase p value to apply more force else: to_pos = pos_drwr + np.array([0., -0.06, 0.]) action['delta_pos'] = move(o_d['hand_pos'], to_pos, p=50.) # keep gripper open action['grab_effort'] = -1. return action.array
unknown
codeparrot/codeparrot-clean
//// [tests/cases/compiler/augmentExportEquals3_1.ts] //// //// [file1.d.ts] declare module "file1" { function foo(): void; namespace foo { export var v: number; } export = foo; } //// [file2.ts] /// <reference path="file1.d.ts"/> import x = require("file1"); x.b = 1; // OK - './file1' is a namespace declare module "file1" { interface A { a } let b: number; } //// [file3.ts] import * as x from "file1"; import "file2"; let a: x.A; let b = x.b; //// [file2.js] define(["require", "exports", "file1"], function (require, exports, x) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); x.b = 1; }); //// [file3.js] var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); define(["require", "exports", "file1", "file2"], function (require, exports, x) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); x = __importStar(x); let a; let b = x.b; });
javascript
github
https://github.com/microsoft/TypeScript
tests/baselines/reference/augmentExportEquals3_1.js
@file:Suppress("PackageDirectoryMismatch") package definitely.not.kotlinx.coroutines import kotlinx.coroutines.testing.* import kotlinx.coroutines.* import kotlinx.coroutines.debug.* import kotlinx.coroutines.selects.* import org.junit.* import org.junit.Test import java.util.concurrent.* import kotlin.test.* class SanitizedProbesTest : DebugTestBase() { @Before override fun setUp() { super.setUp() DebugProbes.sanitizeStackTraces = true DebugProbes.enableCreationStackTraces = true } @Test fun testRecoveredStackTrace() = runTest { val deferred = createDeferred() val traces = listOf( "java.util.concurrent.ExecutionException\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest\$createDeferredNested\$1.invokeSuspend(SanitizedProbesTest.kt:97)\n" + "\tat _COROUTINE._BOUNDARY._(CoroutineDebugging.kt)\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest.oneMoreNestedMethod(SanitizedProbesTest.kt:67)\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest.nestedMethod(SanitizedProbesTest.kt:61)\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest\$testRecoveredStackTrace\$1.invokeSuspend(SanitizedProbesTest.kt:50)\n" + "\tat _COROUTINE._CREATION._(CoroutineDebugging.kt)\n" + "\tat kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsJvmKt.createCoroutineUnintercepted(IntrinsicsJvm.kt:116)\n" + "\tat kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:23)\n" + "\tat kotlinx.coroutines.testing.TestBase.runTest\$default(TestBase.kt:141)\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest.testRecoveredStackTrace(SanitizedProbesTest.kt:33)", "Caused by: java.util.concurrent.ExecutionException\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest\$createDeferredNested\$1.invokeSuspend(SanitizedProbesTest.kt:57)\n" + "\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)\n" ) nestedMethod(deferred, traces) deferred.join() } @Test fun testCoroutinesDump() = runTest { val deferred = createActiveDeferred() yield() verifyDump( "Coroutine \"coroutine#3\":BlockingCoroutine{Active}@7d68ef40, state: RUNNING\n" + "\tat java.lang.Thread.getStackTrace(Thread.java)\n" + "\tat _COROUTINE._CREATION._(CoroutineDebugging.kt)\n" + "\tat kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsJvmKt.createCoroutineUnintercepted(IntrinsicsJvm.kt:116)\n" + "\tat kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:23)\n" + "\tat kotlinx.coroutines.testing.TestBase.runTest\$default(TestBase.kt:141)\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest.testCoroutinesDump(SanitizedProbesTest.kt:56)", "Coroutine \"coroutine#4\":DeferredCoroutine{Active}@75c072cb, state: SUSPENDED\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest\$createActiveDeferred\$1.invokeSuspend(SanitizedProbesTest.kt:63)\n" + "\tat _COROUTINE._CREATION._(CoroutineDebugging.kt)\n" + "\tat kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsJvmKt.createCoroutineUnintercepted(IntrinsicsJvm.kt:116)\n" + "\tat kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:23)\n" + "\tat kotlinx.coroutines.BuildersKt__Builders_commonKt.async\$default(Builders.common.kt)\n" + "\tat kotlinx.coroutines.BuildersKt.async\$default(Unknown Source)\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest.createActiveDeferred(SanitizedProbesTest.kt:62)\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest.access\$createActiveDeferred(SanitizedProbesTest.kt:16)\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest\$testCoroutinesDump\$1.invokeSuspend(SanitizedProbesTest.kt:57)\n" + "\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)\n" + "\tat kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:237)\n" + "\tat kotlinx.coroutines.testing.TestBase.runTest\$default(TestBase.kt:141)\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest.testCoroutinesDump(SanitizedProbesTest.kt:56)" ) deferred.cancelAndJoin() } @Test fun testSelectBuilder() = runTest { val selector = launchSelector() expect(1) yield() expect(3) verifyDump("Coroutine \"coroutine#1\":BlockingCoroutine{Active}@35fc6dc4, state: RUNNING\n" + "\tat java.lang.Thread.getStackTrace(Thread.java:1552)\n" + // Skip the rest "\tat _COROUTINE._CREATION._(CoroutineDebugging.kt)\n" + "\tat kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsJvmKt.createCoroutineUnintercepted(IntrinsicsJvm.kt:116)", "Coroutine \"coroutine#2\":StandaloneCoroutine{Active}@1b68b9a4, state: SUSPENDED\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest\$launchSelector\$1\$1\$1.invokeSuspend(SanitizedProbesTest.kt)\n" + "\tat _COROUTINE._CREATION._(CoroutineDebugging.kt)\n" + "\tat kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsJvmKt.createCoroutineUnintercepted(IntrinsicsJvm.kt:116)\n" + "\tat kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:25)\n" + "\tat kotlinx.coroutines.BuildersKt__Builders_commonKt.launch\$default(Builders.common.kt)\n" + "\tat kotlinx.coroutines.BuildersKt.launch\$default(Unknown Source)\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest.launchSelector(SanitizedProbesTest.kt:100)\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest.access\$launchSelector(SanitizedProbesTest.kt:16)\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest\$testSelectBuilder\$1.invokeSuspend(SanitizedProbesTest.kt:89)\n" + "\tat kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:32)\n" + "\tat kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:233)\n" + "\tat kotlinx.coroutines.testing.TestBase.runTest\$default(TestBase.kt:154)\n" + "\tat definitely.not.kotlinx.coroutines.SanitizedProbesTest.testSelectBuilder(SanitizedProbesTest.kt:88)") finish(4) selector.cancelAndJoin() } private fun CoroutineScope.launchSelector(): Job { val job = CompletableDeferred(Unit) return launch { select<Int> { job.onJoin { expect(2) delay(Long.MAX_VALUE) 1 } } } } private fun CoroutineScope.createActiveDeferred(): Deferred<*> = async { suspendingMethod() assertTrue(true) } private suspend fun suspendingMethod() { delay(Long.MAX_VALUE) } private fun CoroutineScope.createDeferred(): Deferred<*> = createDeferredNested() private fun CoroutineScope.createDeferredNested(): Deferred<*> = async(NonCancellable) { throw ExecutionException(null) } private suspend fun nestedMethod(deferred: Deferred<*>, traces: List<String>) { oneMoreNestedMethod(deferred, traces) assertTrue(true) // Prevent tail-call optimization } private suspend fun oneMoreNestedMethod(deferred: Deferred<*>, traces: List<String>) { try { deferred.await() expectUnreached() } catch (e: ExecutionException) { verifyStackTrace(e, traces) } } }
kotlin
github
https://github.com/Kotlin/kotlinx.coroutines
kotlinx-coroutines-debug/test/SanitizedProbesTest.kt
/* Copyright 2014 The Kubernetes Authors. 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. */ package main import ( "bytes" "fmt" "io" "os" "github.com/spf13/cobra/doc" "k8s.io/cli-runtime/pkg/genericiooptions" "k8s.io/kubectl/pkg/cmd" "k8s.io/kubernetes/cmd/genutils" ) func main() { // use os.Args instead of "flags" because "flags" will mess up the man pages! path := "docs/" if len(os.Args) == 2 { path = os.Args[1] } else if len(os.Args) > 2 { fmt.Fprintf(os.Stderr, "usage: %s [output directory]\n", os.Args[0]) os.Exit(1) } outDir, err := genutils.OutDir(path) if err != nil { fmt.Fprintf(os.Stderr, "failed to get output directory: %v\n", err) os.Exit(1) } // Set environment variables used by kubectl so the output is consistent, // regardless of where we run. os.Setenv("HOME", "/home/username") kubectl := cmd.NewKubectlCommand(cmd.KubectlOptions{IOStreams: genericiooptions.IOStreams{In: bytes.NewReader(nil), Out: io.Discard, ErrOut: io.Discard}}) doc.GenMarkdownTree(kubectl, outDir) }
go
github
https://github.com/kubernetes/kubernetes
cmd/gendocs/gen_kubectl_docs.go
#!/usr/bin/env python ############################################################################ # # Copyright 2016 Samsung Electronics All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific # language governing permissions and limitations under the License. # ############################################################################ ############################################################################ # tools/discover.py # # Copyright (C) 2012 Max Holtzberg. All rights reserved. # Author: Max Holtzberg <mh@uvc.de> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. # 3. Neither the name NuttX nor the names of its contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ############################################################################ from __future__ import print_function import array from socket import * PORT = 96 DISCOVER_PROTO_ID = 0x99 DISCOVER_ALL = 0xff # 0xff means all devices DISCOVER_REQUEST = 0x01 DISCOVER_RESPONSE = 0x02 DISCOVER_REQUEST_SIZE = 4 DISCOVER_RESPONSE_SIZE = 35 def check_sum(data): chksum = 0 for c in data[:-1]: chksum -= c return (chksum & 0xff) == data[-1] def send_discover(socket): cmd = array.array('B', [0] * DISCOVER_REQUEST_SIZE) cmd[0] = DISCOVER_PROTO_ID # Tag for identification of the protocol cmd[1] = DISCOVER_REQUEST # Request command cmd[2] = DISCOVER_ALL chksum = 0 for c in cmd[:3]: chksum -= c; cmd[3] = chksum & 0xff socket.sendto(cmd, ('<broadcast>', PORT)) def read_responses(socket): res = [] response = array.array('B', [0] * DISCOVER_RESPONSE_SIZE) try: while 1: size, src = socket.recvfrom_into(response) if (size == DISCOVER_RESPONSE_SIZE and response[0] == DISCOVER_PROTO_ID and response[1] == DISCOVER_RESPONSE and check_sum(response)): dev = {} dev['addr'] = src[0] dev['descr'] = response[2:-1].tostring().rstrip('\0') res.append(dev) except timeout: return res if __name__ == '__main__': print('Sending discover...') s = socket(AF_INET, SOCK_DGRAM) s.bind(('0.0.0.0', PORT)) s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) s.settimeout(1.0) send_discover(s) devices = read_responses(s) socket.close(s) print(devices)
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env bash # Copyright (c) HashiCorp, Inc. # SPDX-License-Identifier: BUSL-1.1 set -euo pipefail # Check goimports echo "==> Checking the code complies with goimports requirements..." # We only require goimports to have been run on files that were changed # relative to the main branch, so that we can gradually create more consistency # rather than bulk-changing everything at once. declare -a target_files # "readarray" will return an "unbound variable" error if there isn't already # at least one element in the target array. "readarray" will overwrite this # item, though. target_files[0]="" base_branch="origin/main" # HACK: If we seem to be running inside a GitHub Actions pull request check # then we'll use the PR's target branch from this variable instead. if [[ -n "${GITHUB_BASE_REF:-}" ]]; then base_branch="origin/$GITHUB_BASE_REF" fi # FIXME: "readarray' is a Bash 4 feature, which means that currently this script # can't work on macOS which (at the time of writing this) ships with only Bash 3. # We can probably replace this with something more clunky using an overridden # "IFS" environment variable, but the primary place we want to run this right # now is in our "quick checks" workflow and that _does_ have a reasonably # modern version of Bash. readarray -t target_files < <(git diff --name-only ${base_branch} --diff-filter=MA | grep "\.go" | grep -v ".pb.go" | grep -v ".go-version") # NOTE: The above intentionally excludes .pb.go files because those are # generated by a tool (protoc-gen-go) which itself doesn't produce # style-compliant imports. if [[ "${#target_files[@]}" -eq 0 ]]; then echo "No files have changed relative to branch ${base_branch}, so there's nothing to check!" exit 0 fi declare -a incorrect_files # Array must have at least one item before we can append to it. Code below must # work around this extra empty-string element at the beginning of the array. incorrect_files[0]="" for filename in "${target_files[@]}"; do if [[ -z "$filename" ]]; then continue fi output=$(go tool golang.org/x/tools/cmd/goimports -l "${filename}") if [[ $? -ne 0 ]]; then echo >&2 goimports failed for "$filename" exit 1 fi if [[ -n "$output" ]]; then incorrect_files+=("$filename") fi done if [[ "${#incorrect_files[@]}" -gt 1 ]]; then echo >&2 'The following files have import statements that disagree with "goimports"': for filename in "${incorrect_files[@]}"; do if [[ -z "$filename" ]]; then continue fi echo >&2 ' - ' "${filename}" done echo >&2 'Use `go tool golang.org/x/tools/cmd/goimports -w -l` on each of these files to update these files.' exit 1 fi echo 'All of the changed files look good!' exit 0
unknown
github
https://github.com/hashicorp/terraform
scripts/goimportscheck.sh
# -*- coding: utf-8 -*- """ Tests for Shibboleth Authentication @jbau """ import unittest from mock import patch from ddt import ddt, data from django.conf import settings from django.http import HttpResponseRedirect from django.test import TestCase from django.test.client import RequestFactory, Client as DjangoTestClient from django.test.utils import override_settings from django.core.urlresolvers import reverse from django.contrib.auth.models import AnonymousUser, User from django.utils.importlib import import_module from xmodule.modulestore.tests.factories import CourseFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase, mixed_store_config from xmodule.modulestore.django import modulestore from xmodule.modulestore import ModuleStoreEnum from opaque_keys.edx.locations import SlashSeparatedCourseKey from external_auth.models import ExternalAuthMap from external_auth.views import shib_login, course_specific_login, course_specific_register, _flatten_to_ascii from student.views import create_account, change_enrollment from student.models import UserProfile, Registration, CourseEnrollment from student.tests.factories import UserFactory from edxmako.tests import mako_middleware_process_request TEST_DATA_MIXED_MODULESTORE = mixed_store_config(settings.COMMON_TEST_DATA_ROOT, {}) # Shib is supposed to provide 'REMOTE_USER', 'givenName', 'sn', 'mail', 'Shib-Identity-Provider' # attributes via request.META. We can count on 'Shib-Identity-Provider', and 'REMOTE_USER' being present # b/c of how mod_shib works but should test the behavior with the rest of the attributes present/missing # For the sake of python convention we'll make all of these variable names ALL_CAPS # These values would all returned from request.META, so they need to be str, not unicode IDP = 'https://idp.stanford.edu/' REMOTE_USER = 'test_user@stanford.edu' MAILS = [None, '', 'test_user@stanford.edu'] # unicode shouldn't be in emails, would fail django's email validator DISPLAYNAMES = [None, '', 'Jason 包'] GIVENNAMES = [None, '', 'jasön; John; bob'] # At Stanford, the givenNames can be a list delimited by ';' SNS = [None, '', '包; smith'] # At Stanford, the sns can be a list delimited by ';' def gen_all_identities(): """ A generator for all combinations of test inputs. Each generated item is a dict that represents what a shib IDP could potentially pass to django via request.META, i.e. setting (or not) request.META['givenName'], etc. """ def _build_identity_dict(mail, display_name, given_name, surname): """ Helper function to return a dict of test identity """ meta_dict = {'Shib-Identity-Provider': IDP, 'REMOTE_USER': REMOTE_USER} if display_name is not None: meta_dict['displayName'] = display_name if mail is not None: meta_dict['mail'] = mail if given_name is not None: meta_dict['givenName'] = given_name if surname is not None: meta_dict['sn'] = surname return meta_dict for mail in MAILS: for given_name in GIVENNAMES: for surname in SNS: for display_name in DISPLAYNAMES: yield _build_identity_dict(mail, display_name, given_name, surname) @ddt @override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE, SESSION_ENGINE='django.contrib.sessions.backends.cache') class ShibSPTest(ModuleStoreTestCase): """ Tests for the Shibboleth SP, which communicates via request.META (Apache environment variables set by mod_shib) """ request_factory = RequestFactory() def setUp(self): super(ShibSPTest, self).setUp(create_user=False) self.test_user_id = ModuleStoreEnum.UserID.test @unittest.skipUnless(settings.FEATURES.get('AUTH_USE_SHIB'), "AUTH_USE_SHIB not set") def test_exception_shib_login(self): """ Tests that we get the error page when there is no REMOTE_USER or Shib-Identity-Provider in request.META """ no_remote_user_request = self.request_factory.get('/shib-login') no_remote_user_request.META.update({'Shib-Identity-Provider': IDP}) no_remote_user_request.user = AnonymousUser() mako_middleware_process_request(no_remote_user_request) no_remote_user_response = shib_login(no_remote_user_request) self.assertEqual(no_remote_user_response.status_code, 403) self.assertIn("identity server did not return your ID information", no_remote_user_response.content) no_idp_request = self.request_factory.get('/shib-login') no_idp_request.META.update({'REMOTE_USER': REMOTE_USER}) no_idp_response = shib_login(no_idp_request) self.assertEqual(no_idp_response.status_code, 403) self.assertIn("identity server did not return your ID information", no_idp_response.content) def _assert_shib_login_is_logged(self, audit_log_call, remote_user): """Asserts that shibboleth login attempt is being logged""" remote_user = _flatten_to_ascii(remote_user) # django usernames have to be ascii method_name, args, _kwargs = audit_log_call self.assertEquals(method_name, 'info') self.assertEquals(len(args), 1) self.assertIn(u'logged in via Shibboleth', args[0]) self.assertIn(remote_user, args[0]) @unittest.skipUnless(settings.FEATURES.get('AUTH_USE_SHIB'), "AUTH_USE_SHIB not set") def test_shib_login(self): """ Tests that: * shib credentials that match an existing ExternalAuthMap with a linked active user logs the user in * shib credentials that match an existing ExternalAuthMap with a linked inactive user shows error page * shib credentials that match an existing ExternalAuthMap without a linked user and also match the email of an existing user without an existing ExternalAuthMap links the two and log the user in * shib credentials that match an existing ExternalAuthMap without a linked user and also match the email of an existing user that already has an ExternalAuthMap causes an error (403) * shib credentials that do not match an existing ExternalAuthMap causes the registration form to appear """ user_w_map = UserFactory.create(email='withmap@stanford.edu') extauth = ExternalAuthMap(external_id='withmap@stanford.edu', external_email='', external_domain='shib:https://idp.stanford.edu/', external_credentials="", user=user_w_map) user_wo_map = UserFactory.create(email='womap@stanford.edu') user_w_map.save() user_wo_map.save() extauth.save() inactive_user = UserFactory.create(email='inactive@stanford.edu') inactive_user.is_active = False inactive_extauth = ExternalAuthMap(external_id='inactive@stanford.edu', external_email='', external_domain='shib:https://idp.stanford.edu/', external_credentials="", user=inactive_user) inactive_user.save() inactive_extauth.save() idps = ['https://idp.stanford.edu/', 'https://someother.idp.com/'] remote_users = ['withmap@stanford.edu', 'womap@stanford.edu', 'testuser2@someother_idp.com', 'inactive@stanford.edu'] for idp in idps: for remote_user in remote_users: request = self.request_factory.get('/shib-login') request.session = import_module(settings.SESSION_ENGINE).SessionStore() # empty session request.META.update({'Shib-Identity-Provider': idp, 'REMOTE_USER': remote_user, 'mail': remote_user}) request.user = AnonymousUser() mako_middleware_process_request(request) with patch('external_auth.views.AUDIT_LOG') as mock_audit_log: response = shib_login(request) audit_log_calls = mock_audit_log.method_calls if idp == "https://idp.stanford.edu/" and remote_user == 'withmap@stanford.edu': self.assertIsInstance(response, HttpResponseRedirect) self.assertEqual(request.user, user_w_map) self.assertEqual(response['Location'], '/') # verify logging: self.assertEquals(len(audit_log_calls), 2) self._assert_shib_login_is_logged(audit_log_calls[0], remote_user) method_name, args, _kwargs = audit_log_calls[1] self.assertEquals(method_name, 'info') self.assertEquals(len(args), 1) self.assertIn(u'Login success', args[0]) self.assertIn(remote_user, args[0]) elif idp == "https://idp.stanford.edu/" and remote_user == 'inactive@stanford.edu': self.assertEqual(response.status_code, 403) self.assertIn("Account not yet activated: please look for link in your email", response.content) # verify logging: self.assertEquals(len(audit_log_calls), 2) self._assert_shib_login_is_logged(audit_log_calls[0], remote_user) method_name, args, _kwargs = audit_log_calls[1] self.assertEquals(method_name, 'warning') self.assertEquals(len(args), 1) self.assertIn(u'is not active after external login', args[0]) # self.assertEquals(remote_user, args[1]) elif idp == "https://idp.stanford.edu/" and remote_user == 'womap@stanford.edu': self.assertIsNotNone(ExternalAuthMap.objects.get(user=user_wo_map)) self.assertIsInstance(response, HttpResponseRedirect) self.assertEqual(request.user, user_wo_map) self.assertEqual(response['Location'], '/') # verify logging: self.assertEquals(len(audit_log_calls), 2) self._assert_shib_login_is_logged(audit_log_calls[0], remote_user) method_name, args, _kwargs = audit_log_calls[1] self.assertEquals(method_name, 'info') self.assertEquals(len(args), 1) self.assertIn(u'Login success', args[0]) self.assertIn(remote_user, args[0]) elif idp == "https://someother.idp.com/" and remote_user in \ ['withmap@stanford.edu', 'womap@stanford.edu', 'inactive@stanford.edu']: self.assertEqual(response.status_code, 403) self.assertIn("You have already created an account using an external login", response.content) # no audit logging calls self.assertEquals(len(audit_log_calls), 0) else: self.assertEqual(response.status_code, 200) self.assertContains(response, ("Preferences for {platform_name}" .format(platform_name=settings.PLATFORM_NAME))) # no audit logging calls self.assertEquals(len(audit_log_calls), 0) def _base_test_extauth_auto_activate_user_with_flag(self, log_user_string="inactive@stanford.edu"): """ Tests that FEATURES['BYPASS_ACTIVATION_EMAIL_FOR_EXTAUTH'] means extauth automatically linked users, activates them, and logs them in """ inactive_user = UserFactory.create(email='inactive@stanford.edu') inactive_user.is_active = False inactive_user.save() request = self.request_factory.get('/shib-login') request.session = import_module(settings.SESSION_ENGINE).SessionStore() # empty session request.META.update({ 'Shib-Identity-Provider': 'https://idp.stanford.edu/', 'REMOTE_USER': 'inactive@stanford.edu', 'mail': 'inactive@stanford.edu' }) request.user = AnonymousUser() with patch('external_auth.views.AUDIT_LOG') as mock_audit_log: response = shib_login(request) audit_log_calls = mock_audit_log.method_calls # reload user from db, since the view function works via db side-effects inactive_user = User.objects.get(id=inactive_user.id) self.assertIsNotNone(ExternalAuthMap.objects.get(user=inactive_user)) self.assertTrue(inactive_user.is_active) self.assertIsInstance(response, HttpResponseRedirect) self.assertEqual(request.user, inactive_user) self.assertEqual(response['Location'], '/') # verify logging: self.assertEquals(len(audit_log_calls), 3) self._assert_shib_login_is_logged(audit_log_calls[0], log_user_string) method_name, args, _kwargs = audit_log_calls[2] self.assertEquals(method_name, 'info') self.assertEquals(len(args), 1) self.assertIn(u'Login success', args[0]) self.assertIn(log_user_string, args[0]) @unittest.skipUnless(settings.FEATURES.get('AUTH_USE_SHIB'), "AUTH_USE_SHIB not set") @patch.dict(settings.FEATURES, {'BYPASS_ACTIVATION_EMAIL_FOR_EXTAUTH': True, 'SQUELCH_PII_IN_LOGS': False}) def test_extauth_auto_activate_user_with_flag_no_squelch(self): """ Wrapper to run base_test_extauth_auto_activate_user_with_flag with {'SQUELCH_PII_IN_LOGS': False} """ self._base_test_extauth_auto_activate_user_with_flag(log_user_string="inactive@stanford.edu") @unittest.skipUnless(settings.FEATURES.get('AUTH_USE_SHIB'), "AUTH_USE_SHIB not set") @patch.dict(settings.FEATURES, {'BYPASS_ACTIVATION_EMAIL_FOR_EXTAUTH': True, 'SQUELCH_PII_IN_LOGS': True}) def test_extauth_auto_activate_user_with_flag_squelch(self): """ Wrapper to run base_test_extauth_auto_activate_user_with_flag with {'SQUELCH_PII_IN_LOGS': True} """ self._base_test_extauth_auto_activate_user_with_flag(log_user_string="user.id: 1") @unittest.skipUnless(settings.FEATURES.get('AUTH_USE_SHIB'), "AUTH_USE_SHIB not set") @data(*gen_all_identities()) def test_registration_form(self, identity): """ Tests the registration form showing up with the proper parameters. Uses django test client for its session support """ client = DjangoTestClient() # identity k/v pairs will show up in request.META response = client.get(path='/shib-login/', data={}, follow=False, **identity) self.assertEquals(response.status_code, 200) mail_input_HTML = '<input class="" id="email" type="email" name="email"' if not identity.get('mail'): self.assertContains(response, mail_input_HTML) else: self.assertNotContains(response, mail_input_HTML) sn_empty = not identity.get('sn') given_name_empty = not identity.get('givenName') displayname_empty = not identity.get('displayName') fullname_input_html = '<input id="name" type="text" name="name"' if sn_empty and given_name_empty and displayname_empty: self.assertContains(response, fullname_input_html) else: self.assertNotContains(response, fullname_input_html) @unittest.skipUnless(settings.FEATURES.get('AUTH_USE_SHIB'), "AUTH_USE_SHIB not set") @data(*gen_all_identities()) def test_registration_form_submit(self, identity): """ Tests user creation after the registration form that pops is submitted. If there is no shib ExternalAuthMap in the session, then the created user should take the username and email from the request. Uses django test client for its session support """ # First we pop the registration form client = DjangoTestClient() response1 = client.get(path='/shib-login/', data={}, follow=False, **identity) # Then we have the user answer the registration form # These are unicode because request.POST returns unicode postvars = {'email': u'post_email@stanford.edu', 'username': u'post_username', # django usernames can't be unicode 'password': u'post_pássword', 'name': u'post_náme', 'terms_of_service': u'true', 'honor_code': u'true'} # use RequestFactory instead of TestClient here because we want access to request.user request2 = self.request_factory.post('/create_account', data=postvars) request2.session = client.session request2.user = AnonymousUser() mako_middleware_process_request(request2) with patch('student.views.AUDIT_LOG') as mock_audit_log: _response2 = create_account(request2) user = request2.user mail = identity.get('mail') # verify logging of login happening during account creation: audit_log_calls = mock_audit_log.method_calls self.assertEquals(len(audit_log_calls), 3) method_name, args, _kwargs = audit_log_calls[0] self.assertEquals(method_name, 'info') self.assertEquals(len(args), 1) self.assertIn(u'Login success on new account creation', args[0]) self.assertIn(u'post_username', args[0]) method_name, args, _kwargs = audit_log_calls[1] self.assertEquals(method_name, 'info') self.assertEquals(len(args), 2) self.assertIn(u'User registered with external_auth', args[0]) self.assertEquals(u'post_username', args[1]) method_name, args, _kwargs = audit_log_calls[2] self.assertEquals(method_name, 'info') self.assertEquals(len(args), 3) self.assertIn(u'Updated ExternalAuthMap for ', args[0]) self.assertEquals(u'post_username', args[1]) self.assertEquals(u'test_user@stanford.edu', args[2].external_id) # check that the created user has the right email, either taken from shib or user input if mail: self.assertEqual(user.email, mail) self.assertEqual(list(User.objects.filter(email=postvars['email'])), []) self.assertIsNotNone(User.objects.get(email=mail)) # get enforces only 1 such user else: self.assertEqual(user.email, postvars['email']) self.assertEqual(list(User.objects.filter(email=mail)), []) self.assertIsNotNone(User.objects.get(email=postvars['email'])) # get enforces only 1 such user # check that the created user profile has the right name, either taken from shib or user input profile = UserProfile.objects.get(user=user) sn_empty = not identity.get('sn') given_name_empty = not identity.get('givenName') displayname_empty = not identity.get('displayName') if displayname_empty: if sn_empty and given_name_empty: self.assertEqual(profile.name, postvars['name']) else: self.assertEqual(profile.name, request2.session['ExternalAuthMap'].external_name) self.assertNotIn(u';', profile.name) else: self.assertEqual(profile.name, request2.session['ExternalAuthMap'].external_name) self.assertEqual(profile.name, identity.get('displayName').decode('utf-8')) @unittest.skipUnless(settings.FEATURES.get('AUTH_USE_SHIB'), "AUTH_USE_SHIB not set") @data("", "shib:https://idp.stanford.edu/") def test_course_specific_login_and_reg(self, domain): """ Tests that the correct course specific login and registration urls work for shib """ course = CourseFactory.create( org='MITx', number='999', display_name='Robot Super Course', user_id=self.test_user_id, ) # Test for cases where course is found # set domains # temporarily set the branch to draft-preferred so we can update the course with self.store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, course.id): course.enrollment_domain = domain self.store.update_item(course, self.test_user_id) # setting location to test that GET params get passed through login_request = self.request_factory.get('/course_specific_login/MITx/999/Robot_Super_Course' + '?course_id=MITx/999/Robot_Super_Course' + '&enrollment_action=enroll') _reg_request = self.request_factory.get('/course_specific_register/MITx/999/Robot_Super_Course' + '?course_id=MITx/999/course/Robot_Super_Course' + '&enrollment_action=enroll') login_response = course_specific_login(login_request, 'MITx/999/Robot_Super_Course') reg_response = course_specific_register(login_request, 'MITx/999/Robot_Super_Course') if "shib" in domain: self.assertIsInstance(login_response, HttpResponseRedirect) self.assertEqual(login_response['Location'], reverse('shib-login') + '?course_id=MITx/999/Robot_Super_Course' + '&enrollment_action=enroll') self.assertIsInstance(login_response, HttpResponseRedirect) self.assertEqual(reg_response['Location'], reverse('shib-login') + '?course_id=MITx/999/Robot_Super_Course' + '&enrollment_action=enroll') else: self.assertIsInstance(login_response, HttpResponseRedirect) self.assertEqual(login_response['Location'], reverse('signin_user') + '?course_id=MITx/999/Robot_Super_Course' + '&enrollment_action=enroll') self.assertIsInstance(login_response, HttpResponseRedirect) self.assertEqual(reg_response['Location'], reverse('register_user') + '?course_id=MITx/999/Robot_Super_Course' + '&enrollment_action=enroll') # Now test for non-existent course # setting location to test that GET params get passed through login_request = self.request_factory.get('/course_specific_login/DNE/DNE/DNE' + '?course_id=DNE/DNE/DNE' + '&enrollment_action=enroll') _reg_request = self.request_factory.get('/course_specific_register/DNE/DNE/DNE' + '?course_id=DNE/DNE/DNE/Robot_Super_Course' + '&enrollment_action=enroll') login_response = course_specific_login(login_request, 'DNE/DNE/DNE') reg_response = course_specific_register(login_request, 'DNE/DNE/DNE') self.assertIsInstance(login_response, HttpResponseRedirect) self.assertEqual(login_response['Location'], reverse('signin_user') + '?course_id=DNE/DNE/DNE' + '&enrollment_action=enroll') self.assertIsInstance(login_response, HttpResponseRedirect) self.assertEqual(reg_response['Location'], reverse('register_user') + '?course_id=DNE/DNE/DNE' + '&enrollment_action=enroll') @unittest.skipUnless(settings.FEATURES.get('AUTH_USE_SHIB'), "AUTH_USE_SHIB not set") def test_enrollment_limit_by_domain(self): """ Tests that the enrollmentDomain setting is properly limiting enrollment to those who have the proper external auth """ # create 2 course, one with limited enrollment one without shib_course = CourseFactory.create( org='Stanford', number='123', display_name='Shib Only', enrollment_domain='shib:https://idp.stanford.edu/', user_id=self.test_user_id, ) open_enroll_course = CourseFactory.create( org='MITx', number='999', display_name='Robot Super Course', enrollment_domain='', user_id=self.test_user_id, ) # create 3 kinds of students, external_auth matching shib_course, external_auth not matching, no external auth shib_student = UserFactory.create() shib_student.save() extauth = ExternalAuthMap(external_id='testuser@stanford.edu', external_email='', external_domain='shib:https://idp.stanford.edu/', external_credentials="", user=shib_student) extauth.save() other_ext_student = UserFactory.create() other_ext_student.username = "teststudent2" other_ext_student.email = "teststudent2@other.edu" other_ext_student.save() extauth = ExternalAuthMap(external_id='testuser1@other.edu', external_email='', external_domain='shib:https://other.edu/', external_credentials="", user=other_ext_student) extauth.save() int_student = UserFactory.create() int_student.username = "teststudent3" int_student.email = "teststudent3@gmail.com" int_student.save() # Tests the two case for courses, limited and not for course in [shib_course, open_enroll_course]: for student in [shib_student, other_ext_student, int_student]: request = self.request_factory.post('/change_enrollment') request.POST.update({'enrollment_action': 'enroll', 'course_id': course.id.to_deprecated_string()}) request.user = student response = change_enrollment(request) # If course is not limited or student has correct shib extauth then enrollment should be allowed if course is open_enroll_course or student is shib_student: self.assertEqual(response.status_code, 200) self.assertTrue(CourseEnrollment.is_enrolled(student, course.id)) else: self.assertEqual(response.status_code, 400) self.assertFalse(CourseEnrollment.is_enrolled(student, course.id)) @unittest.skipUnless(settings.FEATURES.get('AUTH_USE_SHIB'), "AUTH_USE_SHIB not set") def test_shib_login_enrollment(self): """ A functionality test that a student with an existing shib login can auto-enroll in a class with GET or POST params. Also tests the direction functionality of the 'next' GET/POST param """ student = UserFactory.create() extauth = ExternalAuthMap(external_id='testuser@stanford.edu', external_email='', external_domain='shib:https://idp.stanford.edu/', external_credentials="", internal_password="password", user=student) student.set_password("password") student.save() extauth.save() course = CourseFactory.create( org='Stanford', number='123', display_name='Shib Only', enrollment_domain='shib:https://idp.stanford.edu/', user_id=self.test_user_id, ) # use django test client for sessions and url processing # no enrollment before trying self.assertFalse(CourseEnrollment.is_enrolled(student, course.id)) self.client.logout() request_kwargs = {'path': '/shib-login/', 'data': {'enrollment_action': 'enroll', 'course_id': course.id.to_deprecated_string(), 'next': '/testredirect'}, 'follow': False, 'REMOTE_USER': 'testuser@stanford.edu', 'Shib-Identity-Provider': 'https://idp.stanford.edu/'} response = self.client.get(**request_kwargs) # successful login is a redirect to "/" self.assertEqual(response.status_code, 302) self.assertEqual(response['location'], 'http://testserver/testredirect') # now there is enrollment self.assertTrue(CourseEnrollment.is_enrolled(student, course.id)) # Clean up and try again with POST (doesn't happen with real production shib, doing this for test coverage) self.client.logout() CourseEnrollment.unenroll(student, course.id) self.assertFalse(CourseEnrollment.is_enrolled(student, course.id)) response = self.client.post(**request_kwargs) # successful login is a redirect to "/" self.assertEqual(response.status_code, 302) self.assertEqual(response['location'], 'http://testserver/testredirect') # now there is enrollment self.assertTrue(CourseEnrollment.is_enrolled(student, course.id)) class ShibUtilFnTest(TestCase): """ Tests util functions in shib module """ def test__flatten_to_ascii(self): DIACRITIC = u"àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸåÅçÇ" # pylint: disable=C0103 STR_DIACRI = "àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸåÅçÇ" # pylint: disable=C0103 FLATTENED = u"aeiouAEIOUaeiouyAEIOUYaeiouAEIOUanoANOaeiouyAEIOUYaAcC" # pylint: disable=C0103 self.assertEqual(_flatten_to_ascii('jasön'), 'jason') # umlaut self.assertEqual(_flatten_to_ascii('Jason包'), 'Jason') # mandarin, so it just gets dropped self.assertEqual(_flatten_to_ascii('abc'), 'abc') # pass through unicode_test = _flatten_to_ascii(DIACRITIC) self.assertEqual(unicode_test, FLATTENED) self.assertIsInstance(unicode_test, unicode) str_test = _flatten_to_ascii(STR_DIACRI) self.assertEqual(str_test, FLATTENED) self.assertIsInstance(str_test, str)
unknown
codeparrot/codeparrot-clean
from collections import OrderedDict from typing import Any, Dict from ..wrappers.time_distributed_with_mask import TimeDistributedWithMask from .threshold_tuple_matcher import ThresholdTupleMatcher from ...common.params import get_choice_with_default class EmbeddedTupleMatcher: """ ``EmbeddedTupleMatchers`` operate on tuples with shape ``(batch_size, num_slots, num_words, embedding_dim)``. This class embeds the tuple input, then passes it off to an underlying ``Layer`` that computes the match between two tuples with the above shape. Parameters ---------- text_trainer: TextTrainer A reference to the TextTrainer object this TupleMatcher belongs to, so we can call ``embed_input`` with it. tuple_matcher_params: Dict[str, Any], default={} Parameters for constructing an underlying TupleMatcher that operates on embedded tuples. We only read the "type" key here, which indexes a class in ``embedded_tuple_matchers``, and then pass the rest of the parameters on to that class as ``kwargs``. """ def __init__(self, text_trainer, tuple_matcher_params: Dict[str, Any]=None): self.text_trainer = text_trainer if tuple_matcher_params is None: tuple_matcher_params = {} tuple_matcher_choice = get_choice_with_default(tuple_matcher_params, "embedded_matcher_type", list(embedded_tuple_matchers.keys())) self.tuple_matcher = embedded_tuple_matchers[tuple_matcher_choice](**tuple_matcher_params) def __call__(self, inputs): # pylint: disable=protected-access tuple1, tuple2 = inputs embedded_tuple1 = self.text_trainer._embed_input(tuple1) embedded_tuple2 = self.text_trainer._embed_input(tuple2) # The three TimeDistributedWithMasks wrap around the first three dimensions of the inputs: # num_options, num_answer_tuple, and num_background_tuples. match_layer = TimeDistributedWithMask(TimeDistributedWithMask(TimeDistributedWithMask(self.tuple_matcher))) return match_layer([embedded_tuple1, embedded_tuple2]) # The first item added here will be used as the default in some cases. embedded_tuple_matchers = OrderedDict() # pylint: disable=invalid-name embedded_tuple_matchers['threshold'] = ThresholdTupleMatcher
unknown
codeparrot/codeparrot-clean
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP from librehatti.config import _SENDER_EMAIL from librehatti.config import _PASSWORD DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'librehatti', 'USER': 'root', 'PASSWORD': 'return', 'HOST': 'localhost', 'PORT': '', } } ALLOWED_HOSTS = [] EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = _SENDER_EMAIL EMAIL_HOST_PASSWORD = _PASSWORD TIME_ZONE = 'Asia/Kolkata' LANGUAGE_CODE = 'en-us' SITE_ID = 1 USE_I18N = True USE_L10N = True USE_TZ = True LOCAL_URL = '' MEDIA_ROOT = '' MEDIA_URL = '' STATIC_ROOT = '' STATIC_URL = '/static/' STATICFILES_DIRS = ( '/home/seema/tcc work/Librehatti3/static', ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) TEMPLATE_CONTEXT_PROCESSORS = TCP + ( 'django.core.context_processors.request', ) SECRET_KEY = 'v5j3-ny)7zlk3wmqyg298#re3#8-v_v6+@9635h0-x9zak+8t*' TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) TEST_RUNNER = 'django.test.runner.DiscoverRunner' ROOT_URLCONF = 'librehatti.urls' WSGI_APPLICATION = 'librehatti.wsgi.application' TEMPLATE_DIRS = ( 'templates', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'suit', 'mptt', 'django.contrib.admin', 'librehatti.catalog', 'useraccounts', 'tinymce', 'librehatti.prints', 'librehatti.suspense', 'librehatti.bills', 'librehatti.reports', 'librehatti.voucher', 'librehatti.programmeletter', ) SUIT_CONFIG = { 'ADMIN_NAME': 'LibreHatti', 'MENU_ICONS': { 'sites': 'icon-leaf', 'auth': 'icon-lock', 'bills': 'icon-file', }, } ACCOUNT_ACTIVATION_DAYS = 7 LOGIN_REDIRECT_URL = 'admin:catalog' LOGIN_URL = 'admin:login' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, } }, } AJAX_LOOKUP_CHANNELS = { 'buyer': ('librehatti.catalog.lookups', 'BuyerLookup'), 'staff': ('librehatti.programmeletter.stafflookups', 'StaffLookup'), }
unknown
codeparrot/codeparrot-clean
""" Code to do with the grid engine master process, i.e. submitting slave jobs and waiting for them to report back """ import plugins, os, sys, socket, signal, logging, time from utils import * from Queue import Queue from SocketServer import ThreadingTCPServer, StreamRequestHandler from threading import RLock, Lock from ordereddict import OrderedDict from default.console import TextDisplayResponder, InteractiveResponder from default.knownbugs import CheckForBugs from default.actionrunner import BaseActionRunner from default.performance import getTestPerformance from types import StringType from glob import glob plugins.addCategory("abandoned", "abandoned", "were abandoned") class Abandoned(plugins.TestState): def __init__(self, freeText): plugins.TestState.__init__(self, "abandoned", briefText="job deletion failed", \ freeText=freeText, completed=1, lifecycleChange="complete") class QueueSystemServer(BaseActionRunner): instance = None def __init__(self, optionMap, allApps): BaseActionRunner.__init__(self, optionMap, logging.getLogger("Queue System Submit")) # queue for putting tests when we couldn't reuse the originals self.reuseFailureQueue = Queue() self.counterLock = Lock() self.testCount = 0 self.testsSubmitted = 0 self.maxCapacity = 100000 # infinity, sort of self.allApps = allApps self.jobs = OrderedDict() self.submissionRules = {} self.killedJobs = {} self.queueSystems = {} self.reuseOnly = False self.submitAddress = None self.createDirectories = False self.slaveLogDirs = set() self.delayedTestsForAdd = [] self.remainingForApp = OrderedDict() for app in allApps: queueSystem = self.getQueueSystem(app) # populate cache queueCapacity = queueSystem.getCapacity() if queueSystem else None # If the slaves run somewhere else, they won't create directories for us if queueSystem: self.createDirectories |= queueSystem.slavesOnRemoteSystem() configCapacity = app.getConfigValue("queue_system_max_capacity") for currCap in [queueCapacity, configCapacity]: if currCap is not None and currCap < self.maxCapacity: self.maxCapacity = currCap if self.maxCapacity == 0: raise plugins.TextTestError, "The queue system module is reporting zero capacity.\nEither you have set 'queue_system_max_capacity' to 0 or something is uninstalled or unavailable. Exiting." capacityPerSuite = self.maxCapacity / len(allApps) for app in allApps: self.remainingForApp[app.name] = capacityPerSuite QueueSystemServer.instance = self def addSuites(self, suites): for suite in suites: self.slaveLogDirs.add(suite.app.makeWriteDirectory("slavelogs")) plugins.log.info("Using " + queueSystemName(suite.app) + " queues for " + suite.app.description(includeCheckout=True)) def setSlaveServerAddress(self, address): self.submitAddress = os.getenv("CAPTUREMOCK_SERVER", address) self.testQueue.put("TextTest slave server started on " + address) def addTest(self, test): if self.createDirectories: test.makeWriteDirectory() capacityForApp = self.remainingForApp[test.app.name] if capacityForApp > 0: self.addTestToQueues(test) self.remainingForApp[test.app.name] = capacityForApp - 1 else: if test.app.name == self.remainingForApp.keys()[-1]: self.addTestToQueues(test) # For the last app (which may be the only one) there is no point in delaying else: self.delayedTestsForAdd.append(test) def queueTestForRerun(self, test): # Clear out the previous job reference, otherwise our grid polling will kill it off self.jobs[test] = [] self.addTestToQueues(test) def addTestToQueues(self, test): with self.counterLock: self.testCount += 1 queue = self.findQueueForTest(test) if queue: queue.put(test) def addDelayedTests(self): for test in self.delayedTestsForAdd: self.addTestToQueues(test) self.delayedTestsForAdd = [] def notifyAllRead(self, suites): self.addDelayedTests() BaseActionRunner.notifyAllRead(self, suites) def run(self): # picked up by core to indicate running in a thread self.runAllTests() if len(self.jobs): self.diag.info("All jobs submitted, polling the queue system now.") if self.canPoll(): self.pollQueueSystem() self.diag.info("No jobs left to poll, exiting thread") def pollQueueSystem(self): # Start by polling after 5 seconds, ever after try every 15 attempts = int(os.getenv("TEXTTEST_QS_POLL_WAIT", "5")) * 2 # Amount of time to wait before initiating polling of SGE if attempts >= 0: while True: for _ in range(attempts): time.sleep(0.5) if self.allComplete or self.exited: return self.updateJobStatus() attempts = 30 # In case any tests have had reruns triggered since we stopped submitting self.runQueue(self.getTestForRun, self.runTest, "rerunning", block=False) def canPoll(self): queueSystem = self.getQueueSystem(self.jobs.keys()[0]) return queueSystem.supportsPolling() def updateJobStatus(self): queueSystem = self.getQueueSystem(self.jobs.keys()[0]) statusInfo = queueSystem.getStatusForAllJobs() self.diag.info("Got status for all jobs : " + repr(statusInfo)) if statusInfo is not None: # queue system not available for some reason for test, jobs in self.jobs.items(): if not test.state.isComplete(): for jobId, _ in jobs: status = statusInfo.get(jobId) if status and test.state.hasStarted() and test.state.briefText: # Only do this to test jobs (might make a difference for derived configurations) # Ignore filtering states for now, which have empty 'briefText'. self.updateRunStatus(test, status) elif not status and not self.jobCompleted(test): # Do this to any jobs self.setSlaveFailed(test, False, True) def updateRunStatus(self, test, status): newRunStatus, newExplanation = status newState = test.state.makeModifiedState(newRunStatus, newExplanation, "grid status update") if newState: test.changeState(newState) def findQueueForTest(self, test): # If we've gone into reuse mode and there are no active tests for reuse, use the "reuse failure queue" if self.reuseOnly and self.testsSubmitted == 0: self.diag.info("Putting " + test.uniqueName + " in reuse failure queue " + self.remainStr()) return self.reuseFailureQueue else: self.diag.info("Putting " + test.uniqueName + " in normal queue " + self.remainStr()) return self.testQueue def handleLocalError(self, test, previouslySubmitted): self.handleErrorState(test, previouslySubmitted) if self.testCount == 0 or (self.reuseOnly and self.testsSubmitted == 0): self.diag.info("Submitting terminators after local error") self.submitTerminators() def submitTerminators(self): # snap out of our loop if this was the last one. Rely on others to manage the test queue self.reuseFailureQueue.put(None) def getTestForReuse(self, test, state, tryReuse): # Pick up any test that matches the current one's resource requirements if not self.exited: # Don't allow this to use up the terminator newTest = self.getTest(block=False, replaceTerminators=True) if newTest: if tryReuse and self.allowReuse(test, state, newTest): self.jobs[newTest] = self.getJobInfo(test) with self.counterLock: if self.testCount > 1: self.testCount -= 1 postText = self.remainStr() else: # Don't allow test count to drop to 0 here, can cause race conditions self.submitTerminators() postText = ": submitting terminators as final test" self.diag.info("Reusing slave from " + test.uniqueName + " for " + newTest.uniqueName + postText) return newTest else: self.diag.info("Adding to reuse failure queue : " + newTest.uniqueName) self.reuseFailureQueue.put(newTest) else: self.diag.info("No tests available for reuse : " + test.uniqueName) # Allowed a submitted job to terminate with self.counterLock: self.testsSubmitted -= 1 self.diag.info("No reuse for " + test.uniqueName + " : " + repr(self.testsSubmitted) + " tests still submitted") if self.exited and self.testsSubmitted == 0: self.diag.info("Forcing termination") self.submitTerminators() def allowReuse(self, oldTest, oldState, newTest): # Don't reuse jobs that have been killed if newTest.state.isComplete() or oldState.category == "killed": return False if oldTest.getConfigValue("queue_system_proxy_executable") or \ newTest.getConfigValue("queue_system_proxy_executable"): return False # Jobs maintain the same virtual display instance where possible, if they require different settings they can't be reused if oldTest.getConfigValue("virtual_display_extra_args") != newTest.getConfigValue("virtual_display_extra_args") or \ oldTest.getConfigValue("virtual_display_count") != newTest.getConfigValue("virtual_display_count"): return False oldRules = self.getSubmissionRules(oldTest) newRules = self.getSubmissionRules(newTest) return oldRules.allowsReuse(newRules) def getJobSubmissionRules(self, test): proxyRules = test.app.getProxySubmissionRules(test) if proxyRules: return proxyRules else: return self.getSubmissionRules(test) def getSubmissionRules(self, test): if self.submissionRules.has_key(test): return self.submissionRules[test] else: submissionRules = test.app.getSubmissionRules(test) self.submissionRules[test] = submissionRules return submissionRules def getTest(self, block, replaceTerminators=False): testOrStatus = self.getItemFromQueue(self.testQueue, block, replaceTerminators) if not testOrStatus: return if type(testOrStatus) == StringType: self.sendServerState(testOrStatus) return self.getTest(block) else: return testOrStatus def sendServerState(self, state): self.diag.info("Sending server state '" + state + "'") mimServAddr = os.getenv("CAPTUREMOCK_SERVER") if mimServAddr: host, port = mimServAddr.split(":") serverAddress = (host, int(port)) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(serverAddress) sock.sendall("SUT_SERVER:" + state + "\n") sock.close() def getTestForRunNormalMode(self, block): self.reuseOnly = False reuseFailure = self.getItemFromQueue(self.reuseFailureQueue, block=False) if reuseFailure: self.diag.info("Found a reuse failure...") return reuseFailure else: self.diag.info("Waiting for new tests...") newTest = self.getTest(block=block) if newTest: return newTest else: # Make sure we pick up anything that failed in reuse while we were submitting the final test... self.diag.info("No normal test found, checking reuse failures...") return self.getItemFromQueue(self.reuseFailureQueue, block=False) def getTestForRunReuseOnlyMode(self, block): self.reuseOnly = True self.diag.info("Waiting for reuse failures...") reuseFailure = self.getItemFromQueue(self.reuseFailureQueue, block=block) if reuseFailure: return reuseFailure elif self.testCount > 0 and self.testsSubmitted < self.maxCapacity: # Try again, the capacity situation has changed... return self.getTestForRunNormalMode(block) def getTestForRun(self, block=True): if self.testCount == 0 or (self.testsSubmitted < self.maxCapacity): return self.getTestForRunNormalMode(block) else: return self.getTestForRunReuseOnlyMode(block) def notifyAllComplete(self): BaseActionRunner.notifyAllComplete(self) errors = {} errorFiles = [] for logDir in self.slaveLogDirs: errorFiles += filter(os.path.getsize, glob(os.path.join(logDir, "*.errors"))) if len(errorFiles) == 0: return for fileName in errorFiles: contents = None # Take the shortest (i.e. most filtered) one for app in self.allApps: currContent = app.filterErrorText(fileName) if contents is None or len(currContent) < len(contents): contents = currContent if contents: errors[contents] = os.path.basename(fileName)[:-7] for msg, jobName in errors.items(): sys.stderr.write("WARNING: error produced by slave job '" + jobName + "'\n" + msg) def cleanup(self): self.sendServerState("Completed submission of all tests") def remainStr(self): return " : " + str(self.testCount) + " tests remain, " + str(self.testsSubmitted) + " are submitted." def runTest(self, test): submissionRules = self.getSubmissionRules(test) commandArgs = self.getSlaveCommandArgs(test, submissionRules) plugins.log.info("Q: Submitting " + repr(test) + submissionRules.getSubmitSuffix()) sys.stdout.flush() self.jobs[test] = [] # Preliminary jobs aren't interesting any more slaveEnv = OrderedDict() if not self.submitJob(test, submissionRules, commandArgs, slaveEnv): return with self.counterLock: self.testCount -= 1 self.testsSubmitted += 1 self.diag.info("Submission successful" + self.remainStr()) if not test.state.hasStarted(): test.changeState(self.getPendingState(test)) if self.testsSubmitted == self.maxCapacity: self.sendServerState("Completed submission of tests up to capacity") def fixProxyVar(self, env, test, withProxy): if withProxy and test.getConfigValue("queue_system_proxy_executable"): env["TEXTTEST_SUBMIT_COMMAND_ARGS"] = "?" def fixDisplay(self, env): # Must make sure SGE jobs don't get a locally referencing DISPLAY display = os.environ.get("DISPLAY") if display and display.startswith(":"): env["DISPLAY"] = plugins.gethostname() + display def getPendingState(self, test): freeText = "Job pending in " + queueSystemName(test.app) return plugins.TestState("pending", freeText=freeText, briefText="PEND", lifecycleChange="become pending") def getWindowsExecutable(self): # sys.executable could be something other than Python... like storytext. Don't involve that here return os.path.join(sys.exec_prefix, "python.exe") def getSlaveCommandArgs(self, test, submissionRules): interpreterArgs = [ self.getWindowsExecutable() ] if os.name == "nt" else [] return interpreterArgs + [ plugins.getTextTestProgram(), "-d", ":".join(self.optionMap.rootDirectories), "-a", test.app.name + test.app.versionSuffix(), "-l", "-tp", test.getRelPath() ] + \ self.getSlaveArgs(test) + self.getRunOptions(test.app, submissionRules) def getSlaveArgs(self, test): return [ "-slave", test.app.writeDirectory, "-servaddr", self.submitAddress ] def getRunOptions(self, app, submissionRules): runOptions = [] for slaveSwitch in app.getSlaveSwitches(): if self.optionMap.has_key(slaveSwitch): option = "-" + slaveSwitch runOptions.append(option) value = self.optionMap.get(slaveSwitch) if value: runOptions.append(value) if self.optionMap.has_key("xs"): runOptions.append("-x") runOptions.append("-xr") runOptions.append(self.optionMap.get("xr", os.path.expandvars("$TEXTTEST_PERSONAL_LOG/logging.debug"))) runOptions.append("-xw") runOptions.append(os.path.expandvars("$TEXTTEST_PERSONAL_LOG/" + submissionRules.getJobName())) return runOptions def getSlaveLogDir(self, test): return os.path.join(test.app.writeDirectory, "slavelogs") def setRemoteProcessId(self, test, pid): jobInfo = self.getJobInfo(test) if len(jobInfo) > 0: # Take the most recent job, it's hopefully the most interesting jobId = jobInfo[-1][0] queueSystem = self.getQueueSystem(test) queueSystem.setRemoteProcessId(jobId, pid) def getRemoteTestTmpDir(self, test): jobInfo = self.getJobInfo(test) if len(jobInfo) > 0: # Take the most recent job, it's hopefully the most interesting jobId = jobInfo[-1][0] queueSystem = self.getQueueSystem(test) remoteMachine = queueSystem.getRemoteTestMachine(jobId) if remoteMachine: return remoteMachine, test.writeDirectory def getSubmitCmdArgs(self, test, *args): queueSystem = self.getQueueSystem(test) return queueSystem.getSubmitCmdArgs(*args) def getQueueSystemCommand(self, test): submissionRules = self.getSubmissionRules(test) cmdArgs = self.getSubmitCmdArgs(test, submissionRules) text = queueSystemName(test) + " Command : " + plugins.commandLineString(cmdArgs) + " ...\n" + \ "Slave Command : " + " ".join(self.getSlaveCommandArgs(test, submissionRules)) + "\n" proxyArgs = self.getProxyCmdArgs(test) if proxyArgs: return queueSystemName(test) + " Proxy Command : " + plugins.commandLineString(proxyArgs) + "\n" + text else: return text def getProxyCmdArgs(self, test, slaveEnv={}): proxyCmd = test.getConfigValue("queue_system_proxy_executable") if proxyCmd: proxyOptions = test.getCommandLineOptions("proxy_options") fullProxyCmdArgs = [ proxyCmd ] + proxyOptions proxyRules = self.getJobSubmissionRules(test) return self.getSubmitCmdArgs(test, proxyRules, fullProxyCmdArgs, slaveEnv) else: return [] def modifyCommandForProxy(self, test, cmdArgs, slaveEnv): proxyArgs = self.getProxyCmdArgs(test, slaveEnv) if proxyArgs: cmdArgs[1:1] = [ "-sync", "y", "-V" ] # must sychronise in the proxy # Proxy likes to set environment variables, make sure they get forwarded slaveEnv["TEXTTEST_SUBMIT_COMMAND_ARGS"] = repr(cmdArgs) # Exact command arguments to run TextTest slave, for use by proxy return proxyArgs else: return cmdArgs def submitJob(self, test, submissionRules, commandArgs, slaveEnv, withProxy=True, jobType=""): self.diag.info("Submitting job at " + plugins.localtime() + ":" + repr(commandArgs)) self.diag.info("Creating job at " + plugins.localtime()) self.fixDisplay(slaveEnv) self.fixProxyVar(slaveEnv, test, withProxy) cmdArgs = self.getSubmitCmdArgs(test, submissionRules, commandArgs, slaveEnv) if withProxy: cmdArgs = self.modifyCommandForProxy(test, cmdArgs, slaveEnv) jobName = submissionRules.getJobName() self.diag.info("Creating job " + jobName + " with command arguments : " + " ".join(cmdArgs)) with self.lock: if self.exited: self.cancel(test) plugins.log.info("Q: Submission cancelled for " + repr(test) + " - exit underway") return False self.lockDiag.info("Got lock for submission") queueSystem = self.getQueueSystem(test) logDir = self.getSlaveLogDir(test) jobId, errorMessage = queueSystem.submitSlaveJob(cmdArgs, slaveEnv, logDir, submissionRules, jobType) if jobId is not None: self.diag.info("Job created with id " + jobId) self.jobs.setdefault(test, []).append((jobId, jobName)) self.lockDiag.info("Releasing lock for submission...") return True else: self.diag.info("Job not created : " + errorMessage) test.changeState(plugins.Unrunnable(errorMessage, "NOT SUBMITTED")) self.handleErrorState(test) return False def handleErrorState(self, test, previouslySubmitted=False): with self.counterLock: if previouslySubmitted: self.testsSubmitted -= 1 else: self.testCount -= 1 self.diag.info(repr(test) + " in error state" + self.remainStr()) bugchecker = CheckForBugs() self.setUpSuites(bugchecker, test) bugchecker(test) test.actionsCompleted() def setUpSuites(self, bugchecker, test): if test.parent: bugchecker.setUpSuite(test.parent) self.setUpSuites(bugchecker, test.parent) def _getJobFailureInfo(self, test): jobInfo = self.getJobInfo(test) # Take the most recent job, it's hopefully the most interesting jobId = jobInfo[-1][0] if len(jobInfo) > 0 else None queueSystem = self.getQueueSystem(test) return queueSystem.getJobFailureInfo(jobId) def getSlaveErrors(self, test, name): errorTexts = [ self.getSlaveErrorText(test, jobName, desc) for jobName, desc in self.getErrorJobNames(test, name) ] return "\n".join([text for text in errorTexts if text]) def getErrorJobNames(self, test, name): jobNames = [] for _, jobName in self.getJobInfo(test): jobNames.append((jobName, name)) if jobName.startswith("Test-"): jobNames.append(("Proxy-" + jobName[5:], name + " Proxy")) return jobNames def getSlaveErrorText(self, test, jobName, desc): errFile = os.path.join(self.getSlaveLogDir(test), jobName + ".errors") if os.path.isfile(errFile): errors = open(errFile).read() if errors: return "-" * 10 + " Error messages written by " + desc + " job " + "-" * 10 + \ "\n" + errors return "" def getJobInfo(self, test): return self.jobs.get(test, []) def killJob(self, test, jobId, jobName): prevTest, prevJobExisted = self.killedJobs.get(jobId, (None, False)) # Killing the same job for other tests should result in the cached result being returned if prevTest and test is not prevTest: return prevJobExisted self.describeJob(test, jobId, jobName) queueSystem = self.getQueueSystem(test) jobExisted = queueSystem.killJob(jobId) self.killedJobs[jobId] = test, jobExisted return jobExisted def getQueueSystem(self, test): queueModuleText = queueSystemName(test) if queueModuleText is None: return None queueModule = queueModuleText.lower() if self.queueSystems.has_key(queueModule): return self.queueSystems[queueModule] command = "from " + queueModule + " import QueueSystem as _QueueSystem" exec command system = _QueueSystem(test) #@UndefinedVariable self.queueSystems[queueModule] = system return system def changeState(self, test, newState, previouslySubmitted=True): test.changeState(newState) self.handleLocalError(test, previouslySubmitted) def killTests(self): # If we've been killed with some sort of limit signal, wait here until we know # all tests terminate. Otherwise we rely on them terminating naturally, and if they don't wantStatus = self.killSignal and self.killSignal not in [ signal.SIGINT, signal.SIGTERM ] killedTests = [] for test, jobList in self.jobs.items(): if not test.state.isComplete(): for jobId, jobName in jobList: if self.killTest(test, jobId, jobName, wantStatus): killedTests.append((test, jobId)) if wantStatus: self.waitForKill(killedTests) def waitForKill(self, killedTests): # Wait for a minute for the kill to take effect, otherwise give up stillRunning = killedTests for attempt in range(1, 61): stillRunning = filter(lambda (test, jobId): not test.state.isComplete(), stillRunning) if len(stillRunning) == 0: return time.sleep(1) for test, jobId in stillRunning: plugins.log.info("T: Cancellation in progress for " + repr(test) + ", waited " + str(attempt) + " seconds so far.") for test, jobId in stillRunning: name = queueSystemName(test.app) freeText = "Could not delete test in " + name + " (job " + jobId + "): have abandoned it" self.changeState(test, Abandoned(freeText)) def killOrCancel(self, test): # Explicitly chose test to kill (from the GUI) jobInfo = self.getJobInfo(test) if len(jobInfo) > 0: for jobId, jobName in jobInfo: self.killTest(test, jobId, jobName, wantStatus=True) else: self.diag.info("No job info found from queue system server, changing state to cancelled") return self.cancel(test) def killTest(self, test, jobId, jobName, wantStatus): self.diag.info("Killing test " + repr(test) + " in state " + test.state.category) jobExisted = self.killJob(test, jobId, jobName) startNotified = self.jobStarted(test) if jobExisted: if startNotified: self.diag.info("Job " + jobId + " was running.") return True else: self.diag.info("Job " + jobId + " was pending.") self.setKilledPending(test, jobId) return False else: self.diag.info("Job " + jobId + " did not exist.") # might get here when the test completed since we checked... if not test.state.isComplete(): self.setSlaveFailed(test, startNotified, wantStatus) return False def setSuspendStateForTests(self, tests, newState): for test in tests: queueSystem = self.getQueueSystem(test) for jobId, _ in self.getJobInfo(test): queueSystem.setSuspendState(jobId, newState) def jobStarted(self, test): return test.state.hasStarted() def jobCompleted(self, test): return test.state.isComplete() def setKilledPending(self, test, jobId): timeStr = plugins.localtime("%H:%M") briefText = "cancelled pending job at " + timeStr freeText = "Test job " + jobId + " was cancelled (while still pending in " + queueSystemName(test.app) +\ ") at " + timeStr self.cancel(test, briefText, freeText) def getJobFailureInfo(self, test, wantStatus): if wantStatus: return self._getJobFailureInfo(test) else: # Job accounting info can take ages to find, don't do it from GUI quit return "No accounting info found as quitting..." def setSlaveFailed(self, test, startNotified, wantStatus): failReason, fullText = self.getSlaveFailure(test, startNotified, wantStatus) fullText = failReason + "\n" + fullText self.changeState(test, self.getSlaveFailureState(startNotified, failReason, fullText)) def getSlaveFailure(self, test, startNotified, wantStatus): fullText = "" name = queueSystemName(test.app) slaveErrors = self.getSlaveErrors(test, name) if slaveErrors: fullText += slaveErrors fullText += self.getJobFailureInfo(test, wantStatus) return self.getSlaveFailureBriefText(name, startNotified), fullText def getSlaveFailureBriefText(self, name, startNotified): if startNotified: return "no report, possibly killed with SIGKILL" else: return name + " job exited" def getSlaveFailureState(self, startNotified, failReason, fullText): if startNotified: return plugins.TestState("killed", briefText=failReason, \ freeText=fullText, completed=1, lifecycleChange="complete") else: return plugins.Unrunnable(briefText=failReason, freeText=fullText, lifecycleChange="complete") def getPostText(self, test, jobId): name = queueSystemName(test.app) return "in " + name + " (job " + jobId + ")" def describeJob(self, test, jobId, *args): postText = self.getPostText(test, jobId) plugins.log.info("T: Cancelling " + repr(test) + " " + postText) # Used in slave class BasicSubmissionRules: classPrefix = "Test" def __init__(self, test): self.test = test def getJobName(self): path = self.test.getRelPath() parts = path.split("/") parts.reverse() name = self.classPrefix + "-" + ".".join(parts) + "-" + repr(self.test.app).replace(" ", "_") return name.replace(":", "_") def getJobFiles(self): jobName = self.getJobName() return jobName + ".log", jobName + ".errors" class SubmissionRules(BasicSubmissionRules): def __init__(self, optionMap, test): BasicSubmissionRules.__init__(self, test) self.optionMap = optionMap self.configResources = self.getConfigResources(test) self.processesNeeded = self.getProcessesNeeded() def getProcessesNeeded(self): return 1 def getExtraSubmitArgs(self): # pragma: no cover - documentation only return [] def getParallelEnvironment(self): return "" def findPriority(self): return 0 def findResourceList(self): return self.configResources def findQueue(self): cmdQueue = self.optionMap.get("q", "") if cmdQueue: return cmdQueue configQueue = self.test.app.getConfigValue("default_queue") if configQueue != "texttest_default": return configQueue return self.findDefaultQueue() def findDefaultQueue(self): return "" def findMachineList(self): return [] def forceOnPerformanceMachines(self): return False def allowsReuse(self, newRules): # Don't care about the order of the resources return set(self.configResources) == set(newRules.configResources) class ProxySubmissionRules(SubmissionRules): classPrefix = "Proxy" def getConfigResources(self, test): return test.getConfigValue("queue_system_proxy_resource") class TestSubmissionRules(SubmissionRules): classPrefix = "Test" def getConfigResources(self, test): if not self.optionMap.has_key("reconnect"): envSetting = os.path.expandvars(test.getEnvironment("QUEUE_SYSTEM_RESOURCE", "")) # Deprecated. See "queue_system_resource" in config file docs return [ envSetting ] if envSetting else test.getConfigValue("queue_system_resource") else: return "" def getProcessesNeeded(self): if not self.optionMap.has_key("reconnect"): envSetting = self.test.getEnvironment("QUEUE_SYSTEM_PROCESSES", "") # Deprecated. See "queue_system_processes" in config file docs return int(envSetting) if envSetting else self.test.getConfigValue("queue_system_processes") else: return 1 def getExtraSubmitArgs(self): if not self.optionMap.has_key("reconnect"): envSetting = os.path.expandvars(self.test.getEnvironment("QUEUE_SYSTEM_SUBMIT_ARGS", "")) # Deprecated. See "queue_system_submit_args" in config file docs argStr = envSetting or self.test.getConfigValue("queue_system_submit_args") return plugins.splitcmd(argStr) else: return [] def getSubmitSuffix(self): name = queueSystemName(self.test) queue = self.findQueue() if queue: return " to " + name + " queue " + queue else: return " to default " + name + " queue" def getParallelEnvironment(self): return self.test.getConfigValue("parallel_environment_name") def findResourceList(self): resourceList = [] if self.optionMap.has_key("R"): resourceList.append(self.optionMap["R"]) resourceList += self.configResources machine = self.test.app.getRunMachine() if machine != "localhost": resourceList.append("hostname=" + machine) # Won't work with LSF, but can't be bothered to figure it out there for now... if self.forceOnPerformanceMachines(): resources = self.getConfigValue("performance_test_resource") for resource in resources: resourceList.append(resource) return resourceList def getConfigValue(self, configKey): configDict = self.test.getConfigValue(configKey) defVal = configDict.get("default") if len(defVal) > 0: return defVal for val in configDict.values(): if len(val) > 0 and val[0] != "any" and val[0] != "none": return val return [] def findMachineList(self): if not self.forceOnPerformanceMachines(): return [] performanceMachines = self.getConfigValue("performance_test_machine") if len(performanceMachines) == 0: return [] return performanceMachines def getJobFiles(self): jobName = self.getJobName() return jobName + ".log", jobName + ".errors" def forceOnPerformanceMachines(self): if self.optionMap.has_key("perf"): return 1 minTimeForce = plugins.getNumberOfSeconds(str(self.test.getConfigValue("min_time_for_performance_force"))) if minTimeForce >= 0 and getTestPerformance(self.test) > minTimeForce: return 1 # If we haven't got a log_file yet, we should do this so we collect performance reliably logFile = self.test.getFileName(self.test.getConfigValue("log_file")) return logFile is None def allowsReuse(self, newRules): if self.optionMap.has_key("reconnect"): return True # should be able to reconnect anywhere... else: # Don't care about the order of the resources return set(self.findResourceList()) == set(newRules.findResourceList()) and \ self.processesNeeded == newRules.processesNeeded class SlaveRequestHandler(StreamRequestHandler): noReusePostfix = ".NO_REUSE" rerunPostfix = ".RERUN_TEST" def handle(self): identifier = self.rfile.readline().strip() if identifier == "TERMINATE_SERVER": return clientHost = self.client_address[0] # Don't use port, it changes all the time self.handleRequestFromHost(self.getHostName(clientHost), identifier) def getHostName(self, ipAddress): try: return socket.gethostbyaddr(ipAddress)[0].split(".")[0] except socket.error: return "<UNKNOWN HOST> (check IP configuration)" def parseIdentifier(self, identifier): rerun = identifier.endswith(self.rerunPostfix) if rerun: identifier = identifier.replace(self.rerunPostfix, "") tryReuse = not identifier.endswith(self.noReusePostfix) if not tryReuse: identifier = identifier.replace(self.noReusePostfix, "") return identifier, tryReuse, rerun def handleRequestFromHost(self, hostname, identifier): testString = self.rfile.readline().strip() test = self.server.getTest(testString) identifier, tryReuse, rerun = self.parseIdentifier(identifier) if test is None: sys.stderr.write("WARNING: Received request from hostname " + hostname + " (process " + identifier + ")\nwhich could not be parsed:\n'" + testString + "'\n") self.connection.shutdown(socket.SHUT_RDWR) elif self.server.clientCorrect(test, (hostname, identifier)): if not test.state.isComplete(): # we might have killed it already... oldBt = test.state.briefText # The updates are only for testing against old slave traffic, # a bit sad we can't disable them when not testing... _, state = test.getNewState(self.rfile, updatePaths=True) self.server.diag.info("Changed from '" + oldBt + "' to '" + state.briefText + "'") if rerun: self.server.diag.info("Instructed to rerun test " + test.uniqueName) self.server.clearClient(test) # it might come back from a different process QueueSystemServer.instance.queueTestForRerun(test) else: self.server.changeState(test, state) try: self.connection.shutdown(socket.SHUT_RD) except socket.error, e: # This only occurs on a mac, and doesn't affect functionality. pass if state.isComplete(): newTest = QueueSystemServer.instance.getTestForReuse(test, state, tryReuse) if newTest: self.wfile.write(socketSerialise(newTest)) else: self.server.storeClient(test, (hostname, identifier)) QueueSystemServer.instance.setRemoteProcessId(test, identifier) self.connection.shutdown(socket.SHUT_WR) else: expectedHost, expectedPid = self.server.testClientInfo[test] sys.stderr.write("WARNING: Unexpected TextTest slave for " + repr(test) + " connected from " + \ hostname + " (process " + identifier + ")\n") sys.stderr.write("Slave already registered from " + expectedHost + " (process " + expectedPid + ")\n") sys.stderr.write("Ignored all communication from this unexpected TextTest slave\n") sys.stderr.flush() self.connection.shutdown(socket.SHUT_RDWR) class SlaveServerResponder(plugins.Responder, ThreadingTCPServer): # Python's default value of 5 isn't very much... # There doesn't seem to be any disadvantage of allowing a longer queue, so we will use the system's maximum size request_queue_size = socket.SOMAXCONN def __init__(self, *args): plugins.Responder.__init__(self, *args) ThreadingTCPServer.__init__(self, (self.getIPAddress(), 0), self.handlerClass()) self.testMap = {} self.testLocks = {} self.testClientInfo = {} self.diag = logging.getLogger("Slave Server") self.terminate = False # If a client rings in and then the connectivity is lost, we don't want to hang waiting for it forever # So we enable keepalive that will check the connection if no data is received for a while self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True) # Default is 2 hours here on Linux which is rather a long time to wait for anything to happen. # We give up after 5 minutes if hasattr(socket, "TCP_KEEPIDLE"): self.socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 300) def getIPAddress(self): return socket.gethostbyname(socket.gethostname()) def addSuites(self, *args): # use this as an opportunity to broadcast our address serverAddress = self.getAddress() self.diag.info("Starting slave server at " + serverAddress) # Tell the submission code where we are QueueSystemServer.instance.setSlaveServerAddress(serverAddress) def handlerClass(self): return SlaveRequestHandler def canBeMainThread(self): return False # We wait for sockets and stuff def run(self): while not self.terminate: self.diag.info("Waiting for a new request...") try: self.handle_request() except: # e.g. can get interrupted system call here in 'select' if we get a signal sys.stderr.write("WARNING: slave server caught exception while processing request!\n") plugins.printException() self.diag.info("Terminating slave server") def notifyAllRead(self, *args): if len(self.testMap) == 0: self.notifyAllComplete() def notifyAllComplete(self): self.diag.info("Notified all complete, shutting down soon...") self.terminate = True sendSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sendSocket.connect(self.socket.getsockname()) sendSocket.sendall("TERMINATE_SERVER\n") sendSocket.close() def getAddress(self): host, port = self.socket.getsockname() return host + ":" + str(port) def notifyAdd(self, test, initial): if test.classId() == "test-case": self.storeTest(test) def storeTest(self, test): testPath = test.getRelPath() testApp = test.app.name + test.app.versionSuffix() if not self.testMap.has_key(testApp): self.testMap[testApp] = {} self.testMap[testApp][testPath] = test self.testLocks[test] = RLock() def changeState(self, test, state): # Several threads could be trying to do this at once... lock = self.testLocks.get(test) with lock: allow = self.allowChange(test.state, state) if allow: test.changeState(state) else: self.diag.info("Rejecting state change, old state " + test.state.category + " is complete, new state " + state.category + " is not.") return allow def allowChange(self, oldState, newState): return newState.isComplete() or not oldState.isComplete() def getTest(self, testString): self.diag.info("Received request for '" + testString + "'") try: appName, testPath = socketParse(testString) return self.testMap[appName][testPath] except ValueError: return def clientCorrect(self, test, clientInfo): # Only allow one client per test! return test not in self.testClientInfo or self.testClientInfo[test] == clientInfo def storeClient(self, test, clientInfo): self.testClientInfo[test] = clientInfo def clearClient(self, test): del self.testClientInfo[test] class MasterTextResponder(TextDisplayResponder): def getPrefix(self, test): return "S: " # don't get things in order, so indenting is pointless def shouldDescribe(self, test): return True # Write the successful tests also class MasterInteractiveResponder(InteractiveResponder): def getPrefix(self, test): return "" # don't get things in order, so indenting is pointless
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python # # Copyright 2011-2013 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. import os, tarfile, hashlib, re, shutil from snapshot import * f = open(snapshotfile) date = None rev = None platform = None snap = None i = 0 for line in f.readlines(): i += 1 parsed = parse_line(i, line) if (not parsed): continue if parsed["type"] == "snapshot": date = parsed["date"] rev = parsed["rev"] elif rev != None and parsed["type"] == "file": platform = parsed["platform"] hsh = parsed["hash"] snap = full_snapshot_name(date, rev, platform, hsh) dl = os.path.join(download_dir_base, snap) url = download_url_base + "/" + snap if (not os.path.exists(dl)): print("downloading " + url) get_url_to_file(url, dl) if (snap_filename_hash_part(snap) == hash_file(dl)): print("got download with ok hash") else: raise Exception("bad hash on download")
unknown
codeparrot/codeparrot-clean
# -*- coding: iso-8859-1 -*- """ MoinMoin - page contents writer @copyright: 2007 MoinMoin:JohannesBerg @license: GNU GPL, see COPYING for details. """ import xmlrpclib import sys from MoinMoin.script import MoinScript class PluginScript(MoinScript): """\ Purpose: ======== This tool allows you to edit a page with xmlrpc. It is more of a commented example than an actual script. Detailed Instructions: ====================== General syntax: moin xmlrpc write <targeturl> <username> <password> <pagename> Example: To edit the page 'FrontPage' on 'http://wiki.example.org/' using the username 'JohnSmith' and the password 'MyPass', changing the page contents to 'This will be the new contents of the page!' use: moin xmlrpc write http://wiki.example.org/ JohnSmith MyPass FrontPage This will be the new contents of the page! ^D Note: we automatically append ?action=xmlrpc2 to the target url given. """ def __init__(self, argv, def_values): MoinScript.__init__(self, argv, def_values) self.argv = argv # script entrypoint def mainloop(self): # grab parameters url = self.argv[0] + '?action=xmlrpc2' user = self.argv[1] passwd = self.argv[2] pagename = self.argv[3] # get auth token from server giving username/password s = xmlrpclib.ServerProxy(url) token = s.getAuthToken(user, passwd) if not token: print 'Invalid username/password' return # Verify that the token is valid by using it # and checking that the result is 'SUCCESS'. # The token should be valid for 15 minutes. assert s.applyAuthToken(token) == 'SUCCESS' try: # read new page contents content = sys.stdin.read() # build a multicall object that mcall = xmlrpclib.MultiCall(s) # first applies the token and mcall.applyAuthToken(token) # then edits the page mcall.putPage(pagename, content) # now execute the multicall results = mcall() # everything should have worked # instead of the asserts you can have anything else # but you should definitely access all the results # once so that faults are checked and raised assert results[0] == 'SUCCESS' assert results[1] is True finally: # be nice to the server and clean up the token # regardless of what happened assert s.deleteAuthToken(token) == 'SUCCESS'
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- # ########################## Copyrights and license ############################ # # # Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> # # Copyright 2012 Zearin <zearin@gonk.net> # # Copyright 2013 AKFish <akfish@gmail.com> # # Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> # # # # This file is part of PyGithub. http://jacquev6.github.com/PyGithub/ # # # # PyGithub is free software: you can redistribute it and/or modify it under # # the terms of the GNU Lesser General Public License as published by the Free # # Software Foundation, either version 3 of the License, or (at your option) # # any later version. # # # # PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # # details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with PyGithub. If not, see <http://www.gnu.org/licenses/>. # # # # ############################################################################## import github.GithubObject class GitAuthor(github.GithubObject.NonCompletableGithubObject): """ This class represents GitAuthors as returned for example by http://developer.github.com/v3/todo """ @property def date(self): """ :type: datetime.datetime """ return self._date.value @property def email(self): """ :type: string """ return self._email.value @property def name(self): """ :type: string """ return self._name.value def _initAttributes(self): self._date = github.GithubObject.NotSet self._email = github.GithubObject.NotSet self._name = github.GithubObject.NotSet def _useAttributes(self, attributes): if "date" in attributes: # pragma no branch self._date = self._makeDatetimeAttribute(attributes["date"]) if "email" in attributes: # pragma no branch self._email = self._makeStringAttribute(attributes["email"]) if "name" in attributes: # pragma no branch self._name = self._makeStringAttribute(attributes["name"])
unknown
codeparrot/codeparrot-clean
it("should allow to access utils in loader", () => { expect(require("./loader!" + __filename)).toEqual({ request1: "./index.js", request2: "./index.js" }); });
javascript
github
https://github.com/webpack/webpack
test/cases/loaders/utils/index.js
from abc import abstractmethod, ABCMeta import collections class Primitive(metaclass=ABCMeta): """ Base class for callable Lisp-like objects to be defined inside config """ @abstractmethod def __call__(self): pass class Constant(Primitive): def __init__(self, value): assert not isinstance(value, Primitive) self.value = value def __call__(self): return self.value class Function(Primitive): def __init__(self, func, *args): assert isinstance(func, collections.Callable), func self.func = func for value in args: assert isinstance(value, Primitive) self.args = args def __call__(self): return self.func(*(arg() for arg in self.args)) class Try(Primitive): def __init__(self, *funcs): for func in funcs: assert isinstance(func, collections.Callable) self.funcs = funcs def __call__(self): for func in self.funcs: try: return func() except Exception: continue
unknown
codeparrot/codeparrot-clean
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from erpnext.stock.doctype.bin.bin import update_item_projected_qty def execute(): repost_bin_qty() repost_item_projected_qty() def repost_bin_qty(): for bin in frappe.db.sql(""" select name from `tabBin` where (actual_qty + ordered_qty + indented_qty + planned_qty- reserved_qty - reserved_qty_for_production) != projected_qty """, as_dict=1): bin_doc = frappe.get_doc('Bin', bin.name) bin_doc.set_projected_qty() bin_doc.db_set("projected_qty", bin_doc.projected_qty, update_modified = False) def repost_item_projected_qty(): for data in frappe.db.sql(""" select `tabBin`.item_code as item_code, sum(`tabBin`.projected_qty) as projected_qty, `tabItem`.total_projected_qty as total_projected_qty from `tabBin`, `tabItem` where `tabBin`.item_code = `tabItem`.name group by `tabBin`.item_code having projected_qty <> total_projected_qty """, as_dict=1): update_item_projected_qty(data.item_code)
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python # This Python script generates AWS CloudFormation templates to start a VoltDB # cluster. Run the program without any arguments to see usage. # # For details on the CloudFormation template, you can check out the doc page at # http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html from string import Template import sys TEMPLATE = r""" { "AWSTemplateFormatVersion": "2010-09-09", "Description" : "AWS CloudFormation template for launching a $hosts-node k-safety=$ksafety VoltDB cluster. **WARNING** This template creates an Amazon EC2 instance. You will be billed for the AWS resources used if you create a stack from this template.", "Parameters": { $zone "InstanceType": { "Description": "VoltDB server EC2 instance type", "Type": "String", "Default": "m2.xlarge", "AllowedValues": [ "m1.medium","m1.large","m1.xlarge","m2.xlarge","m2.2xlarge","m2.4xlarge","m3.xlarge","m3.2xlarge","c1.medium","c1.xlarge","cc1.4xlarge"], "ConstraintDescription": "must be a valid EC2 instance type." }, "Example": { "Description": "VoltDB example to start. (voter, json-sessions, voltcache, voltkv, windowing)", "Type": "String", "Default": "voter", "AllowedValues": ["voter", "json-sessions", "voltkv", "windowing"], "ConstraintDescription": "must be a valid VoltDB example name." } }, "Mappings": { "AWSInstanceType2Arch": { "m1.medium" : { "Arch": "64" }, "m1.large" : { "Arch": "64" }, "m1.xlarge" : { "Arch": "64" }, "m2.xlarge" : { "Arch": "64" }, "m2.2xlarge" : { "Arch": "64" }, "m2.4xlarge" : { "Arch": "64" }, "m3.xlarge" : { "Arch": "64" }, "m3.2xlarge" : { "Arch": "64" }, "c1.medium" : { "Arch": "64" }, "c1.xlarge" : { "Arch": "64" }, "cc1.4xlarge": { "Arch": "64" } }, "AWSRegionArch2AMI": { "us-east-1" : { "64": "$amiid", "64HVM": "NOT YET SUPPORTED" } } }, "Resources": { "DBServer1": { "Type": "AWS::EC2::Instance", "Metadata": { "Comment": "Configure the bootstrap helpers to install and start VoltDB", "AWS::CloudFormation::Init": { "config": { "packages": { }, "sources": { }, "files": { "/etc/ntp.conf": { "content": { "Fn::Join": ["", [ "driftfile /var/lib/ntp/ntp.drift\n", "server time1.google.com burst iburst minpoll 4 maxpoll 4\n", "server time2.google.com burst iburst minpoll 4 maxpoll 4\n", "server time3.google.com burst iburst minpoll 4 maxpoll 4\n", "server time4.google.com burst iburst minpoll 4 maxpoll 4\n", "server 127.127.0.1\n", "fudge 127.127.0.1 stratum 10\n" ]]}, "mode": "000644", "owner": "root", "group": "root" }, "/tmp/deployment.xml": { "content": { "Fn::Join": ["", [ $deployment ]]}, "mode" : "000644" } }, "services": { "sysvinit": { "ntp": { "enabled" : "true", "ensureRunning": "true", "files": ["/etc/ntp.conf"] } } } } } }, "Properties": { "ImageId": { "Fn::FindInMap": [ "AWSRegionArch2AMI", { "Ref": "AWS::Region" }, { "Fn::FindInMap": [ "AWSInstanceType2Arch", { "Ref": "InstanceType" }, "Arch" ] } ] }, ${zone_ref} "InstanceType" : { "Ref": "InstanceType" }, "SecurityGroups": [ {"Ref": "DBServerSecurityGroup"} ], "UserData" : { "Fn::Base64": { "Fn::Join": ["", [ "#!/bin/bash -v\n", "# Helper function\n", "function error_exit\n", "{\n", " cfn-signal -e 1 -r \"$$1\" '", { "Ref": "WaitHandle" }, "'\n", " exit 1\n", "}\n", "# Initialize\n", "cfn-init -s ", { "Ref": "AWS::StackId" }, " -r DBServer1 ", " --region ", { "Ref": "AWS::Region" }, " || error_exit 'Failed to run cfn-init'\n", "# Sync clocks so that they are close enough to start a cluster\n", "service ntp stop\n", "a=\"1.0\"\n", "while [ $$(echo \"$${a#-}>0.05\" | bc) -eq 1 ];\n", "do a=`ntpdate -b -p 8 time1.google.com | awk '{ print $$10 }'`; done\n", "\n", "# Start VoltDB as user voltdb\n", "sudo su - voltdb -c bash << EOF\n", "exec > /tmp/script.out 2>&1\n", "set -x\n", "cd ", { "Ref": "Example" }, ";echo \"Starting VoltDB server\"\n", "../../bin/voltdb create -B -H `hostname -I` -l ../../voltdb/license.xml -d /tmp/deployment.xml\n", "\n", "while true; do\n", " sleep 1\n", " ../../bin/sqlcmd --query=exec\\ @Statistics\\ MEMORY\\ 0 </dev/null && break\n", "done\n", "./run.sh init\n", "EOF\n", "\n", "# All is well so signal success\n", "cfn-signal -e 0 -r \"VoltDB setup complete\" '", { "Ref": "WaitHandle" }, "'\n" ]]}} } }, $additional_servers "WaitHandle": { "Type": "AWS::CloudFormation::WaitConditionHandle" }, "WaitCondition": { "Type": "AWS::CloudFormation::WaitCondition", "DependsOn": "DBServer1", "Properties": { "Handle": {"Ref": "WaitHandle"}, "Timeout": "1200" } }, "DBServerSecurityGroup": { "Type": "AWS::EC2::SecurityGroup", "Properties": { "GroupDescription": "Enable client access via port 21212 and HTTP access via port 8080", "SecurityGroupIngress": [ {"IpProtocol": "tcp", "FromPort": "3021", "ToPort": "3021", "CidrIp": "0.0.0.0/0"}, {"IpProtocol": "tcp", "FromPort": "8080", "ToPort": "8080", "CidrIp": "0.0.0.0/0"}, {"IpProtocol": "tcp", "FromPort": "9090", "ToPort": "9090", "CidrIp": "0.0.0.0/0"}, {"IpProtocol": "tcp", "FromPort": "21211", "ToPort": "21211", "CidrIp": "0.0.0.0/0"}, {"IpProtocol": "tcp", "FromPort": "21212", "ToPort": "21212", "CidrIp": "0.0.0.0/0"}, {"IpProtocol": "tcp", "FromPort": "22", "ToPort": "22", "CidrIp": "0.0.0.0/0"}, {"IpProtocol": "udp", "FromPort": "123", "ToPort": "123", "CidrIp": "0.0.0.0/0"} ] } } }, "Outputs": { "VoltDBNodeURL": { "Value": { "Fn::Join": ["", ["http://", { "Fn::GetAtt": [ "DBServer1", "PublicDnsName" ]}, ":8080"]] }, "Description": "URL to VoltDB Catalog Report page." }, "VoltDBClientCmd": { "Value": { "Fn::Join": ["", ["ssh voltdb@", { "Fn::GetAtt": [ "DBServer1", "PublicDnsName" ]}, " \"bash --login -c 'cd ", { "Ref": "Example" }, "; ./run.sh client'\""]] }, "Description": "Command to start the client over an SSH connection. The password is 'voltdb'." } } } """ ZONE_TEMPLATE = r""""AvailabilityZone": { "Description": "Availability zone to start the servers in", "Type": "String", "Default": "us-east-1e", "AllowedValues": ["us-east-1a", "us-east-1b", "us-east-1c", "us-east-1d", "us-east-1e"], "ConstraintDescription": "must be a valid availability zone in the U.S. East region." }, """ ZONE_REF_TEMPLATE = r""""AvailabilityZone" : { "Ref": "AvailabilityZone" },""" DEPLOYMENT_TEMPLATE = r""" "<?xml version=\"1.0\"?>\n", "<deployment>\n", " <cluster hostcount=\"$hosts\" kfactor=\"$ksafety\" />\n", " <httpd enabled=\"true\">\n", " <jsonapi enabled=\"true\" />\n", " </httpd>\n", "</deployment>\n" """ SERVER_TEMPLATE = r""" "DBServer$seqId": { "Type": "AWS::EC2::Instance", "Metadata": { "Comment": "Configure the bootstrap helpers to install and start VoltDB", "AWS::CloudFormation::Init": { "config": { "packages": { }, "sources": { }, "files": { "/etc/ntp.conf": { "content": { "Fn::Join": ["", [ "driftfile /var/lib/ntp/ntp.drift\n", "server ", { "Fn::GetAtt": [ "DBServer1", "PrivateIp" ]}, " burst iburst minpoll 4 maxpoll 4\n", "server 127.127.0.1\n", "fudge 127.127.0.1 stratum 10\n" ]]}, "mode": "000644", "owner": "root", "group": "root" }, "/tmp/deployment.xml": { "content": { "Fn::Join": ["", [ $deployment ]]}, "mode" : "000644" } }, "services": { "sysvinit": { "ntp": { "enabled" : "true", "ensureRunning": "true", "files": ["/etc/ntp.conf"] } } } } } }, "Properties": { "ImageId": { "Fn::FindInMap": [ "AWSRegionArch2AMI", { "Ref": "AWS::Region" }, { "Fn::FindInMap": [ "AWSInstanceType2Arch", { "Ref": "InstanceType" }, "Arch" ] } ] }, "AvailabilityZone" : { "Ref": "AvailabilityZone" }, "InstanceType" : { "Ref": "InstanceType" }, "SecurityGroups": [ {"Ref": "DBServerSecurityGroup"} ], "UserData" : { "Fn::Base64": { "Fn::Join": ["", [ "#!/bin/bash -v\n", "# Helper function\n", "function error_exit\n", "{\n", " cfn-signal -e 1 -r \"$$1\" '", { "Ref": "WaitHandle" }, "'\n", " exit 1\n", "}\n", "# Sync clocks so that they are close enough to start a cluster\n", "service ntp stop\n", "a=\"1.0\"\n", "while [ $$(echo \"$${a#-}>0.05\" | bc) -eq 1 ];\n", "do a=`ntpdate -b -p 8 time1.google.com | awk '{ print $$10 }'`; done\n", "\n", "# Initialize\n", "cfn-init -s ", { "Ref": "AWS::StackId" }, " -r DBServer$seqId ", " --region ", { "Ref": "AWS::Region" }, " || error_exit 'Failed to run cfn-init'\n", "# Start VoltDB as user voltdb\n", "sudo su - voltdb -c bash << EOF\n", "cd ", { "Ref": "Example" }, ";echo \"Starting VoltDB server\"\n", "../../bin/voltdb create -B -H ", { "Fn::GetAtt": [ "DBServer1", "PrivateIp" ]}, " -l ../../voltdb/license.xml -d /tmp/deployment.xml\n", "EOF\n" ]]}} } }, """ def main(): if (len(sys.argv) != 4): print "Usage: %s HOSTCOUNT KSAFETY AMI-ID" % (sys.argv[0]) return -1 params = dict(hosts=int(sys.argv[1]), ksafety=int(sys.argv[2]), amiid=sys.argv[3], zone="", zone_ref="") # Order of template substitution: # - deployment # - servers # - zone # - top level template params["deployment"] = Template(DEPLOYMENT_TEMPLATE).substitute(params) servers = [] if params["hosts"] > 1: params["zone"] = Template(ZONE_TEMPLATE).substitute(params) params["zone_ref"] = ZONE_REF_TEMPLATE for i in xrange(params["hosts"]-1): params["seqId"] = i + 2 servers.append(Template(SERVER_TEMPLATE).substitute(params)) params["additional_servers"] = "\n".join(servers) print Template(TEMPLATE).substitute(params) return 0 if __name__ == "__main__": sys.exit(main())
unknown
codeparrot/codeparrot-clean
# # 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. # """ A collections of builtin functions """ import sys import functools import warnings if sys.version < "3": from itertools import imap as map if sys.version >= '3': basestring = str from pyspark import since, SparkContext from pyspark.rdd import ignore_unicode_prefix, PythonEvalType from pyspark.sql.column import Column, _to_java_column, _to_seq, _create_column_from_literal from pyspark.sql.dataframe import DataFrame from pyspark.sql.types import StringType, DataType # Keep UserDefinedFunction import for backwards compatible import; moved in SPARK-22409 from pyspark.sql.udf import UserDefinedFunction, _create_udf def _create_name_function(name, doc=""): """ Create a function that takes a column name argument, by name""" def _(col): sc = SparkContext._active_spark_context jc = getattr(sc._jvm.functions, name)(col._jc if isinstance(col, Column) else col) return Column(jc) _.__name__ = name _.__doc__ = doc return _ def _create_function(name, doc=""): """ Create a function that takes a Column object, by name""" def _(col): sc = SparkContext._active_spark_context jc = getattr(sc._jvm.functions, name)(_to_java_column(col)) return Column(jc) _.__name__ = name _.__doc__ = doc return _ def _wrap_deprecated_function(func, message): """ Wrap the deprecated function to print out deprecation warnings""" def _(col): warnings.warn(message, DeprecationWarning) return func(col) return functools.wraps(func)(_) def _create_binary_mathfunction(name, doc=""): """ Create a binary mathfunction by name""" def _(col1, col2): sc = SparkContext._active_spark_context # users might write ints for simplicity. This would throw an error on the JVM side. jc = getattr(sc._jvm.functions, name)(col1._jc if isinstance(col1, Column) else float(col1), col2._jc if isinstance(col2, Column) else float(col2)) return Column(jc) _.__name__ = name _.__doc__ = doc return _ def _create_window_function(name, doc=''): """ Create a window function by name """ def _(): sc = SparkContext._active_spark_context jc = getattr(sc._jvm.functions, name)() return Column(jc) _.__name__ = name _.__doc__ = 'Window function: ' + doc return _ _lit_doc = """ Creates a :class:`Column` of literal value. >>> df.select(lit(5).alias('height')).withColumn('spark_user', lit(True)).take(1) [Row(height=5, spark_user=True)] """ _name_functions = { # name functions take a column name as their argument 'lit': _lit_doc, 'col': 'Returns a :class:`Column` based on the given column name.', 'column': 'Returns a :class:`Column` based on the given column name.', 'asc': 'Returns a sort expression based on the ascending order of the given column name.', 'desc': 'Returns a sort expression based on the descending order of the given column name.', } _functions = { 'upper': 'Converts a string expression to upper case.', 'lower': 'Converts a string expression to upper case.', 'sqrt': 'Computes the square root of the specified float value.', 'abs': 'Computes the absolute value.', 'max': 'Aggregate function: returns the maximum value of the expression in a group.', 'min': 'Aggregate function: returns the minimum value of the expression in a group.', 'count': 'Aggregate function: returns the number of items in a group.', 'sum': 'Aggregate function: returns the sum of all values in the expression.', 'avg': 'Aggregate function: returns the average of the values in a group.', 'mean': 'Aggregate function: returns the average of the values in a group.', 'sumDistinct': 'Aggregate function: returns the sum of distinct values in the expression.', } _functions_1_4 = { # unary math functions 'acos': ':return: inverse cosine of `col`, as if computed by `java.lang.Math.acos()`', 'asin': ':return: inverse sine of `col`, as if computed by `java.lang.Math.asin()`', 'atan': ':return: inverse tangent of `col`, as if computed by `java.lang.Math.atan()`', 'cbrt': 'Computes the cube-root of the given value.', 'ceil': 'Computes the ceiling of the given value.', 'cos': """:param col: angle in radians :return: cosine of the angle, as if computed by `java.lang.Math.cos()`.""", 'cosh': """:param col: hyperbolic angle :return: hyperbolic cosine of the angle, as if computed by `java.lang.Math.cosh()`""", 'exp': 'Computes the exponential of the given value.', 'expm1': 'Computes the exponential of the given value minus one.', 'floor': 'Computes the floor of the given value.', 'log': 'Computes the natural logarithm of the given value.', 'log10': 'Computes the logarithm of the given value in Base 10.', 'log1p': 'Computes the natural logarithm of the given value plus one.', 'rint': 'Returns the double value that is closest in value to the argument and' + ' is equal to a mathematical integer.', 'signum': 'Computes the signum of the given value.', 'sin': """:param col: angle in radians :return: sine of the angle, as if computed by `java.lang.Math.sin()`""", 'sinh': """:param col: hyperbolic angle :return: hyperbolic sine of the given value, as if computed by `java.lang.Math.sinh()`""", 'tan': """:param col: angle in radians :return: tangent of the given value, as if computed by `java.lang.Math.tan()`""", 'tanh': """:param col: hyperbolic angle :return: hyperbolic tangent of the given value, as if computed by `java.lang.Math.tanh()`""", 'toDegrees': '.. note:: Deprecated in 2.1, use :func:`degrees` instead.', 'toRadians': '.. note:: Deprecated in 2.1, use :func:`radians` instead.', 'bitwiseNOT': 'Computes bitwise not.', } _name_functions_2_4 = { 'asc_nulls_first': 'Returns a sort expression based on the ascending order of the given' + ' column name, and null values return before non-null values.', 'asc_nulls_last': 'Returns a sort expression based on the ascending order of the given' + ' column name, and null values appear after non-null values.', 'desc_nulls_first': 'Returns a sort expression based on the descending order of the given' + ' column name, and null values appear before non-null values.', 'desc_nulls_last': 'Returns a sort expression based on the descending order of the given' + ' column name, and null values appear after non-null values', } _collect_list_doc = """ Aggregate function: returns a list of objects with duplicates. .. note:: The function is non-deterministic because the order of collected results depends on order of rows which may be non-deterministic after a shuffle. >>> df2 = spark.createDataFrame([(2,), (5,), (5,)], ('age',)) >>> df2.agg(collect_list('age')).collect() [Row(collect_list(age)=[2, 5, 5])] """ _collect_set_doc = """ Aggregate function: returns a set of objects with duplicate elements eliminated. .. note:: The function is non-deterministic because the order of collected results depends on order of rows which may be non-deterministic after a shuffle. >>> df2 = spark.createDataFrame([(2,), (5,), (5,)], ('age',)) >>> df2.agg(collect_set('age')).collect() [Row(collect_set(age)=[5, 2])] """ _functions_1_6 = { # unary math functions 'stddev': 'Aggregate function: returns the unbiased sample standard deviation of' + ' the expression in a group.', 'stddev_samp': 'Aggregate function: returns the unbiased sample standard deviation of' + ' the expression in a group.', 'stddev_pop': 'Aggregate function: returns population standard deviation of' + ' the expression in a group.', 'variance': 'Aggregate function: returns the population variance of the values in a group.', 'var_samp': 'Aggregate function: returns the unbiased variance of the values in a group.', 'var_pop': 'Aggregate function: returns the population variance of the values in a group.', 'skewness': 'Aggregate function: returns the skewness of the values in a group.', 'kurtosis': 'Aggregate function: returns the kurtosis of the values in a group.', 'collect_list': _collect_list_doc, 'collect_set': _collect_set_doc } _functions_2_1 = { # unary math functions 'degrees': """ Converts an angle measured in radians to an approximately equivalent angle measured in degrees. :param col: angle in radians :return: angle in degrees, as if computed by `java.lang.Math.toDegrees()` """, 'radians': """ Converts an angle measured in degrees to an approximately equivalent angle measured in radians. :param col: angle in degrees :return: angle in radians, as if computed by `java.lang.Math.toRadians()` """, } # math functions that take two arguments as input _binary_mathfunctions = { 'atan2': """ :param col1: coordinate on y-axis :param col2: coordinate on x-axis :return: the `theta` component of the point (`r`, `theta`) in polar coordinates that corresponds to the point (`x`, `y`) in Cartesian coordinates, as if computed by `java.lang.Math.atan2()` """, 'hypot': 'Computes ``sqrt(a^2 + b^2)`` without intermediate overflow or underflow.', 'pow': 'Returns the value of the first argument raised to the power of the second argument.', } _window_functions = { 'row_number': """returns a sequential number starting at 1 within a window partition.""", 'dense_rank': """returns the rank of rows within a window partition, without any gaps. The difference between rank and dense_rank is that dense_rank leaves no gaps in ranking sequence when there are ties. That is, if you were ranking a competition using dense_rank and had three people tie for second place, you would say that all three were in second place and that the next person came in third. Rank would give me sequential numbers, making the person that came in third place (after the ties) would register as coming in fifth. This is equivalent to the DENSE_RANK function in SQL.""", 'rank': """returns the rank of rows within a window partition. The difference between rank and dense_rank is that dense_rank leaves no gaps in ranking sequence when there are ties. That is, if you were ranking a competition using dense_rank and had three people tie for second place, you would say that all three were in second place and that the next person came in third. Rank would give me sequential numbers, making the person that came in third place (after the ties) would register as coming in fifth. This is equivalent to the RANK function in SQL.""", 'cume_dist': """returns the cumulative distribution of values within a window partition, i.e. the fraction of rows that are below the current row.""", 'percent_rank': """returns the relative rank (i.e. percentile) of rows within a window partition.""", } # Wraps deprecated functions (keys) with the messages (values). _functions_deprecated = { } for _name, _doc in _name_functions.items(): globals()[_name] = since(1.3)(_create_name_function(_name, _doc)) for _name, _doc in _functions.items(): globals()[_name] = since(1.3)(_create_function(_name, _doc)) for _name, _doc in _functions_1_4.items(): globals()[_name] = since(1.4)(_create_function(_name, _doc)) for _name, _doc in _binary_mathfunctions.items(): globals()[_name] = since(1.4)(_create_binary_mathfunction(_name, _doc)) for _name, _doc in _window_functions.items(): globals()[_name] = since(1.6)(_create_window_function(_name, _doc)) for _name, _doc in _functions_1_6.items(): globals()[_name] = since(1.6)(_create_function(_name, _doc)) for _name, _doc in _functions_2_1.items(): globals()[_name] = since(2.1)(_create_function(_name, _doc)) for _name, _message in _functions_deprecated.items(): globals()[_name] = _wrap_deprecated_function(globals()[_name], _message) for _name, _doc in _name_functions_2_4.items(): globals()[_name] = since(2.4)(_create_name_function(_name, _doc)) del _name, _doc @since(2.1) def approx_count_distinct(col, rsd=None): """Aggregate function: returns a new :class:`Column` for approximate distinct count of column `col`. :param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more efficient to use :func:`countDistinct` >>> df.agg(approx_count_distinct(df.age).alias('distinct_ages')).collect() [Row(distinct_ages=2)] """ sc = SparkContext._active_spark_context if rsd is None: jc = sc._jvm.functions.approx_count_distinct(_to_java_column(col)) else: jc = sc._jvm.functions.approx_count_distinct(_to_java_column(col), rsd) return Column(jc) @since(1.6) def broadcast(df): """Marks a DataFrame as small enough for use in broadcast joins.""" sc = SparkContext._active_spark_context return DataFrame(sc._jvm.functions.broadcast(df._jdf), df.sql_ctx) @since(1.4) def coalesce(*cols): """Returns the first column that is not null. >>> cDf = spark.createDataFrame([(None, None), (1, None), (None, 2)], ("a", "b")) >>> cDf.show() +----+----+ | a| b| +----+----+ |null|null| | 1|null| |null| 2| +----+----+ >>> cDf.select(coalesce(cDf["a"], cDf["b"])).show() +--------------+ |coalesce(a, b)| +--------------+ | null| | 1| | 2| +--------------+ >>> cDf.select('*', coalesce(cDf["a"], lit(0.0))).show() +----+----+----------------+ | a| b|coalesce(a, 0.0)| +----+----+----------------+ |null|null| 0.0| | 1|null| 1.0| |null| 2| 0.0| +----+----+----------------+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.coalesce(_to_seq(sc, cols, _to_java_column)) return Column(jc) @since(1.6) def corr(col1, col2): """Returns a new :class:`Column` for the Pearson Correlation Coefficient for ``col1`` and ``col2``. >>> a = range(20) >>> b = [2 * x for x in range(20)] >>> df = spark.createDataFrame(zip(a, b), ["a", "b"]) >>> df.agg(corr("a", "b").alias('c')).collect() [Row(c=1.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.corr(_to_java_column(col1), _to_java_column(col2))) @since(2.0) def covar_pop(col1, col2): """Returns a new :class:`Column` for the population covariance of ``col1`` and ``col2``. >>> a = [1] * 10 >>> b = [1] * 10 >>> df = spark.createDataFrame(zip(a, b), ["a", "b"]) >>> df.agg(covar_pop("a", "b").alias('c')).collect() [Row(c=0.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.covar_pop(_to_java_column(col1), _to_java_column(col2))) @since(2.0) def covar_samp(col1, col2): """Returns a new :class:`Column` for the sample covariance of ``col1`` and ``col2``. >>> a = [1] * 10 >>> b = [1] * 10 >>> df = spark.createDataFrame(zip(a, b), ["a", "b"]) >>> df.agg(covar_samp("a", "b").alias('c')).collect() [Row(c=0.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.covar_samp(_to_java_column(col1), _to_java_column(col2))) @since(1.3) def countDistinct(col, *cols): """Returns a new :class:`Column` for distinct count of ``col`` or ``cols``. >>> df.agg(countDistinct(df.age, df.name).alias('c')).collect() [Row(c=2)] >>> df.agg(countDistinct("age", "name").alias('c')).collect() [Row(c=2)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.countDistinct(_to_java_column(col), _to_seq(sc, cols, _to_java_column)) return Column(jc) @since(1.3) def first(col, ignorenulls=False): """Aggregate function: returns the first value in a group. The function by default returns the first values it sees. It will return the first non-null value it sees when ignoreNulls is set to true. If all values are null, then null is returned. .. note:: The function is non-deterministic because its results depends on order of rows which may be non-deterministic after a shuffle. """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.first(_to_java_column(col), ignorenulls) return Column(jc) @since(2.0) def grouping(col): """ Aggregate function: indicates whether a specified column in a GROUP BY list is aggregated or not, returns 1 for aggregated or 0 for not aggregated in the result set. >>> df.cube("name").agg(grouping("name"), sum("age")).orderBy("name").show() +-----+--------------+--------+ | name|grouping(name)|sum(age)| +-----+--------------+--------+ | null| 1| 7| |Alice| 0| 2| | Bob| 0| 5| +-----+--------------+--------+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.grouping(_to_java_column(col)) return Column(jc) @since(2.0) def grouping_id(*cols): """ Aggregate function: returns the level of grouping, equals to (grouping(c1) << (n-1)) + (grouping(c2) << (n-2)) + ... + grouping(cn) .. note:: The list of columns should match with grouping columns exactly, or empty (means all the grouping columns). >>> df.cube("name").agg(grouping_id(), sum("age")).orderBy("name").show() +-----+-------------+--------+ | name|grouping_id()|sum(age)| +-----+-------------+--------+ | null| 1| 7| |Alice| 0| 2| | Bob| 0| 5| +-----+-------------+--------+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.grouping_id(_to_seq(sc, cols, _to_java_column)) return Column(jc) @since(1.6) def input_file_name(): """Creates a string column for the file name of the current Spark task. """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.input_file_name()) @since(1.6) def isnan(col): """An expression that returns true iff the column is NaN. >>> df = spark.createDataFrame([(1.0, float('nan')), (float('nan'), 2.0)], ("a", "b")) >>> df.select(isnan("a").alias("r1"), isnan(df.a).alias("r2")).collect() [Row(r1=False, r2=False), Row(r1=True, r2=True)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.isnan(_to_java_column(col))) @since(1.6) def isnull(col): """An expression that returns true iff the column is null. >>> df = spark.createDataFrame([(1, None), (None, 2)], ("a", "b")) >>> df.select(isnull("a").alias("r1"), isnull(df.a).alias("r2")).collect() [Row(r1=False, r2=False), Row(r1=True, r2=True)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.isnull(_to_java_column(col))) @since(1.3) def last(col, ignorenulls=False): """Aggregate function: returns the last value in a group. The function by default returns the last values it sees. It will return the last non-null value it sees when ignoreNulls is set to true. If all values are null, then null is returned. .. note:: The function is non-deterministic because its results depends on order of rows which may be non-deterministic after a shuffle. """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.last(_to_java_column(col), ignorenulls) return Column(jc) @since(1.6) def monotonically_increasing_id(): """A column that generates monotonically increasing 64-bit integers. The generated ID is guaranteed to be monotonically increasing and unique, but not consecutive. The current implementation puts the partition ID in the upper 31 bits, and the record number within each partition in the lower 33 bits. The assumption is that the data frame has less than 1 billion partitions, and each partition has less than 8 billion records. .. note:: The function is non-deterministic because its result depends on partition IDs. As an example, consider a :class:`DataFrame` with two partitions, each with 3 records. This expression would return the following IDs: 0, 1, 2, 8589934592 (1L << 33), 8589934593, 8589934594. >>> df0 = sc.parallelize(range(2), 2).mapPartitions(lambda x: [(1,), (2,), (3,)]).toDF(['col1']) >>> df0.select(monotonically_increasing_id().alias('id')).collect() [Row(id=0), Row(id=1), Row(id=2), Row(id=8589934592), Row(id=8589934593), Row(id=8589934594)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.monotonically_increasing_id()) @since(1.6) def nanvl(col1, col2): """Returns col1 if it is not NaN, or col2 if col1 is NaN. Both inputs should be floating point columns (:class:`DoubleType` or :class:`FloatType`). >>> df = spark.createDataFrame([(1.0, float('nan')), (float('nan'), 2.0)], ("a", "b")) >>> df.select(nanvl("a", "b").alias("r1"), nanvl(df.a, df.b).alias("r2")).collect() [Row(r1=1.0, r2=1.0), Row(r1=2.0, r2=2.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.nanvl(_to_java_column(col1), _to_java_column(col2))) @ignore_unicode_prefix @since(1.4) def rand(seed=None): """Generates a random column with independent and identically distributed (i.i.d.) samples from U[0.0, 1.0]. .. note:: The function is non-deterministic in general case. >>> df.withColumn('rand', rand(seed=42) * 3).collect() [Row(age=2, name=u'Alice', rand=1.1568609015300986), Row(age=5, name=u'Bob', rand=1.403379671529166)] """ sc = SparkContext._active_spark_context if seed is not None: jc = sc._jvm.functions.rand(seed) else: jc = sc._jvm.functions.rand() return Column(jc) @ignore_unicode_prefix @since(1.4) def randn(seed=None): """Generates a column with independent and identically distributed (i.i.d.) samples from the standard normal distribution. .. note:: The function is non-deterministic in general case. >>> df.withColumn('randn', randn(seed=42)).collect() [Row(age=2, name=u'Alice', randn=-0.7556247885860078), Row(age=5, name=u'Bob', randn=-0.0861619008451133)] """ sc = SparkContext._active_spark_context if seed is not None: jc = sc._jvm.functions.randn(seed) else: jc = sc._jvm.functions.randn() return Column(jc) @since(1.5) def round(col, scale=0): """ Round the given value to `scale` decimal places using HALF_UP rounding mode if `scale` >= 0 or at integral part when `scale` < 0. >>> spark.createDataFrame([(2.5,)], ['a']).select(round('a', 0).alias('r')).collect() [Row(r=3.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.round(_to_java_column(col), scale)) @since(2.0) def bround(col, scale=0): """ Round the given value to `scale` decimal places using HALF_EVEN rounding mode if `scale` >= 0 or at integral part when `scale` < 0. >>> spark.createDataFrame([(2.5,)], ['a']).select(bround('a', 0).alias('r')).collect() [Row(r=2.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.bround(_to_java_column(col), scale)) @since(1.5) def shiftLeft(col, numBits): """Shift the given value numBits left. >>> spark.createDataFrame([(21,)], ['a']).select(shiftLeft('a', 1).alias('r')).collect() [Row(r=42)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.shiftLeft(_to_java_column(col), numBits)) @since(1.5) def shiftRight(col, numBits): """(Signed) shift the given value numBits right. >>> spark.createDataFrame([(42,)], ['a']).select(shiftRight('a', 1).alias('r')).collect() [Row(r=21)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.shiftRight(_to_java_column(col), numBits) return Column(jc) @since(1.5) def shiftRightUnsigned(col, numBits): """Unsigned shift the given value numBits right. >>> df = spark.createDataFrame([(-42,)], ['a']) >>> df.select(shiftRightUnsigned('a', 1).alias('r')).collect() [Row(r=9223372036854775787)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.shiftRightUnsigned(_to_java_column(col), numBits) return Column(jc) @since(1.6) def spark_partition_id(): """A column for partition ID. .. note:: This is indeterministic because it depends on data partitioning and task scheduling. >>> df.repartition(1).select(spark_partition_id().alias("pid")).collect() [Row(pid=0), Row(pid=0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.spark_partition_id()) @since(1.5) def expr(str): """Parses the expression string into the column that it represents >>> df.select(expr("length(name)")).collect() [Row(length(name)=5), Row(length(name)=3)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.expr(str)) @ignore_unicode_prefix @since(1.4) def struct(*cols): """Creates a new struct column. :param cols: list of column names (string) or list of :class:`Column` expressions >>> df.select(struct('age', 'name').alias("struct")).collect() [Row(struct=Row(age=2, name=u'Alice')), Row(struct=Row(age=5, name=u'Bob'))] >>> df.select(struct([df.age, df.name]).alias("struct")).collect() [Row(struct=Row(age=2, name=u'Alice')), Row(struct=Row(age=5, name=u'Bob'))] """ sc = SparkContext._active_spark_context if len(cols) == 1 and isinstance(cols[0], (list, set)): cols = cols[0] jc = sc._jvm.functions.struct(_to_seq(sc, cols, _to_java_column)) return Column(jc) @since(1.5) def greatest(*cols): """ Returns the greatest value of the list of column names, skipping null values. This function takes at least 2 parameters. It will return null iff all parameters are null. >>> df = spark.createDataFrame([(1, 4, 3)], ['a', 'b', 'c']) >>> df.select(greatest(df.a, df.b, df.c).alias("greatest")).collect() [Row(greatest=4)] """ if len(cols) < 2: raise ValueError("greatest should take at least two columns") sc = SparkContext._active_spark_context return Column(sc._jvm.functions.greatest(_to_seq(sc, cols, _to_java_column))) @since(1.5) def least(*cols): """ Returns the least value of the list of column names, skipping null values. This function takes at least 2 parameters. It will return null iff all parameters are null. >>> df = spark.createDataFrame([(1, 4, 3)], ['a', 'b', 'c']) >>> df.select(least(df.a, df.b, df.c).alias("least")).collect() [Row(least=1)] """ if len(cols) < 2: raise ValueError("least should take at least two columns") sc = SparkContext._active_spark_context return Column(sc._jvm.functions.least(_to_seq(sc, cols, _to_java_column))) @since(1.4) def when(condition, value): """Evaluates a list of conditions and returns one of multiple possible result expressions. If :func:`Column.otherwise` is not invoked, None is returned for unmatched conditions. :param condition: a boolean :class:`Column` expression. :param value: a literal value, or a :class:`Column` expression. >>> df.select(when(df['age'] == 2, 3).otherwise(4).alias("age")).collect() [Row(age=3), Row(age=4)] >>> df.select(when(df.age == 2, df.age + 1).alias("age")).collect() [Row(age=3), Row(age=None)] """ sc = SparkContext._active_spark_context if not isinstance(condition, Column): raise TypeError("condition should be a Column") v = value._jc if isinstance(value, Column) else value jc = sc._jvm.functions.when(condition._jc, v) return Column(jc) @since(1.5) def log(arg1, arg2=None): """Returns the first argument-based logarithm of the second argument. If there is only one argument, then this takes the natural logarithm of the argument. >>> df.select(log(10.0, df.age).alias('ten')).rdd.map(lambda l: str(l.ten)[:7]).collect() ['0.30102', '0.69897'] >>> df.select(log(df.age).alias('e')).rdd.map(lambda l: str(l.e)[:7]).collect() ['0.69314', '1.60943'] """ sc = SparkContext._active_spark_context if arg2 is None: jc = sc._jvm.functions.log(_to_java_column(arg1)) else: jc = sc._jvm.functions.log(arg1, _to_java_column(arg2)) return Column(jc) @since(1.5) def log2(col): """Returns the base-2 logarithm of the argument. >>> spark.createDataFrame([(4,)], ['a']).select(log2('a').alias('log2')).collect() [Row(log2=2.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.log2(_to_java_column(col))) @since(1.5) @ignore_unicode_prefix def conv(col, fromBase, toBase): """ Convert a number in a string column from one base to another. >>> df = spark.createDataFrame([("010101",)], ['n']) >>> df.select(conv(df.n, 2, 16).alias('hex')).collect() [Row(hex=u'15')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.conv(_to_java_column(col), fromBase, toBase)) @since(1.5) def factorial(col): """ Computes the factorial of the given value. >>> df = spark.createDataFrame([(5,)], ['n']) >>> df.select(factorial(df.n).alias('f')).collect() [Row(f=120)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.factorial(_to_java_column(col))) # --------------- Window functions ------------------------ @since(1.4) def lag(col, offset=1, default=None): """ Window function: returns the value that is `offset` rows before the current row, and `defaultValue` if there is less than `offset` rows before the current row. For example, an `offset` of one will return the previous row at any given point in the window partition. This is equivalent to the LAG function in SQL. :param col: name of column or expression :param offset: number of row to extend :param default: default value """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.lag(_to_java_column(col), offset, default)) @since(1.4) def lead(col, offset=1, default=None): """ Window function: returns the value that is `offset` rows after the current row, and `defaultValue` if there is less than `offset` rows after the current row. For example, an `offset` of one will return the next row at any given point in the window partition. This is equivalent to the LEAD function in SQL. :param col: name of column or expression :param offset: number of row to extend :param default: default value """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.lead(_to_java_column(col), offset, default)) @since(1.4) def ntile(n): """ Window function: returns the ntile group id (from 1 to `n` inclusive) in an ordered window partition. For example, if `n` is 4, the first quarter of the rows will get value 1, the second quarter will get 2, the third quarter will get 3, and the last quarter will get 4. This is equivalent to the NTILE function in SQL. :param n: an integer """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.ntile(int(n))) # ---------------------- Date/Timestamp functions ------------------------------ @since(1.5) def current_date(): """ Returns the current date as a :class:`DateType` column. """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.current_date()) def current_timestamp(): """ Returns the current timestamp as a :class:`TimestampType` column. """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.current_timestamp()) @ignore_unicode_prefix @since(1.5) def date_format(date, format): """ Converts a date/timestamp/string to a value of string in the format specified by the date format given by the second argument. A pattern could be for instance `dd.MM.yyyy` and could return a string like '18.03.1993'. All pattern letters of the Java class `java.time.format.DateTimeFormatter` can be used. .. note:: Use when ever possible specialized functions like `year`. These benefit from a specialized implementation. >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(date_format('dt', 'MM/dd/yyy').alias('date')).collect() [Row(date=u'04/08/2015')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.date_format(_to_java_column(date), format)) @since(1.5) def year(col): """ Extract the year of a given date as integer. >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(year('dt').alias('year')).collect() [Row(year=2015)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.year(_to_java_column(col))) @since(1.5) def quarter(col): """ Extract the quarter of a given date as integer. >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(quarter('dt').alias('quarter')).collect() [Row(quarter=2)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.quarter(_to_java_column(col))) @since(1.5) def month(col): """ Extract the month of a given date as integer. >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(month('dt').alias('month')).collect() [Row(month=4)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.month(_to_java_column(col))) @since(2.3) def dayofweek(col): """ Extract the day of the week of a given date as integer. >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(dayofweek('dt').alias('day')).collect() [Row(day=4)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.dayofweek(_to_java_column(col))) @since(1.5) def dayofmonth(col): """ Extract the day of the month of a given date as integer. >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(dayofmonth('dt').alias('day')).collect() [Row(day=8)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.dayofmonth(_to_java_column(col))) @since(1.5) def dayofyear(col): """ Extract the day of the year of a given date as integer. >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(dayofyear('dt').alias('day')).collect() [Row(day=98)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.dayofyear(_to_java_column(col))) @since(1.5) def hour(col): """ Extract the hours of a given date as integer. >>> df = spark.createDataFrame([('2015-04-08 13:08:15',)], ['ts']) >>> df.select(hour('ts').alias('hour')).collect() [Row(hour=13)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.hour(_to_java_column(col))) @since(1.5) def minute(col): """ Extract the minutes of a given date as integer. >>> df = spark.createDataFrame([('2015-04-08 13:08:15',)], ['ts']) >>> df.select(minute('ts').alias('minute')).collect() [Row(minute=8)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.minute(_to_java_column(col))) @since(1.5) def second(col): """ Extract the seconds of a given date as integer. >>> df = spark.createDataFrame([('2015-04-08 13:08:15',)], ['ts']) >>> df.select(second('ts').alias('second')).collect() [Row(second=15)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.second(_to_java_column(col))) @since(1.5) def weekofyear(col): """ Extract the week number of a given date as integer. >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(weekofyear(df.dt).alias('week')).collect() [Row(week=15)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.weekofyear(_to_java_column(col))) @since(1.5) def date_add(start, days): """ Returns the date that is `days` days after `start` >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(date_add(df.dt, 1).alias('next_date')).collect() [Row(next_date=datetime.date(2015, 4, 9))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.date_add(_to_java_column(start), days)) @since(1.5) def date_sub(start, days): """ Returns the date that is `days` days before `start` >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(date_sub(df.dt, 1).alias('prev_date')).collect() [Row(prev_date=datetime.date(2015, 4, 7))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.date_sub(_to_java_column(start), days)) @since(1.5) def datediff(end, start): """ Returns the number of days from `start` to `end`. >>> df = spark.createDataFrame([('2015-04-08','2015-05-10')], ['d1', 'd2']) >>> df.select(datediff(df.d2, df.d1).alias('diff')).collect() [Row(diff=32)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.datediff(_to_java_column(end), _to_java_column(start))) @since(1.5) def add_months(start, months): """ Returns the date that is `months` months after `start` >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(add_months(df.dt, 1).alias('next_month')).collect() [Row(next_month=datetime.date(2015, 5, 8))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.add_months(_to_java_column(start), months)) @since(1.5) def months_between(date1, date2, roundOff=True): """ Returns number of months between dates date1 and date2. If date1 is later than date2, then the result is positive. If date1 and date2 are on the same day of month, or both are the last day of month, returns an integer (time of day will be ignored). The result is rounded off to 8 digits unless `roundOff` is set to `False`. >>> df = spark.createDataFrame([('1997-02-28 10:30:00', '1996-10-30')], ['date1', 'date2']) >>> df.select(months_between(df.date1, df.date2).alias('months')).collect() [Row(months=3.94959677)] >>> df.select(months_between(df.date1, df.date2, False).alias('months')).collect() [Row(months=3.9495967741935485)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.months_between( _to_java_column(date1), _to_java_column(date2), roundOff)) @since(2.2) def to_date(col, format=None): """Converts a :class:`Column` of :class:`pyspark.sql.types.StringType` or :class:`pyspark.sql.types.TimestampType` into :class:`pyspark.sql.types.DateType` using the optionally specified format. Specify formats according to `DateTimeFormatter <https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html>`_. # noqa By default, it follows casting rules to :class:`pyspark.sql.types.DateType` if the format is omitted (equivalent to ``col.cast("date")``). >>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t']) >>> df.select(to_date(df.t).alias('date')).collect() [Row(date=datetime.date(1997, 2, 28))] >>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t']) >>> df.select(to_date(df.t, 'yyyy-MM-dd HH:mm:ss').alias('date')).collect() [Row(date=datetime.date(1997, 2, 28))] """ sc = SparkContext._active_spark_context if format is None: jc = sc._jvm.functions.to_date(_to_java_column(col)) else: jc = sc._jvm.functions.to_date(_to_java_column(col), format) return Column(jc) @since(2.2) def to_timestamp(col, format=None): """Converts a :class:`Column` of :class:`pyspark.sql.types.StringType` or :class:`pyspark.sql.types.TimestampType` into :class:`pyspark.sql.types.DateType` using the optionally specified format. Specify formats according to `DateTimeFormatter <https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html>`_. # noqa By default, it follows casting rules to :class:`pyspark.sql.types.TimestampType` if the format is omitted (equivalent to ``col.cast("timestamp")``). >>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t']) >>> df.select(to_timestamp(df.t).alias('dt')).collect() [Row(dt=datetime.datetime(1997, 2, 28, 10, 30))] >>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t']) >>> df.select(to_timestamp(df.t, 'yyyy-MM-dd HH:mm:ss').alias('dt')).collect() [Row(dt=datetime.datetime(1997, 2, 28, 10, 30))] """ sc = SparkContext._active_spark_context if format is None: jc = sc._jvm.functions.to_timestamp(_to_java_column(col)) else: jc = sc._jvm.functions.to_timestamp(_to_java_column(col), format) return Column(jc) @since(1.5) def trunc(date, format): """ Returns date truncated to the unit specified by the format. :param format: 'year', 'yyyy', 'yy' or 'month', 'mon', 'mm' >>> df = spark.createDataFrame([('1997-02-28',)], ['d']) >>> df.select(trunc(df.d, 'year').alias('year')).collect() [Row(year=datetime.date(1997, 1, 1))] >>> df.select(trunc(df.d, 'mon').alias('month')).collect() [Row(month=datetime.date(1997, 2, 1))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.trunc(_to_java_column(date), format)) @since(2.3) def date_trunc(format, timestamp): """ Returns timestamp truncated to the unit specified by the format. :param format: 'year', 'yyyy', 'yy', 'month', 'mon', 'mm', 'day', 'dd', 'hour', 'minute', 'second', 'week', 'quarter' >>> df = spark.createDataFrame([('1997-02-28 05:02:11',)], ['t']) >>> df.select(date_trunc('year', df.t).alias('year')).collect() [Row(year=datetime.datetime(1997, 1, 1, 0, 0))] >>> df.select(date_trunc('mon', df.t).alias('month')).collect() [Row(month=datetime.datetime(1997, 2, 1, 0, 0))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.date_trunc(format, _to_java_column(timestamp))) @since(1.5) def next_day(date, dayOfWeek): """ Returns the first date which is later than the value of the date column. Day of the week parameter is case insensitive, and accepts: "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun". >>> df = spark.createDataFrame([('2015-07-27',)], ['d']) >>> df.select(next_day(df.d, 'Sun').alias('date')).collect() [Row(date=datetime.date(2015, 8, 2))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.next_day(_to_java_column(date), dayOfWeek)) @since(1.5) def last_day(date): """ Returns the last day of the month which the given date belongs to. >>> df = spark.createDataFrame([('1997-02-10',)], ['d']) >>> df.select(last_day(df.d).alias('date')).collect() [Row(date=datetime.date(1997, 2, 28))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.last_day(_to_java_column(date))) @ignore_unicode_prefix @since(1.5) def from_unixtime(timestamp, format="yyyy-MM-dd HH:mm:ss"): """ Converts the number of seconds from unix epoch (1970-01-01 00:00:00 UTC) to a string representing the timestamp of that moment in the current system time zone in the given format. >>> spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles") >>> time_df = spark.createDataFrame([(1428476400,)], ['unix_time']) >>> time_df.select(from_unixtime('unix_time').alias('ts')).collect() [Row(ts=u'2015-04-08 00:00:00')] >>> spark.conf.unset("spark.sql.session.timeZone") """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.from_unixtime(_to_java_column(timestamp), format)) @since(1.5) def unix_timestamp(timestamp=None, format='yyyy-MM-dd HH:mm:ss'): """ Convert time string with given pattern ('yyyy-MM-dd HH:mm:ss', by default) to Unix time stamp (in seconds), using the default timezone and the default locale, return null if fail. if `timestamp` is None, then it returns current timestamp. >>> spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles") >>> time_df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> time_df.select(unix_timestamp('dt', 'yyyy-MM-dd').alias('unix_time')).collect() [Row(unix_time=1428476400)] >>> spark.conf.unset("spark.sql.session.timeZone") """ sc = SparkContext._active_spark_context if timestamp is None: return Column(sc._jvm.functions.unix_timestamp()) return Column(sc._jvm.functions.unix_timestamp(_to_java_column(timestamp), format)) @since(1.5) def from_utc_timestamp(timestamp, tz): """ This is a common function for databases supporting TIMESTAMP WITHOUT TIMEZONE. This function takes a timestamp which is timezone-agnostic, and interprets it as a timestamp in UTC, and renders that timestamp as a timestamp in the given time zone. However, timestamp in Spark represents number of microseconds from the Unix epoch, which is not timezone-agnostic. So in Spark this function just shift the timestamp value from UTC timezone to the given timezone. This function may return confusing result if the input is a string with timezone, e.g. '2018-03-13T06:18:23+00:00'. The reason is that, Spark firstly cast the string to timestamp according to the timezone in the string, and finally display the result by converting the timestamp to string according to the session local timezone. :param timestamp: the column that contains timestamps :param tz: a string that has the ID of timezone, e.g. "GMT", "America/Los_Angeles", etc .. versionchanged:: 2.4 `tz` can take a :class:`Column` containing timezone ID strings. >>> df = spark.createDataFrame([('1997-02-28 10:30:00', 'JST')], ['ts', 'tz']) >>> df.select(from_utc_timestamp(df.ts, "PST").alias('local_time')).collect() [Row(local_time=datetime.datetime(1997, 2, 28, 2, 30))] >>> df.select(from_utc_timestamp(df.ts, df.tz).alias('local_time')).collect() [Row(local_time=datetime.datetime(1997, 2, 28, 19, 30))] """ sc = SparkContext._active_spark_context if isinstance(tz, Column): tz = _to_java_column(tz) return Column(sc._jvm.functions.from_utc_timestamp(_to_java_column(timestamp), tz)) @since(1.5) def to_utc_timestamp(timestamp, tz): """ This is a common function for databases supporting TIMESTAMP WITHOUT TIMEZONE. This function takes a timestamp which is timezone-agnostic, and interprets it as a timestamp in the given timezone, and renders that timestamp as a timestamp in UTC. However, timestamp in Spark represents number of microseconds from the Unix epoch, which is not timezone-agnostic. So in Spark this function just shift the timestamp value from the given timezone to UTC timezone. This function may return confusing result if the input is a string with timezone, e.g. '2018-03-13T06:18:23+00:00'. The reason is that, Spark firstly cast the string to timestamp according to the timezone in the string, and finally display the result by converting the timestamp to string according to the session local timezone. :param timestamp: the column that contains timestamps :param tz: a string that has the ID of timezone, e.g. "GMT", "America/Los_Angeles", etc .. versionchanged:: 2.4 `tz` can take a :class:`Column` containing timezone ID strings. >>> df = spark.createDataFrame([('1997-02-28 10:30:00', 'JST')], ['ts', 'tz']) >>> df.select(to_utc_timestamp(df.ts, "PST").alias('utc_time')).collect() [Row(utc_time=datetime.datetime(1997, 2, 28, 18, 30))] >>> df.select(to_utc_timestamp(df.ts, df.tz).alias('utc_time')).collect() [Row(utc_time=datetime.datetime(1997, 2, 28, 1, 30))] """ sc = SparkContext._active_spark_context if isinstance(tz, Column): tz = _to_java_column(tz) return Column(sc._jvm.functions.to_utc_timestamp(_to_java_column(timestamp), tz)) @since(2.0) @ignore_unicode_prefix def window(timeColumn, windowDuration, slideDuration=None, startTime=None): """Bucketize rows into one or more time windows given a timestamp specifying column. Window starts are inclusive but the window ends are exclusive, e.g. 12:05 will be in the window [12:05,12:10) but not in [12:00,12:05). Windows can support microsecond precision. Windows in the order of months are not supported. The time column must be of :class:`pyspark.sql.types.TimestampType`. Durations are provided as strings, e.g. '1 second', '1 day 12 hours', '2 minutes'. Valid interval strings are 'week', 'day', 'hour', 'minute', 'second', 'millisecond', 'microsecond'. If the ``slideDuration`` is not provided, the windows will be tumbling windows. The startTime is the offset with respect to 1970-01-01 00:00:00 UTC with which to start window intervals. For example, in order to have hourly tumbling windows that start 15 minutes past the hour, e.g. 12:15-13:15, 13:15-14:15... provide `startTime` as `15 minutes`. The output column will be a struct called 'window' by default with the nested columns 'start' and 'end', where 'start' and 'end' will be of :class:`pyspark.sql.types.TimestampType`. >>> df = spark.createDataFrame([("2016-03-11 09:00:07", 1)]).toDF("date", "val") >>> w = df.groupBy(window("date", "5 seconds")).agg(sum("val").alias("sum")) >>> w.select(w.window.start.cast("string").alias("start"), ... w.window.end.cast("string").alias("end"), "sum").collect() [Row(start=u'2016-03-11 09:00:05', end=u'2016-03-11 09:00:10', sum=1)] """ def check_string_field(field, fieldName): if not field or type(field) is not str: raise TypeError("%s should be provided as a string" % fieldName) sc = SparkContext._active_spark_context time_col = _to_java_column(timeColumn) check_string_field(windowDuration, "windowDuration") if slideDuration and startTime: check_string_field(slideDuration, "slideDuration") check_string_field(startTime, "startTime") res = sc._jvm.functions.window(time_col, windowDuration, slideDuration, startTime) elif slideDuration: check_string_field(slideDuration, "slideDuration") res = sc._jvm.functions.window(time_col, windowDuration, slideDuration) elif startTime: check_string_field(startTime, "startTime") res = sc._jvm.functions.window(time_col, windowDuration, windowDuration, startTime) else: res = sc._jvm.functions.window(time_col, windowDuration) return Column(res) # ---------------------------- misc functions ---------------------------------- @since(1.5) @ignore_unicode_prefix def crc32(col): """ Calculates the cyclic redundancy check value (CRC32) of a binary column and returns the value as a bigint. >>> spark.createDataFrame([('ABC',)], ['a']).select(crc32('a').alias('crc32')).collect() [Row(crc32=2743272264)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.crc32(_to_java_column(col))) @ignore_unicode_prefix @since(1.5) def md5(col): """Calculates the MD5 digest and returns the value as a 32 character hex string. >>> spark.createDataFrame([('ABC',)], ['a']).select(md5('a').alias('hash')).collect() [Row(hash=u'902fbdd2b1df0c4f70b4a5d23525e932')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.md5(_to_java_column(col)) return Column(jc) @ignore_unicode_prefix @since(1.5) def sha1(col): """Returns the hex string result of SHA-1. >>> spark.createDataFrame([('ABC',)], ['a']).select(sha1('a').alias('hash')).collect() [Row(hash=u'3c01bdbb26f358bab27f267924aa2c9a03fcfdb8')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.sha1(_to_java_column(col)) return Column(jc) @ignore_unicode_prefix @since(1.5) def sha2(col, numBits): """Returns the hex string result of SHA-2 family of hash functions (SHA-224, SHA-256, SHA-384, and SHA-512). The numBits indicates the desired bit length of the result, which must have a value of 224, 256, 384, 512, or 0 (which is equivalent to 256). >>> digests = df.select(sha2(df.name, 256).alias('s')).collect() >>> digests[0] Row(s=u'3bc51062973c458d5a6f2d8d64a023246354ad7e064b1e4e009ec8a0699a3043') >>> digests[1] Row(s=u'cd9fb1e148ccd8442e5aa74904cc73bf6fb54d1d54d333bd596aa9bb4bb4e961') """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.sha2(_to_java_column(col), numBits) return Column(jc) @since(2.0) def hash(*cols): """Calculates the hash code of given columns, and returns the result as an int column. >>> spark.createDataFrame([('ABC',)], ['a']).select(hash('a').alias('hash')).collect() [Row(hash=-757602832)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.hash(_to_seq(sc, cols, _to_java_column)) return Column(jc) # ---------------------- String/Binary functions ------------------------------ _string_functions = { 'ascii': 'Computes the numeric value of the first character of the string column.', 'base64': 'Computes the BASE64 encoding of a binary column and returns it as a string column.', 'unbase64': 'Decodes a BASE64 encoded string column and returns it as a binary column.', 'ltrim': 'Trim the spaces from left end for the specified string value.', 'rtrim': 'Trim the spaces from right end for the specified string value.', 'trim': 'Trim the spaces from both ends for the specified string column.', } for _name, _doc in _string_functions.items(): globals()[_name] = since(1.5)(_create_function(_name, _doc)) del _name, _doc @since(1.5) @ignore_unicode_prefix def concat_ws(sep, *cols): """ Concatenates multiple input string columns together into a single string column, using the given separator. >>> df = spark.createDataFrame([('abcd','123')], ['s', 'd']) >>> df.select(concat_ws('-', df.s, df.d).alias('s')).collect() [Row(s=u'abcd-123')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.concat_ws(sep, _to_seq(sc, cols, _to_java_column))) @since(1.5) def decode(col, charset): """ Computes the first argument into a string from a binary using the provided character set (one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16'). """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.decode(_to_java_column(col), charset)) @since(1.5) def encode(col, charset): """ Computes the first argument into a binary from a string using the provided character set (one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16'). """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.encode(_to_java_column(col), charset)) @ignore_unicode_prefix @since(1.5) def format_number(col, d): """ Formats the number X to a format like '#,--#,--#.--', rounded to d decimal places with HALF_EVEN round mode, and returns the result as a string. :param col: the column name of the numeric value to be formatted :param d: the N decimal places >>> spark.createDataFrame([(5,)], ['a']).select(format_number('a', 4).alias('v')).collect() [Row(v=u'5.0000')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.format_number(_to_java_column(col), d)) @ignore_unicode_prefix @since(1.5) def format_string(format, *cols): """ Formats the arguments in printf-style and returns the result as a string column. :param col: the column name of the numeric value to be formatted :param d: the N decimal places >>> df = spark.createDataFrame([(5, "hello")], ['a', 'b']) >>> df.select(format_string('%d %s', df.a, df.b).alias('v')).collect() [Row(v=u'5 hello')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.format_string(format, _to_seq(sc, cols, _to_java_column))) @since(1.5) def instr(str, substr): """ Locate the position of the first occurrence of substr column in the given string. Returns null if either of the arguments are null. .. note:: The position is not zero based, but 1 based index. Returns 0 if substr could not be found in str. >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(instr(df.s, 'b').alias('s')).collect() [Row(s=2)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.instr(_to_java_column(str), substr)) @since(1.5) @ignore_unicode_prefix def substring(str, pos, len): """ Substring starts at `pos` and is of length `len` when str is String type or returns the slice of byte array that starts at `pos` in byte and is of length `len` when str is Binary type. .. note:: The position is not zero based, but 1 based index. >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(substring(df.s, 1, 2).alias('s')).collect() [Row(s=u'ab')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.substring(_to_java_column(str), pos, len)) @since(1.5) @ignore_unicode_prefix def substring_index(str, delim, count): """ Returns the substring from string str before count occurrences of the delimiter delim. If count is positive, everything the left of the final delimiter (counting from left) is returned. If count is negative, every to the right of the final delimiter (counting from the right) is returned. substring_index performs a case-sensitive match when searching for delim. >>> df = spark.createDataFrame([('a.b.c.d',)], ['s']) >>> df.select(substring_index(df.s, '.', 2).alias('s')).collect() [Row(s=u'a.b')] >>> df.select(substring_index(df.s, '.', -3).alias('s')).collect() [Row(s=u'b.c.d')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.substring_index(_to_java_column(str), delim, count)) @ignore_unicode_prefix @since(1.5) def levenshtein(left, right): """Computes the Levenshtein distance of the two given strings. >>> df0 = spark.createDataFrame([('kitten', 'sitting',)], ['l', 'r']) >>> df0.select(levenshtein('l', 'r').alias('d')).collect() [Row(d=3)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.levenshtein(_to_java_column(left), _to_java_column(right)) return Column(jc) @since(1.5) def locate(substr, str, pos=1): """ Locate the position of the first occurrence of substr in a string column, after position pos. .. note:: The position is not zero based, but 1 based index. Returns 0 if substr could not be found in str. :param substr: a string :param str: a Column of :class:`pyspark.sql.types.StringType` :param pos: start position (zero based) >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(locate('b', df.s, 1).alias('s')).collect() [Row(s=2)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.locate(substr, _to_java_column(str), pos)) @since(1.5) @ignore_unicode_prefix def lpad(col, len, pad): """ Left-pad the string column to width `len` with `pad`. >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(lpad(df.s, 6, '#').alias('s')).collect() [Row(s=u'##abcd')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.lpad(_to_java_column(col), len, pad)) @since(1.5) @ignore_unicode_prefix def rpad(col, len, pad): """ Right-pad the string column to width `len` with `pad`. >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(rpad(df.s, 6, '#').alias('s')).collect() [Row(s=u'abcd##')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.rpad(_to_java_column(col), len, pad)) @since(1.5) @ignore_unicode_prefix def repeat(col, n): """ Repeats a string column n times, and returns it as a new string column. >>> df = spark.createDataFrame([('ab',)], ['s',]) >>> df.select(repeat(df.s, 3).alias('s')).collect() [Row(s=u'ababab')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.repeat(_to_java_column(col), n)) @since(1.5) @ignore_unicode_prefix def split(str, pattern, limit=-1): """ Splits str around matches of the given pattern. :param str: a string expression to split :param pattern: a string representing a regular expression. The regex string should be a Java regular expression. :param limit: an integer which controls the number of times `pattern` is applied. * ``limit > 0``: The resulting array's length will not be more than `limit`, and the resulting array's last entry will contain all input beyond the last matched pattern. * ``limit <= 0``: `pattern` will be applied as many times as possible, and the resulting array can be of any size. .. versionchanged:: 3.0 `split` now takes an optional `limit` field. If not provided, default limit value is -1. >>> df = spark.createDataFrame([('oneAtwoBthreeC',)], ['s',]) >>> df.select(split(df.s, '[ABC]', 2).alias('s')).collect() [Row(s=[u'one', u'twoBthreeC'])] >>> df.select(split(df.s, '[ABC]', -1).alias('s')).collect() [Row(s=[u'one', u'two', u'three', u''])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.split(_to_java_column(str), pattern, limit)) @ignore_unicode_prefix @since(1.5) def regexp_extract(str, pattern, idx): r"""Extract a specific group matched by a Java regex, from the specified string column. If the regex did not match, or the specified group did not match, an empty string is returned. >>> df = spark.createDataFrame([('100-200',)], ['str']) >>> df.select(regexp_extract('str', r'(\d+)-(\d+)', 1).alias('d')).collect() [Row(d=u'100')] >>> df = spark.createDataFrame([('foo',)], ['str']) >>> df.select(regexp_extract('str', r'(\d+)', 1).alias('d')).collect() [Row(d=u'')] >>> df = spark.createDataFrame([('aaaac',)], ['str']) >>> df.select(regexp_extract('str', '(a+)(b)?(c)', 2).alias('d')).collect() [Row(d=u'')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.regexp_extract(_to_java_column(str), pattern, idx) return Column(jc) @ignore_unicode_prefix @since(1.5) def regexp_replace(str, pattern, replacement): r"""Replace all substrings of the specified string value that match regexp with rep. >>> df = spark.createDataFrame([('100-200',)], ['str']) >>> df.select(regexp_replace('str', r'(\d+)', '--').alias('d')).collect() [Row(d=u'-----')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.regexp_replace(_to_java_column(str), pattern, replacement) return Column(jc) @ignore_unicode_prefix @since(1.5) def initcap(col): """Translate the first letter of each word to upper case in the sentence. >>> spark.createDataFrame([('ab cd',)], ['a']).select(initcap("a").alias('v')).collect() [Row(v=u'Ab Cd')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.initcap(_to_java_column(col))) @since(1.5) @ignore_unicode_prefix def soundex(col): """ Returns the SoundEx encoding for a string >>> df = spark.createDataFrame([("Peters",),("Uhrbach",)], ['name']) >>> df.select(soundex(df.name).alias("soundex")).collect() [Row(soundex=u'P362'), Row(soundex=u'U612')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.soundex(_to_java_column(col))) @ignore_unicode_prefix @since(1.5) def bin(col): """Returns the string representation of the binary value of the given column. >>> df.select(bin(df.age).alias('c')).collect() [Row(c=u'10'), Row(c=u'101')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.bin(_to_java_column(col)) return Column(jc) @ignore_unicode_prefix @since(1.5) def hex(col): """Computes hex value of the given column, which could be :class:`pyspark.sql.types.StringType`, :class:`pyspark.sql.types.BinaryType`, :class:`pyspark.sql.types.IntegerType` or :class:`pyspark.sql.types.LongType`. >>> spark.createDataFrame([('ABC', 3)], ['a', 'b']).select(hex('a'), hex('b')).collect() [Row(hex(a)=u'414243', hex(b)=u'3')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.hex(_to_java_column(col)) return Column(jc) @ignore_unicode_prefix @since(1.5) def unhex(col): """Inverse of hex. Interprets each pair of characters as a hexadecimal number and converts to the byte representation of number. >>> spark.createDataFrame([('414243',)], ['a']).select(unhex('a')).collect() [Row(unhex(a)=bytearray(b'ABC'))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.unhex(_to_java_column(col))) @ignore_unicode_prefix @since(1.5) def length(col): """Computes the character length of string data or number of bytes of binary data. The length of character data includes the trailing spaces. The length of binary data includes binary zeros. >>> spark.createDataFrame([('ABC ',)], ['a']).select(length('a').alias('length')).collect() [Row(length=4)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.length(_to_java_column(col))) @ignore_unicode_prefix @since(1.5) def translate(srcCol, matching, replace): """A function translate any character in the `srcCol` by a character in `matching`. The characters in `replace` is corresponding to the characters in `matching`. The translate will happen when any character in the string matching with the character in the `matching`. >>> spark.createDataFrame([('translate',)], ['a']).select(translate('a', "rnlt", "123") \\ ... .alias('r')).collect() [Row(r=u'1a2s3ae')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.translate(_to_java_column(srcCol), matching, replace)) # ---------------------- Collection functions ------------------------------ @ignore_unicode_prefix @since(2.0) def create_map(*cols): """Creates a new map column. :param cols: list of column names (string) or list of :class:`Column` expressions that are grouped as key-value pairs, e.g. (key1, value1, key2, value2, ...). >>> df.select(create_map('name', 'age').alias("map")).collect() [Row(map={u'Alice': 2}), Row(map={u'Bob': 5})] >>> df.select(create_map([df.name, df.age]).alias("map")).collect() [Row(map={u'Alice': 2}), Row(map={u'Bob': 5})] """ sc = SparkContext._active_spark_context if len(cols) == 1 and isinstance(cols[0], (list, set)): cols = cols[0] jc = sc._jvm.functions.map(_to_seq(sc, cols, _to_java_column)) return Column(jc) @since(2.4) def map_from_arrays(col1, col2): """Creates a new map from two arrays. :param col1: name of column containing a set of keys. All elements should not be null :param col2: name of column containing a set of values >>> df = spark.createDataFrame([([2, 5], ['a', 'b'])], ['k', 'v']) >>> df.select(map_from_arrays(df.k, df.v).alias("map")).show() +----------------+ | map| +----------------+ |[2 -> a, 5 -> b]| +----------------+ """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.map_from_arrays(_to_java_column(col1), _to_java_column(col2))) @since(1.4) def array(*cols): """Creates a new array column. :param cols: list of column names (string) or list of :class:`Column` expressions that have the same data type. >>> df.select(array('age', 'age').alias("arr")).collect() [Row(arr=[2, 2]), Row(arr=[5, 5])] >>> df.select(array([df.age, df.age]).alias("arr")).collect() [Row(arr=[2, 2]), Row(arr=[5, 5])] """ sc = SparkContext._active_spark_context if len(cols) == 1 and isinstance(cols[0], (list, set)): cols = cols[0] jc = sc._jvm.functions.array(_to_seq(sc, cols, _to_java_column)) return Column(jc) @since(1.5) def array_contains(col, value): """ Collection function: returns null if the array is null, true if the array contains the given value, and false otherwise. :param col: name of column containing array :param value: value to check for in array >>> df = spark.createDataFrame([(["a", "b", "c"],), ([],)], ['data']) >>> df.select(array_contains(df.data, "a")).collect() [Row(array_contains(data, a)=True), Row(array_contains(data, a)=False)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_contains(_to_java_column(col), value)) @since(2.4) def arrays_overlap(a1, a2): """ Collection function: returns true if the arrays contain any common non-null element; if not, returns null if both the arrays are non-empty and any of them contains a null element; returns false otherwise. >>> df = spark.createDataFrame([(["a", "b"], ["b", "c"]), (["a"], ["b", "c"])], ['x', 'y']) >>> df.select(arrays_overlap(df.x, df.y).alias("overlap")).collect() [Row(overlap=True), Row(overlap=False)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.arrays_overlap(_to_java_column(a1), _to_java_column(a2))) @since(2.4) def slice(x, start, length): """ Collection function: returns an array containing all the elements in `x` from index `start` (or starting from the end if `start` is negative) with the specified `length`. >>> df = spark.createDataFrame([([1, 2, 3],), ([4, 5],)], ['x']) >>> df.select(slice(df.x, 2, 2).alias("sliced")).collect() [Row(sliced=[2, 3]), Row(sliced=[5])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.slice(_to_java_column(x), start, length)) @ignore_unicode_prefix @since(2.4) def array_join(col, delimiter, null_replacement=None): """ Concatenates the elements of `column` using the `delimiter`. Null values are replaced with `null_replacement` if set, otherwise they are ignored. >>> df = spark.createDataFrame([(["a", "b", "c"],), (["a", None],)], ['data']) >>> df.select(array_join(df.data, ",").alias("joined")).collect() [Row(joined=u'a,b,c'), Row(joined=u'a')] >>> df.select(array_join(df.data, ",", "NULL").alias("joined")).collect() [Row(joined=u'a,b,c'), Row(joined=u'a,NULL')] """ sc = SparkContext._active_spark_context if null_replacement is None: return Column(sc._jvm.functions.array_join(_to_java_column(col), delimiter)) else: return Column(sc._jvm.functions.array_join( _to_java_column(col), delimiter, null_replacement)) @since(1.5) @ignore_unicode_prefix def concat(*cols): """ Concatenates multiple input columns together into a single column. The function works with strings, binary and compatible array columns. >>> df = spark.createDataFrame([('abcd','123')], ['s', 'd']) >>> df.select(concat(df.s, df.d).alias('s')).collect() [Row(s=u'abcd123')] >>> df = spark.createDataFrame([([1, 2], [3, 4], [5]), ([1, 2], None, [3])], ['a', 'b', 'c']) >>> df.select(concat(df.a, df.b, df.c).alias("arr")).collect() [Row(arr=[1, 2, 3, 4, 5]), Row(arr=None)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.concat(_to_seq(sc, cols, _to_java_column))) @since(2.4) def array_position(col, value): """ Collection function: Locates the position of the first occurrence of the given value in the given array. Returns null if either of the arguments are null. .. note:: The position is not zero based, but 1 based index. Returns 0 if the given value could not be found in the array. >>> df = spark.createDataFrame([(["c", "b", "a"],), ([],)], ['data']) >>> df.select(array_position(df.data, "a")).collect() [Row(array_position(data, a)=3), Row(array_position(data, a)=0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_position(_to_java_column(col), value)) @ignore_unicode_prefix @since(2.4) def element_at(col, extraction): """ Collection function: Returns element of array at given index in extraction if col is array. Returns value for the given key in extraction if col is map. :param col: name of column containing array or map :param extraction: index to check for in array or key to check for in map .. note:: The position is not zero based, but 1 based index. >>> df = spark.createDataFrame([(["a", "b", "c"],), ([],)], ['data']) >>> df.select(element_at(df.data, 1)).collect() [Row(element_at(data, 1)=u'a'), Row(element_at(data, 1)=None)] >>> df = spark.createDataFrame([({"a": 1.0, "b": 2.0},), ({},)], ['data']) >>> df.select(element_at(df.data, "a")).collect() [Row(element_at(data, a)=1.0), Row(element_at(data, a)=None)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.element_at(_to_java_column(col), extraction)) @since(2.4) def array_remove(col, element): """ Collection function: Remove all elements that equal to element from the given array. :param col: name of column containing array :param element: element to be removed from the array >>> df = spark.createDataFrame([([1, 2, 3, 1, 1],), ([],)], ['data']) >>> df.select(array_remove(df.data, 1)).collect() [Row(array_remove(data, 1)=[2, 3]), Row(array_remove(data, 1)=[])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_remove(_to_java_column(col), element)) @since(2.4) def array_distinct(col): """ Collection function: removes duplicate values from the array. :param col: name of column or expression >>> df = spark.createDataFrame([([1, 2, 3, 2],), ([4, 5, 5, 4],)], ['data']) >>> df.select(array_distinct(df.data)).collect() [Row(array_distinct(data)=[1, 2, 3]), Row(array_distinct(data)=[4, 5])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_distinct(_to_java_column(col))) @ignore_unicode_prefix @since(2.4) def array_intersect(col1, col2): """ Collection function: returns an array of the elements in the intersection of col1 and col2, without duplicates. :param col1: name of column containing array :param col2: name of column containing array >>> from pyspark.sql import Row >>> df = spark.createDataFrame([Row(c1=["b", "a", "c"], c2=["c", "d", "a", "f"])]) >>> df.select(array_intersect(df.c1, df.c2)).collect() [Row(array_intersect(c1, c2)=[u'a', u'c'])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_intersect(_to_java_column(col1), _to_java_column(col2))) @ignore_unicode_prefix @since(2.4) def array_union(col1, col2): """ Collection function: returns an array of the elements in the union of col1 and col2, without duplicates. :param col1: name of column containing array :param col2: name of column containing array >>> from pyspark.sql import Row >>> df = spark.createDataFrame([Row(c1=["b", "a", "c"], c2=["c", "d", "a", "f"])]) >>> df.select(array_union(df.c1, df.c2)).collect() [Row(array_union(c1, c2)=[u'b', u'a', u'c', u'd', u'f'])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_union(_to_java_column(col1), _to_java_column(col2))) @ignore_unicode_prefix @since(2.4) def array_except(col1, col2): """ Collection function: returns an array of the elements in col1 but not in col2, without duplicates. :param col1: name of column containing array :param col2: name of column containing array >>> from pyspark.sql import Row >>> df = spark.createDataFrame([Row(c1=["b", "a", "c"], c2=["c", "d", "a", "f"])]) >>> df.select(array_except(df.c1, df.c2)).collect() [Row(array_except(c1, c2)=[u'b'])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_except(_to_java_column(col1), _to_java_column(col2))) @since(1.4) def explode(col): """Returns a new row for each element in the given array or map. >>> from pyspark.sql import Row >>> eDF = spark.createDataFrame([Row(a=1, intlist=[1,2,3], mapfield={"a": "b"})]) >>> eDF.select(explode(eDF.intlist).alias("anInt")).collect() [Row(anInt=1), Row(anInt=2), Row(anInt=3)] >>> eDF.select(explode(eDF.mapfield).alias("key", "value")).show() +---+-----+ |key|value| +---+-----+ | a| b| +---+-----+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.explode(_to_java_column(col)) return Column(jc) @since(2.1) def posexplode(col): """Returns a new row for each element with position in the given array or map. >>> from pyspark.sql import Row >>> eDF = spark.createDataFrame([Row(a=1, intlist=[1,2,3], mapfield={"a": "b"})]) >>> eDF.select(posexplode(eDF.intlist)).collect() [Row(pos=0, col=1), Row(pos=1, col=2), Row(pos=2, col=3)] >>> eDF.select(posexplode(eDF.mapfield)).show() +---+---+-----+ |pos|key|value| +---+---+-----+ | 0| a| b| +---+---+-----+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.posexplode(_to_java_column(col)) return Column(jc) @since(2.3) def explode_outer(col): """Returns a new row for each element in the given array or map. Unlike explode, if the array/map is null or empty then null is produced. >>> df = spark.createDataFrame( ... [(1, ["foo", "bar"], {"x": 1.0}), (2, [], {}), (3, None, None)], ... ("id", "an_array", "a_map") ... ) >>> df.select("id", "an_array", explode_outer("a_map")).show() +---+----------+----+-----+ | id| an_array| key|value| +---+----------+----+-----+ | 1|[foo, bar]| x| 1.0| | 2| []|null| null| | 3| null|null| null| +---+----------+----+-----+ >>> df.select("id", "a_map", explode_outer("an_array")).show() +---+----------+----+ | id| a_map| col| +---+----------+----+ | 1|[x -> 1.0]| foo| | 1|[x -> 1.0]| bar| | 2| []|null| | 3| null|null| +---+----------+----+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.explode_outer(_to_java_column(col)) return Column(jc) @since(2.3) def posexplode_outer(col): """Returns a new row for each element with position in the given array or map. Unlike posexplode, if the array/map is null or empty then the row (null, null) is produced. >>> df = spark.createDataFrame( ... [(1, ["foo", "bar"], {"x": 1.0}), (2, [], {}), (3, None, None)], ... ("id", "an_array", "a_map") ... ) >>> df.select("id", "an_array", posexplode_outer("a_map")).show() +---+----------+----+----+-----+ | id| an_array| pos| key|value| +---+----------+----+----+-----+ | 1|[foo, bar]| 0| x| 1.0| | 2| []|null|null| null| | 3| null|null|null| null| +---+----------+----+----+-----+ >>> df.select("id", "a_map", posexplode_outer("an_array")).show() +---+----------+----+----+ | id| a_map| pos| col| +---+----------+----+----+ | 1|[x -> 1.0]| 0| foo| | 1|[x -> 1.0]| 1| bar| | 2| []|null|null| | 3| null|null|null| +---+----------+----+----+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.posexplode_outer(_to_java_column(col)) return Column(jc) @ignore_unicode_prefix @since(1.6) def get_json_object(col, path): """ Extracts json object from a json string based on json path specified, and returns json string of the extracted json object. It will return null if the input json string is invalid. :param col: string column in json format :param path: path to the json object to extract >>> data = [("1", '''{"f1": "value1", "f2": "value2"}'''), ("2", '''{"f1": "value12"}''')] >>> df = spark.createDataFrame(data, ("key", "jstring")) >>> df.select(df.key, get_json_object(df.jstring, '$.f1').alias("c0"), \\ ... get_json_object(df.jstring, '$.f2').alias("c1") ).collect() [Row(key=u'1', c0=u'value1', c1=u'value2'), Row(key=u'2', c0=u'value12', c1=None)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.get_json_object(_to_java_column(col), path) return Column(jc) @ignore_unicode_prefix @since(1.6) def json_tuple(col, *fields): """Creates a new row for a json column according to the given field names. :param col: string column in json format :param fields: list of fields to extract >>> data = [("1", '''{"f1": "value1", "f2": "value2"}'''), ("2", '''{"f1": "value12"}''')] >>> df = spark.createDataFrame(data, ("key", "jstring")) >>> df.select(df.key, json_tuple(df.jstring, 'f1', 'f2')).collect() [Row(key=u'1', c0=u'value1', c1=u'value2'), Row(key=u'2', c0=u'value12', c1=None)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.json_tuple(_to_java_column(col), _to_seq(sc, fields)) return Column(jc) @ignore_unicode_prefix @since(2.1) def from_json(col, schema, options={}): """ Parses a column containing a JSON string into a :class:`MapType` with :class:`StringType` as keys type, :class:`StructType` or :class:`ArrayType` with the specified schema. Returns `null`, in the case of an unparseable string. :param col: string column in json format :param schema: a StructType or ArrayType of StructType to use when parsing the json column. :param options: options to control parsing. accepts the same options as the json datasource .. note:: Since Spark 2.3, the DDL-formatted string or a JSON format string is also supported for ``schema``. >>> from pyspark.sql.types import * >>> data = [(1, '''{"a": 1}''')] >>> schema = StructType([StructField("a", IntegerType())]) >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(from_json(df.value, schema).alias("json")).collect() [Row(json=Row(a=1))] >>> df.select(from_json(df.value, "a INT").alias("json")).collect() [Row(json=Row(a=1))] >>> df.select(from_json(df.value, "MAP<STRING,INT>").alias("json")).collect() [Row(json={u'a': 1})] >>> data = [(1, '''[{"a": 1}]''')] >>> schema = ArrayType(StructType([StructField("a", IntegerType())])) >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(from_json(df.value, schema).alias("json")).collect() [Row(json=[Row(a=1)])] >>> schema = schema_of_json(lit('''{"a": 0}''')) >>> df.select(from_json(df.value, schema).alias("json")).collect() [Row(json=Row(a=None))] >>> data = [(1, '''[1, 2, 3]''')] >>> schema = ArrayType(IntegerType()) >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(from_json(df.value, schema).alias("json")).collect() [Row(json=[1, 2, 3])] """ sc = SparkContext._active_spark_context if isinstance(schema, DataType): schema = schema.json() elif isinstance(schema, Column): schema = _to_java_column(schema) jc = sc._jvm.functions.from_json(_to_java_column(col), schema, options) return Column(jc) @ignore_unicode_prefix @since(2.1) def to_json(col, options={}): """ Converts a column containing a :class:`StructType`, :class:`ArrayType` or a :class:`MapType` into a JSON string. Throws an exception, in the case of an unsupported type. :param col: name of column containing a struct, an array or a map. :param options: options to control converting. accepts the same options as the JSON datasource. Additionally the function supports the `pretty` option which enables pretty JSON generation. >>> from pyspark.sql import Row >>> from pyspark.sql.types import * >>> data = [(1, Row(name='Alice', age=2))] >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(to_json(df.value).alias("json")).collect() [Row(json=u'{"age":2,"name":"Alice"}')] >>> data = [(1, [Row(name='Alice', age=2), Row(name='Bob', age=3)])] >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(to_json(df.value).alias("json")).collect() [Row(json=u'[{"age":2,"name":"Alice"},{"age":3,"name":"Bob"}]')] >>> data = [(1, {"name": "Alice"})] >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(to_json(df.value).alias("json")).collect() [Row(json=u'{"name":"Alice"}')] >>> data = [(1, [{"name": "Alice"}, {"name": "Bob"}])] >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(to_json(df.value).alias("json")).collect() [Row(json=u'[{"name":"Alice"},{"name":"Bob"}]')] >>> data = [(1, ["Alice", "Bob"])] >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(to_json(df.value).alias("json")).collect() [Row(json=u'["Alice","Bob"]')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.to_json(_to_java_column(col), options) return Column(jc) @ignore_unicode_prefix @since(2.4) def schema_of_json(json, options={}): """ Parses a JSON string and infers its schema in DDL format. :param json: a JSON string or a string literal containing a JSON string. :param options: options to control parsing. accepts the same options as the JSON datasource .. versionchanged:: 3.0 It accepts `options` parameter to control schema inferring. >>> df = spark.range(1) >>> df.select(schema_of_json(lit('{"a": 0}')).alias("json")).collect() [Row(json=u'struct<a:bigint>')] >>> schema = schema_of_json('{a: 1}', {'allowUnquotedFieldNames':'true'}) >>> df.select(schema.alias("json")).collect() [Row(json=u'struct<a:bigint>')] """ if isinstance(json, basestring): col = _create_column_from_literal(json) elif isinstance(json, Column): col = _to_java_column(json) else: raise TypeError("schema argument should be a column or string") sc = SparkContext._active_spark_context jc = sc._jvm.functions.schema_of_json(col, options) return Column(jc) @ignore_unicode_prefix @since(3.0) def schema_of_csv(csv, options={}): """ Parses a CSV string and infers its schema in DDL format. :param col: a CSV string or a string literal containing a CSV string. :param options: options to control parsing. accepts the same options as the CSV datasource >>> df = spark.range(1) >>> df.select(schema_of_csv(lit('1|a'), {'sep':'|'}).alias("csv")).collect() [Row(csv=u'struct<_c0:int,_c1:string>')] >>> df.select(schema_of_csv('1|a', {'sep':'|'}).alias("csv")).collect() [Row(csv=u'struct<_c0:int,_c1:string>')] """ if isinstance(csv, basestring): col = _create_column_from_literal(csv) elif isinstance(csv, Column): col = _to_java_column(csv) else: raise TypeError("schema argument should be a column or string") sc = SparkContext._active_spark_context jc = sc._jvm.functions.schema_of_csv(col, options) return Column(jc) @ignore_unicode_prefix @since(3.0) def to_csv(col, options={}): """ Converts a column containing a :class:`StructType` into a CSV string. Throws an exception, in the case of an unsupported type. :param col: name of column containing a struct. :param options: options to control converting. accepts the same options as the CSV datasource. >>> from pyspark.sql import Row >>> data = [(1, Row(name='Alice', age=2))] >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(to_csv(df.value).alias("csv")).collect() [Row(csv=u'2,Alice')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.to_csv(_to_java_column(col), options) return Column(jc) @since(1.5) def size(col): """ Collection function: returns the length of the array or map stored in the column. :param col: name of column or expression >>> df = spark.createDataFrame([([1, 2, 3],),([1],),([],)], ['data']) >>> df.select(size(df.data)).collect() [Row(size(data)=3), Row(size(data)=1), Row(size(data)=0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.size(_to_java_column(col))) @since(2.4) def array_min(col): """ Collection function: returns the minimum value of the array. :param col: name of column or expression >>> df = spark.createDataFrame([([2, 1, 3],), ([None, 10, -1],)], ['data']) >>> df.select(array_min(df.data).alias('min')).collect() [Row(min=1), Row(min=-1)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_min(_to_java_column(col))) @since(2.4) def array_max(col): """ Collection function: returns the maximum value of the array. :param col: name of column or expression >>> df = spark.createDataFrame([([2, 1, 3],), ([None, 10, -1],)], ['data']) >>> df.select(array_max(df.data).alias('max')).collect() [Row(max=3), Row(max=10)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_max(_to_java_column(col))) @since(1.5) def sort_array(col, asc=True): """ Collection function: sorts the input array in ascending or descending order according to the natural ordering of the array elements. Null elements will be placed at the beginning of the returned array in ascending order or at the end of the returned array in descending order. :param col: name of column or expression >>> df = spark.createDataFrame([([2, 1, None, 3],),([1],),([],)], ['data']) >>> df.select(sort_array(df.data).alias('r')).collect() [Row(r=[None, 1, 2, 3]), Row(r=[1]), Row(r=[])] >>> df.select(sort_array(df.data, asc=False).alias('r')).collect() [Row(r=[3, 2, 1, None]), Row(r=[1]), Row(r=[])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.sort_array(_to_java_column(col), asc)) @since(2.4) def array_sort(col): """ Collection function: sorts the input array in ascending order. The elements of the input array must be orderable. Null elements will be placed at the end of the returned array. :param col: name of column or expression >>> df = spark.createDataFrame([([2, 1, None, 3],),([1],),([],)], ['data']) >>> df.select(array_sort(df.data).alias('r')).collect() [Row(r=[1, 2, 3, None]), Row(r=[1]), Row(r=[])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_sort(_to_java_column(col))) @since(2.4) def shuffle(col): """ Collection function: Generates a random permutation of the given array. .. note:: The function is non-deterministic. :param col: name of column or expression >>> df = spark.createDataFrame([([1, 20, 3, 5],), ([1, 20, None, 3],)], ['data']) >>> df.select(shuffle(df.data).alias('s')).collect() # doctest: +SKIP [Row(s=[3, 1, 5, 20]), Row(s=[20, None, 3, 1])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.shuffle(_to_java_column(col))) @since(1.5) @ignore_unicode_prefix def reverse(col): """ Collection function: returns a reversed string or an array with reverse order of elements. :param col: name of column or expression >>> df = spark.createDataFrame([('Spark SQL',)], ['data']) >>> df.select(reverse(df.data).alias('s')).collect() [Row(s=u'LQS krapS')] >>> df = spark.createDataFrame([([2, 1, 3],) ,([1],) ,([],)], ['data']) >>> df.select(reverse(df.data).alias('r')).collect() [Row(r=[3, 1, 2]), Row(r=[1]), Row(r=[])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.reverse(_to_java_column(col))) @since(2.4) def flatten(col): """ Collection function: creates a single array from an array of arrays. If a structure of nested arrays is deeper than two levels, only one level of nesting is removed. :param col: name of column or expression >>> df = spark.createDataFrame([([[1, 2, 3], [4, 5], [6]],), ([None, [4, 5]],)], ['data']) >>> df.select(flatten(df.data).alias('r')).collect() [Row(r=[1, 2, 3, 4, 5, 6]), Row(r=None)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.flatten(_to_java_column(col))) @since(2.3) def map_keys(col): """ Collection function: Returns an unordered array containing the keys of the map. :param col: name of column or expression >>> from pyspark.sql.functions import map_keys >>> df = spark.sql("SELECT map(1, 'a', 2, 'b') as data") >>> df.select(map_keys("data").alias("keys")).show() +------+ | keys| +------+ |[1, 2]| +------+ """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.map_keys(_to_java_column(col))) @since(2.3) def map_values(col): """ Collection function: Returns an unordered array containing the values of the map. :param col: name of column or expression >>> from pyspark.sql.functions import map_values >>> df = spark.sql("SELECT map(1, 'a', 2, 'b') as data") >>> df.select(map_values("data").alias("values")).show() +------+ |values| +------+ |[a, b]| +------+ """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.map_values(_to_java_column(col))) @since(3.0) def map_entries(col): """ Collection function: Returns an unordered array of all entries in the given map. :param col: name of column or expression >>> from pyspark.sql.functions import map_entries >>> df = spark.sql("SELECT map(1, 'a', 2, 'b') as data") >>> df.select(map_entries("data").alias("entries")).show() +----------------+ | entries| +----------------+ |[[1, a], [2, b]]| +----------------+ """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.map_entries(_to_java_column(col))) @since(2.4) def map_from_entries(col): """ Collection function: Returns a map created from the given array of entries. :param col: name of column or expression >>> from pyspark.sql.functions import map_from_entries >>> df = spark.sql("SELECT array(struct(1, 'a'), struct(2, 'b')) as data") >>> df.select(map_from_entries("data").alias("map")).show() +----------------+ | map| +----------------+ |[1 -> a, 2 -> b]| +----------------+ """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.map_from_entries(_to_java_column(col))) @ignore_unicode_prefix @since(2.4) def array_repeat(col, count): """ Collection function: creates an array containing a column repeated count times. >>> df = spark.createDataFrame([('ab',)], ['data']) >>> df.select(array_repeat(df.data, 3).alias('r')).collect() [Row(r=[u'ab', u'ab', u'ab'])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_repeat(_to_java_column(col), count)) @since(2.4) def arrays_zip(*cols): """ Collection function: Returns a merged array of structs in which the N-th struct contains all N-th values of input arrays. :param cols: columns of arrays to be merged. >>> from pyspark.sql.functions import arrays_zip >>> df = spark.createDataFrame([(([1, 2, 3], [2, 3, 4]))], ['vals1', 'vals2']) >>> df.select(arrays_zip(df.vals1, df.vals2).alias('zipped')).collect() [Row(zipped=[Row(vals1=1, vals2=2), Row(vals1=2, vals2=3), Row(vals1=3, vals2=4)])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.arrays_zip(_to_seq(sc, cols, _to_java_column))) @since(2.4) def map_concat(*cols): """Returns the union of all the given maps. :param cols: list of column names (string) or list of :class:`Column` expressions >>> from pyspark.sql.functions import map_concat >>> df = spark.sql("SELECT map(1, 'a', 2, 'b') as map1, map(3, 'c', 1, 'd') as map2") >>> df.select(map_concat("map1", "map2").alias("map3")).show(truncate=False) +------------------------+ |map3 | +------------------------+ |[1 -> d, 2 -> b, 3 -> c]| +------------------------+ """ sc = SparkContext._active_spark_context if len(cols) == 1 and isinstance(cols[0], (list, set)): cols = cols[0] jc = sc._jvm.functions.map_concat(_to_seq(sc, cols, _to_java_column)) return Column(jc) @since(2.4) def sequence(start, stop, step=None): """ Generate a sequence of integers from `start` to `stop`, incrementing by `step`. If `step` is not set, incrementing by 1 if `start` is less than or equal to `stop`, otherwise -1. >>> df1 = spark.createDataFrame([(-2, 2)], ('C1', 'C2')) >>> df1.select(sequence('C1', 'C2').alias('r')).collect() [Row(r=[-2, -1, 0, 1, 2])] >>> df2 = spark.createDataFrame([(4, -4, -2)], ('C1', 'C2', 'C3')) >>> df2.select(sequence('C1', 'C2', 'C3').alias('r')).collect() [Row(r=[4, 2, 0, -2, -4])] """ sc = SparkContext._active_spark_context if step is None: return Column(sc._jvm.functions.sequence(_to_java_column(start), _to_java_column(stop))) else: return Column(sc._jvm.functions.sequence( _to_java_column(start), _to_java_column(stop), _to_java_column(step))) @ignore_unicode_prefix @since(3.0) def from_csv(col, schema, options={}): """ Parses a column containing a CSV string to a row with the specified schema. Returns `null`, in the case of an unparseable string. :param col: string column in CSV format :param schema: a string with schema in DDL format to use when parsing the CSV column. :param options: options to control parsing. accepts the same options as the CSV datasource >>> data = [("1,2,3",)] >>> df = spark.createDataFrame(data, ("value",)) >>> df.select(from_csv(df.value, "a INT, b INT, c INT").alias("csv")).collect() [Row(csv=Row(a=1, b=2, c=3))] >>> value = data[0][0] >>> df.select(from_csv(df.value, schema_of_csv(value)).alias("csv")).collect() [Row(csv=Row(_c0=1, _c1=2, _c2=3))] """ sc = SparkContext._active_spark_context if isinstance(schema, basestring): schema = _create_column_from_literal(schema) elif isinstance(schema, Column): schema = _to_java_column(schema) else: raise TypeError("schema argument should be a column or string") jc = sc._jvm.functions.from_csv(_to_java_column(col), schema, options) return Column(jc) # ---------------------------- User Defined Function ---------------------------------- class PandasUDFType(object): """Pandas UDF Types. See :meth:`pyspark.sql.functions.pandas_udf`. """ SCALAR = PythonEvalType.SQL_SCALAR_PANDAS_UDF GROUPED_MAP = PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF GROUPED_AGG = PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF @since(1.3) def udf(f=None, returnType=StringType()): """Creates a user defined function (UDF). .. note:: The user-defined functions are considered deterministic by default. Due to optimization, duplicate invocations may be eliminated or the function may even be invoked more times than it is present in the query. If your function is not deterministic, call `asNondeterministic` on the user defined function. E.g.: >>> from pyspark.sql.types import IntegerType >>> import random >>> random_udf = udf(lambda: int(random.random() * 100), IntegerType()).asNondeterministic() .. note:: The user-defined functions do not support conditional expressions or short circuiting in boolean expressions and it ends up with being executed all internally. If the functions can fail on special rows, the workaround is to incorporate the condition into the functions. .. note:: The user-defined functions do not take keyword arguments on the calling side. :param f: python function if used as a standalone function :param returnType: the return type of the user-defined function. The value can be either a :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string. >>> from pyspark.sql.types import IntegerType >>> slen = udf(lambda s: len(s), IntegerType()) >>> @udf ... def to_upper(s): ... if s is not None: ... return s.upper() ... >>> @udf(returnType=IntegerType()) ... def add_one(x): ... if x is not None: ... return x + 1 ... >>> df = spark.createDataFrame([(1, "John Doe", 21)], ("id", "name", "age")) >>> df.select(slen("name").alias("slen(name)"), to_upper("name"), add_one("age")).show() +----------+--------------+------------+ |slen(name)|to_upper(name)|add_one(age)| +----------+--------------+------------+ | 8| JOHN DOE| 22| +----------+--------------+------------+ """ # The following table shows most of Python data and SQL type conversions in normal UDFs that # are not yet visible to the user. Some of behaviors are buggy and might be changed in the near # future. The table might have to be eventually documented externally. # Please see SPARK-25666's PR to see the codes in order to generate the table below. # # +-----------------------------+--------------+----------+------+-------+---------------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+-----------------+------------+--------------+------------------+----------------------+ # noqa # |SQL Type \ Python Value(Type)|None(NoneType)|True(bool)|1(int)|1(long)| a(str)| a(unicode)| 1970-01-01(date)|1970-01-01 00:00:00(datetime)|1.0(float)|array('i', [1])(array)|[1](list)| (1,)(tuple)| ABC(bytearray)| 1(Decimal)|{'a': 1}(dict)|Row(kwargs=1)(Row)|Row(namedtuple=1)(Row)| # noqa # +-----------------------------+--------------+----------+------+-------+---------------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+-----------------+------------+--------------+------------------+----------------------+ # noqa # | boolean| None| True| None| None| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa # | tinyint| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa # | smallint| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa # | int| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa # | bigint| None| None| 1| 1| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa # | string| None| u'true'| u'1'| u'1'| u'a'| u'a'|u'java.util.Grego...| u'java.util.Grego...| u'1.0'| u'[I@24a83055'| u'[1]'|u'[Ljava.lang.Obj...| u'[B@49093632'| u'1'| u'{a=1}'| X| X| # noqa # | date| None| X| X| X| X| X|datetime.date(197...| datetime.date(197...| X| X| X| X| X| X| X| X| X| # noqa # | timestamp| None| X| X| X| X| X| X| datetime.datetime...| X| X| X| X| X| X| X| X| X| # noqa # | float| None| None| None| None| None| None| None| None| 1.0| None| None| None| None| None| None| X| X| # noqa # | double| None| None| None| None| None| None| None| None| 1.0| None| None| None| None| None| None| X| X| # noqa # | array<int>| None| None| None| None| None| None| None| None| None| [1]| [1]| [1]| [65, 66, 67]| None| None| X| X| # noqa # | binary| None| None| None| None|bytearray(b'a')|bytearray(b'a')| None| None| None| None| None| None|bytearray(b'ABC')| None| None| X| X| # noqa # | decimal(10,0)| None| None| None| None| None| None| None| None| None| None| None| None| None|Decimal('1')| None| X| X| # noqa # | map<string,int>| None| None| None| None| None| None| None| None| None| None| None| None| None| None| {u'a': 1}| X| X| # noqa # | struct<_1:int>| None| X| X| X| X| X| X| X| X| X|Row(_1=1)| Row(_1=1)| X| X| Row(_1=None)| Row(_1=1)| Row(_1=1)| # noqa # +-----------------------------+--------------+----------+------+-------+---------------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+-----------------+------------+--------------+------------------+----------------------+ # noqa # # Note: DDL formatted string is used for 'SQL Type' for simplicity. This string can be # used in `returnType`. # Note: The values inside of the table are generated by `repr`. # Note: Python 2 is used to generate this table since it is used to check the backward # compatibility often in practice. # Note: 'X' means it throws an exception during the conversion. # decorator @udf, @udf(), @udf(dataType()) if f is None or isinstance(f, (str, DataType)): # If DataType has been passed as a positional argument # for decorator use it as a returnType return_type = f or returnType return functools.partial(_create_udf, returnType=return_type, evalType=PythonEvalType.SQL_BATCHED_UDF) else: return _create_udf(f=f, returnType=returnType, evalType=PythonEvalType.SQL_BATCHED_UDF) @since(2.3) def pandas_udf(f=None, returnType=None, functionType=None): """ Creates a vectorized user defined function (UDF). :param f: user-defined function. A python function if used as a standalone function :param returnType: the return type of the user-defined function. The value can be either a :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string. :param functionType: an enum value in :class:`pyspark.sql.functions.PandasUDFType`. Default: SCALAR. .. note:: Experimental The function type of the UDF can be one of the following: 1. SCALAR A scalar UDF defines a transformation: One or more `pandas.Series` -> A `pandas.Series`. The length of the returned `pandas.Series` must be of the same as the input `pandas.Series`. If the return type is :class:`StructType`, the returned value should be a `pandas.DataFrame`. :class:`MapType`, nested :class:`StructType` are currently not supported as output types. Scalar UDFs are used with :meth:`pyspark.sql.DataFrame.withColumn` and :meth:`pyspark.sql.DataFrame.select`. >>> from pyspark.sql.functions import pandas_udf, PandasUDFType >>> from pyspark.sql.types import IntegerType, StringType >>> slen = pandas_udf(lambda s: s.str.len(), IntegerType()) # doctest: +SKIP >>> @pandas_udf(StringType()) # doctest: +SKIP ... def to_upper(s): ... return s.str.upper() ... >>> @pandas_udf("integer", PandasUDFType.SCALAR) # doctest: +SKIP ... def add_one(x): ... return x + 1 ... >>> df = spark.createDataFrame([(1, "John Doe", 21)], ... ("id", "name", "age")) # doctest: +SKIP >>> df.select(slen("name").alias("slen(name)"), to_upper("name"), add_one("age")) \\ ... .show() # doctest: +SKIP +----------+--------------+------------+ |slen(name)|to_upper(name)|add_one(age)| +----------+--------------+------------+ | 8| JOHN DOE| 22| +----------+--------------+------------+ >>> @pandas_udf("first string, last string") # doctest: +SKIP ... def split_expand(n): ... return n.str.split(expand=True) >>> df.select(split_expand("name")).show() # doctest: +SKIP +------------------+ |split_expand(name)| +------------------+ | [John, Doe]| +------------------+ .. note:: The length of `pandas.Series` within a scalar UDF is not that of the whole input column, but is the length of an internal batch used for each call to the function. Therefore, this can be used, for example, to ensure the length of each returned `pandas.Series`, and can not be used as the column length. 2. GROUPED_MAP A grouped map UDF defines transformation: A `pandas.DataFrame` -> A `pandas.DataFrame` The returnType should be a :class:`StructType` describing the schema of the returned `pandas.DataFrame`. The column labels of the returned `pandas.DataFrame` must either match the field names in the defined returnType schema if specified as strings, or match the field data types by position if not strings, e.g. integer indices. The length of the returned `pandas.DataFrame` can be arbitrary. Grouped map UDFs are used with :meth:`pyspark.sql.GroupedData.apply`. >>> from pyspark.sql.functions import pandas_udf, PandasUDFType >>> df = spark.createDataFrame( ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)], ... ("id", "v")) # doctest: +SKIP >>> @pandas_udf("id long, v double", PandasUDFType.GROUPED_MAP) # doctest: +SKIP ... def normalize(pdf): ... v = pdf.v ... return pdf.assign(v=(v - v.mean()) / v.std()) >>> df.groupby("id").apply(normalize).show() # doctest: +SKIP +---+-------------------+ | id| v| +---+-------------------+ | 1|-0.7071067811865475| | 1| 0.7071067811865475| | 2|-0.8320502943378437| | 2|-0.2773500981126146| | 2| 1.1094003924504583| +---+-------------------+ Alternatively, the user can define a function that takes two arguments. In this case, the grouping key(s) will be passed as the first argument and the data will be passed as the second argument. The grouping key(s) will be passed as a tuple of numpy data types, e.g., `numpy.int32` and `numpy.float64`. The data will still be passed in as a `pandas.DataFrame` containing all columns from the original Spark DataFrame. This is useful when the user does not want to hardcode grouping key(s) in the function. >>> import pandas as pd # doctest: +SKIP >>> from pyspark.sql.functions import pandas_udf, PandasUDFType >>> df = spark.createDataFrame( ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)], ... ("id", "v")) # doctest: +SKIP >>> @pandas_udf("id long, v double", PandasUDFType.GROUPED_MAP) # doctest: +SKIP ... def mean_udf(key, pdf): ... # key is a tuple of one numpy.int64, which is the value ... # of 'id' for the current group ... return pd.DataFrame([key + (pdf.v.mean(),)]) >>> df.groupby('id').apply(mean_udf).show() # doctest: +SKIP +---+---+ | id| v| +---+---+ | 1|1.5| | 2|6.0| +---+---+ >>> @pandas_udf( ... "id long, `ceil(v / 2)` long, v double", ... PandasUDFType.GROUPED_MAP) # doctest: +SKIP >>> def sum_udf(key, pdf): ... # key is a tuple of two numpy.int64s, which is the values ... # of 'id' and 'ceil(df.v / 2)' for the current group ... return pd.DataFrame([key + (pdf.v.sum(),)]) >>> df.groupby(df.id, ceil(df.v / 2)).apply(sum_udf).show() # doctest: +SKIP +---+-----------+----+ | id|ceil(v / 2)| v| +---+-----------+----+ | 2| 5|10.0| | 1| 1| 3.0| | 2| 3| 5.0| | 2| 2| 3.0| +---+-----------+----+ .. note:: If returning a new `pandas.DataFrame` constructed with a dictionary, it is recommended to explicitly index the columns by name to ensure the positions are correct, or alternatively use an `OrderedDict`. For example, `pd.DataFrame({'id': ids, 'a': data}, columns=['id', 'a'])` or `pd.DataFrame(OrderedDict([('id', ids), ('a', data)]))`. .. seealso:: :meth:`pyspark.sql.GroupedData.apply` 3. GROUPED_AGG A grouped aggregate UDF defines a transformation: One or more `pandas.Series` -> A scalar The `returnType` should be a primitive data type, e.g., :class:`DoubleType`. The returned scalar can be either a python primitive type, e.g., `int` or `float` or a numpy data type, e.g., `numpy.int64` or `numpy.float64`. :class:`MapType` and :class:`StructType` are currently not supported as output types. Group aggregate UDFs are used with :meth:`pyspark.sql.GroupedData.agg` and :class:`pyspark.sql.Window` This example shows using grouped aggregated UDFs with groupby: >>> from pyspark.sql.functions import pandas_udf, PandasUDFType >>> df = spark.createDataFrame( ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)], ... ("id", "v")) >>> @pandas_udf("double", PandasUDFType.GROUPED_AGG) # doctest: +SKIP ... def mean_udf(v): ... return v.mean() >>> df.groupby("id").agg(mean_udf(df['v'])).show() # doctest: +SKIP +---+-----------+ | id|mean_udf(v)| +---+-----------+ | 1| 1.5| | 2| 6.0| +---+-----------+ This example shows using grouped aggregated UDFs as window functions. >>> from pyspark.sql.functions import pandas_udf, PandasUDFType >>> from pyspark.sql import Window >>> df = spark.createDataFrame( ... [(1, 1.0), (1, 2.0), (2, 3.0), (2, 5.0), (2, 10.0)], ... ("id", "v")) >>> @pandas_udf("double", PandasUDFType.GROUPED_AGG) # doctest: +SKIP ... def mean_udf(v): ... return v.mean() >>> w = (Window.partitionBy('id') ... .orderBy('v') ... .rowsBetween(-1, 0)) >>> df.withColumn('mean_v', mean_udf(df['v']).over(w)).show() # doctest: +SKIP +---+----+------+ | id| v|mean_v| +---+----+------+ | 1| 1.0| 1.0| | 1| 2.0| 1.5| | 2| 3.0| 3.0| | 2| 5.0| 4.0| | 2|10.0| 7.5| +---+----+------+ .. note:: For performance reasons, the input series to window functions are not copied. Therefore, mutating the input series is not allowed and will cause incorrect results. For the same reason, users should also not rely on the index of the input series. .. seealso:: :meth:`pyspark.sql.GroupedData.agg` and :class:`pyspark.sql.Window` .. note:: The user-defined functions are considered deterministic by default. Due to optimization, duplicate invocations may be eliminated or the function may even be invoked more times than it is present in the query. If your function is not deterministic, call `asNondeterministic` on the user defined function. E.g.: >>> @pandas_udf('double', PandasUDFType.SCALAR) # doctest: +SKIP ... def random(v): ... import numpy as np ... import pandas as pd ... return pd.Series(np.random.randn(len(v)) >>> random = random.asNondeterministic() # doctest: +SKIP .. note:: The user-defined functions do not support conditional expressions or short circuiting in boolean expressions and it ends up with being executed all internally. If the functions can fail on special rows, the workaround is to incorporate the condition into the functions. .. note:: The user-defined functions do not take keyword arguments on the calling side. .. note:: The data type of returned `pandas.Series` from the user-defined functions should be matched with defined returnType (see :meth:`types.to_arrow_type` and :meth:`types.from_arrow_type`). When there is mismatch between them, Spark might do conversion on returned data. The conversion is not guaranteed to be correct and results should be checked for accuracy by users. """ # The following table shows most of Pandas data and SQL type conversions in Pandas UDFs that # are not yet visible to the user. Some of behaviors are buggy and might be changed in the near # future. The table might have to be eventually documented externally. # Please see SPARK-25798's PR to see the codes in order to generate the table below. # # +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa # |SQL Type \ Pandas Value(Type)|None(object(NoneType))|True(bool)|1(int8)|1(int16)| 1(int32)| 1(int64)|1(uint8)|1(uint16)|1(uint32)|1(uint64)|1.0(float16)|1.0(float32)|1.0(float64)|1970-01-01 00:00:00(datetime64[ns])|1970-01-01 00:00:00-05:00(datetime64[ns, US/Eastern])|a(object(string))| 1(object(Decimal))|[1 2 3](object(array[int32]))|1.0(float128)|(1+0j)(complex64)|(1+0j)(complex128)|A(category)|1 days 00:00:00(timedelta64[ns])| # noqa # +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa # | boolean| None| True| True| True| True| True| True| True| True| True| False| False| False| False| False| X| X| X| False| False| False| X| False| # noqa # | tinyint| None| 1| 1| 1| 1| 1| X| X| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| 0| X| # noqa # | smallint| None| 1| 1| 1| 1| 1| 1| X| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| X| X| # noqa # | int| None| 1| 1| 1| 1| 1| 1| 1| X| X| 1| 1| 1| X| X| X| X| X| X| X| X| X| X| # noqa # | bigint| None| 1| 1| 1| 1| 1| 1| 1| 1| X| 1| 1| 1| 0| 18000000000000| X| X| X| X| X| X| X| X| # noqa # | float| None| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| X| X| X|1.401298464324817...| X| X| X| X| X| X| # noqa # | double| None| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| X| X| X| X| X| X| X| X| X| X| # noqa # | date| None| X| X| X|datetime.date(197...| X| X| X| X| X| X| X| X| datetime.date(197...| X| X| X| X| X| X| X| X| X| # noqa # | timestamp| None| X| X| X| X|datetime.datetime...| X| X| X| X| X| X| X| datetime.datetime...| datetime.datetime...| X| X| X| X| X| X| X| X| # noqa # | string| None| u''|u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u'\x01'| u''| u''| u''| X| X| u'a'| X| X| u''| u''| u''| X| X| # noqa # | decimal(10,0)| None| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| Decimal('1')| X| X| X| X| X| X| # noqa # | array<int>| None| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| [1, 2, 3]| X| X| X| X| X| # noqa # | map<string,int>| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa # | struct<_1:int>| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa # | binary| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| X| # noqa # +-----------------------------+----------------------+----------+-------+--------+--------------------+--------------------+--------+---------+---------+---------+------------+------------+------------+-----------------------------------+-----------------------------------------------------+-----------------+--------------------+-----------------------------+-------------+-----------------+------------------+-----------+--------------------------------+ # noqa # # Note: DDL formatted string is used for 'SQL Type' for simplicity. This string can be # used in `returnType`. # Note: The values inside of the table are generated by `repr`. # Note: Python 2 is used to generate this table since it is used to check the backward # compatibility often in practice. # Note: Pandas 0.19.2 and PyArrow 0.9.0 are used. # Note: Timezone is Singapore timezone. # Note: 'X' means it throws an exception during the conversion. # Note: 'binary' type is only supported with PyArrow 0.10.0+ (SPARK-23555). # decorator @pandas_udf(returnType, functionType) is_decorator = f is None or isinstance(f, (str, DataType)) if is_decorator: # If DataType has been passed as a positional argument # for decorator use it as a returnType return_type = f or returnType if functionType is not None: # @pandas_udf(dataType, functionType=functionType) # @pandas_udf(returnType=dataType, functionType=functionType) eval_type = functionType elif returnType is not None and isinstance(returnType, int): # @pandas_udf(dataType, functionType) eval_type = returnType else: # @pandas_udf(dataType) or @pandas_udf(returnType=dataType) eval_type = PythonEvalType.SQL_SCALAR_PANDAS_UDF else: return_type = returnType if functionType is not None: eval_type = functionType else: eval_type = PythonEvalType.SQL_SCALAR_PANDAS_UDF if return_type is None: raise ValueError("Invalid returnType: returnType can not be None") if eval_type not in [PythonEvalType.SQL_SCALAR_PANDAS_UDF, PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF, PythonEvalType.SQL_GROUPED_AGG_PANDAS_UDF]: raise ValueError("Invalid functionType: " "functionType must be one the values from PandasUDFType") if is_decorator: return functools.partial(_create_udf, returnType=return_type, evalType=eval_type) else: return _create_udf(f=f, returnType=return_type, evalType=eval_type) blacklist = ['map', 'since', 'ignore_unicode_prefix'] __all__ = [k for k, v in globals().items() if not k.startswith('_') and k[0].islower() and callable(v) and k not in blacklist] __all__ += ["PandasUDFType"] __all__.sort() def _test(): import doctest from pyspark.sql import Row, SparkSession import pyspark.sql.functions globs = pyspark.sql.functions.__dict__.copy() spark = SparkSession.builder\ .master("local[4]")\ .appName("sql.functions tests")\ .getOrCreate() sc = spark.sparkContext globs['sc'] = sc globs['spark'] = spark globs['df'] = spark.createDataFrame([Row(name='Alice', age=2), Row(name='Bob', age=5)]) (failure_count, test_count) = doctest.testmod( pyspark.sql.functions, globs=globs, optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE) spark.stop() if failure_count: sys.exit(-1) if __name__ == "__main__": _test()
unknown
codeparrot/codeparrot-clean
import { type Author } from "./author"; export type Post = { slug: string; title: string; date: string; coverImage: string; author: Author; excerpt: string; ogImage: { url: string; }; content: string; preview?: boolean; };
typescript
github
https://github.com/vercel/next.js
examples/blog-starter/src/interfaces/post.ts
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from airflow.hooks.presto_hook import PrestoHook from airflow.hooks.mysql_hook import MySqlHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class PrestoToMySqlTransfer(BaseOperator): """ Moves data from Presto to MySQL, note that for now the data is loaded into memory before being pushed to MySQL, so this operator should be used for smallish amount of data. :param sql: SQL query to execute against Presto. (templated) :type sql: str :param mysql_table: target MySQL table, use dot notation to target a specific database. (templated) :type mysql_table: str :param mysql_conn_id: source mysql connection :type mysql_conn_id: str :param presto_conn_id: source presto connection :type presto_conn_id: str :param mysql_preoperator: sql statement to run against mysql prior to import, typically use to truncate of delete in place of the data coming in, allowing the task to be idempotent (running the task twice won't double load data). (templated) :type mysql_preoperator: str """ template_fields = ('sql', 'mysql_table', 'mysql_preoperator') template_ext = ('.sql',) ui_color = '#a0e08c' @apply_defaults def __init__( self, sql, mysql_table, presto_conn_id='presto_default', mysql_conn_id='mysql_default', mysql_preoperator=None, *args, **kwargs): super(PrestoToMySqlTransfer, self).__init__(*args, **kwargs) self.sql = sql self.mysql_table = mysql_table self.mysql_conn_id = mysql_conn_id self.mysql_preoperator = mysql_preoperator self.presto_conn_id = presto_conn_id def execute(self, context): presto = PrestoHook(presto_conn_id=self.presto_conn_id) self.log.info("Extracting data from Presto: %s", self.sql) results = presto.get_records(self.sql) mysql = MySqlHook(mysql_conn_id=self.mysql_conn_id) if self.mysql_preoperator: self.log.info("Running MySQL preoperator") self.log.info(self.mysql_preoperator) mysql.run(self.mysql_preoperator) self.log.info("Inserting rows into MySQL") mysql.insert_rows(table=self.mysql_table, rows=results)
unknown
codeparrot/codeparrot-clean
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) return True pybindgen.settings.error_handler = ErrorHandler() import sys def module_init(): root_module = Module('ns.aodv', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## 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']) typehandlers.add_type_alias(u'std::list< ns3::AttributeConstructionList::Item > const_iterator', u'ns3::AttributeConstructionList::CIterator') typehandlers.add_type_alias(u'std::list< ns3::AttributeConstructionList::Item > const_iterator*', u'ns3::AttributeConstructionList::CIterator*') typehandlers.add_type_alias(u'std::list< ns3::AttributeConstructionList::Item > const_iterator&', u'ns3::AttributeConstructionList::CIterator&') ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeChecker']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::AttributeValue']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::EventImpl']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Ipv4Route> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Ipv4Route']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::NixVector']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::Packet']) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor> [struct] module.add_class('DefaultDeleter', import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor']) ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress', import_from_module='ns.network') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] module.add_class('InetSocketAddress', import_from_module='ns.network') ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## int-to-type.h (module 'core'): ns3::IntToType<0> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['0']) ## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<1> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['1']) ## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<2> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['2']) ## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<3> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['3']) ## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<4> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['4']) ## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<5> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5']) ## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<6> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['6']) ## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'], import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper [class] module.add_class('Ipv4RoutingHelper', allow_subclassing=True, import_from_module='ns.internet') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') typehandlers.add_type_alias(u'void ( * ) ( ns3::Mac48Address )', u'ns3::Mac48Address::TracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Mac48Address )*', u'ns3::Mac48Address::TracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Mac48Address )&', u'ns3::Mac48Address::TracedCallback&') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## mac8-address.h (module 'network'): ns3::Mac8Address [class] module.add_class('Mac8Address', import_from_module='ns.network') ## mac8-address.h (module 'network'): ns3::Mac8Address [class] root_module['ns3::Mac8Address'].implicitly_converts_to(root_module['ns3::Address']) ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Node > > const_iterator', u'ns3::NodeContainer::Iterator') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Node > > const_iterator*', u'ns3::NodeContainer::Iterator*') typehandlers.add_type_alias(u'std::vector< ns3::Ptr< ns3::Node > > const_iterator&', u'ns3::NodeContainer::Iterator&') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::ItemType [enumeration] module.add_enum('ItemType', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## simulator.h (module 'core'): ns3::Simulator [enumeration] module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer [class] module.add_class('Timer', import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration] module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::State [enumeration] module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer-impl.h (module 'core'): ns3::TimerImpl [class] module.add_class('TimerImpl', allow_subclassing=True, import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::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']) typehandlers.add_type_alias(u'uint32_t', u'ns3::TypeId::hash_t') typehandlers.add_type_alias(u'uint32_t*', u'ns3::TypeId::hash_t*') typehandlers.add_type_alias(u'uint32_t&', u'ns3::TypeId::hash_t&') ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-128.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-128.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') ## aodv-helper.h (module 'aodv'): ns3::AodvHelper [class] module.add_class('AodvHelper', parent=root_module['ns3::Ipv4RoutingHelper']) ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class] module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration] module.add_enum('DscpType', ['DscpDefault', 'DSCP_CS1', 'DSCP_AF11', 'DSCP_AF12', 'DSCP_AF13', 'DSCP_CS2', 'DSCP_AF21', 'DSCP_AF22', 'DSCP_AF23', 'DSCP_CS3', 'DSCP_AF31', 'DSCP_AF32', 'DSCP_AF33', 'DSCP_CS4', 'DSCP_AF41', 'DSCP_AF42', 'DSCP_AF43', 'DSCP_CS5', 'DSCP_EF', 'DSCP_CS6', 'DSCP_CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration] module.add_enum('EcnType', ['ECN_NotECT', 'ECN_ECT1', 'ECN_ECT0', 'ECN_CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class] module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class] module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<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::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4MulticastRoute>'], 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::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4Route>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## socket.h (module 'network'): ns3::Socket [class] module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketPriority [enumeration] module.add_enum('SocketPriority', ['NS3_PRIO_BESTEFFORT', 'NS3_PRIO_FILLER', 'NS3_PRIO_BULK', 'NS3_PRIO_INTERACTIVE_BULK', 'NS3_PRIO_INTERACTIVE', 'NS3_PRIO_CONTROL'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::Ipv6MulticastFilterMode [enumeration] module.add_enum('Ipv6MulticastFilterMode', ['INCLUDE', 'EXCLUDE'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::SocketIpTosTag [class] module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketPriorityTag [class] module.add_class('SocketPriorityTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time )', u'ns3::Time::TracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time )*', u'ns3::Time::TracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time )&', u'ns3::Time::TracedCallback&') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class] module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## 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']) ## arp-cache.h (module 'internet'): ns3::ArpCache [class] module.add_class('ArpCache', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## arp-cache.h (module 'internet'): ns3::ArpCache::Entry [class] module.add_class('Entry', import_from_module='ns.internet', outer_class=root_module['ns3::ArpCache']) typehandlers.add_type_alias(u'std::pair< ns3::Ptr< ns3::Packet >, ns3::Ipv4Header >', u'ns3::ArpCache::Ipv4PayloadHeaderPair') typehandlers.add_type_alias(u'std::pair< ns3::Ptr< ns3::Packet >, ns3::Ipv4Header >*', u'ns3::ArpCache::Ipv4PayloadHeaderPair*') typehandlers.add_type_alias(u'std::pair< ns3::Ptr< ns3::Packet >, ns3::Ipv4Header >&', u'ns3::ArpCache::Ipv4PayloadHeaderPair&') ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## 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']) ## enum.h (module 'core'): ns3::EnumChecker [class] module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## enum.h (module 'core'): ns3::EnumValue [class] module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class] module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<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']) ## ipv4.h (module 'internet'): ns3::Ipv4 [class] module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface [class] module.add_class('Ipv4Interface', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol [class] module.add_class('Ipv4L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv4']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::DropReason [enumeration] module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_BAD_CHECKSUM', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv4L3Protocol'], import_from_module='ns.internet') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, uint32_t )', u'ns3::Ipv4L3Protocol::SentTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, uint32_t )*', u'ns3::Ipv4L3Protocol::SentTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, uint32_t )&', u'ns3::Ipv4L3Protocol::SentTracedCallback&') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Ptr< ns3::Ipv4 >, uint32_t )', u'ns3::Ipv4L3Protocol::TxRxTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Ptr< ns3::Ipv4 >, uint32_t )*', u'ns3::Ipv4L3Protocol::TxRxTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Ptr< ns3::Ipv4 >, uint32_t )&', u'ns3::Ipv4L3Protocol::TxRxTracedCallback&') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr< ns3::Ipv4 >, uint32_t )', u'ns3::Ipv4L3Protocol::DropTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr< ns3::Ipv4 >, uint32_t )*', u'ns3::Ipv4L3Protocol::DropTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr< ns3::Ipv4 >, uint32_t )&', u'ns3::Ipv4L3Protocol::DropTracedCallback&') ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class] module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class] module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class] module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::Ipv4RoutingProtocol::UnicastForwardCallback') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::Ipv4RoutingProtocol::UnicastForwardCallback*') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::Ipv4RoutingProtocol::UnicastForwardCallback&') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::Ipv4RoutingProtocol::MulticastForwardCallback') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::Ipv4RoutingProtocol::MulticastForwardCallback*') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::Ipv4RoutingProtocol::MulticastForwardCallback&') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::Ipv4RoutingProtocol::LocalDeliverCallback') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::Ipv4RoutingProtocol::LocalDeliverCallback*') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::Ipv4RoutingProtocol::LocalDeliverCallback&') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::Ipv4RoutingProtocol::ErrorCallback') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::Ipv4RoutingProtocol::ErrorCallback*') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::Ipv4RoutingProtocol::ErrorCallback&') ## 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']) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class] module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') typehandlers.add_type_alias(u'void ( * ) ( )', u'ns3::NetDevice::LinkChangeTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( )*', u'ns3::NetDevice::LinkChangeTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( )&', u'ns3::NetDevice::LinkChangeTracedCallback&') typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::NetDevice::ReceiveCallback') typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::NetDevice::ReceiveCallback*') typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::NetDevice::ReceiveCallback&') typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', u'ns3::NetDevice::PromiscReceiveCallback') typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::NetDevice::PromiscReceiveCallback*') typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::NetDevice::PromiscReceiveCallback&') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) typehandlers.add_type_alias(u'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 >', u'ns3::Node::ProtocolHandler') typehandlers.add_type_alias(u'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 >*', u'ns3::Node::ProtocolHandler*') typehandlers.add_type_alias(u'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 >&', u'ns3::Node::ProtocolHandler&') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::Node::DeviceAdditionListener') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::Node::DeviceAdditionListener*') typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::Node::DeviceAdditionListener&') ## 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> >']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > )', u'ns3::Packet::TracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > )*', u'ns3::Packet::TracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > )&', u'ns3::Packet::TracedCallback&') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )', u'ns3::Packet::AddressTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )*', u'ns3::Packet::AddressTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Address const & )&', u'ns3::Packet::AddressTracedCallback&') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )', u'ns3::Packet::TwoAddressTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )*', u'ns3::Packet::TwoAddressTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const > const, ns3::Address const &, ns3::Address const & )&', u'ns3::Packet::TwoAddressTracedCallback&') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )', u'ns3::Packet::Mac48AddressTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )*', u'ns3::Packet::Mac48AddressTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, ns3::Mac48Address )&', u'ns3::Packet::Mac48AddressTracedCallback&') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t )', u'ns3::Packet::SizeTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t )*', u'ns3::Packet::SizeTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t )&', u'ns3::Packet::SizeTracedCallback&') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, double )', u'ns3::Packet::SinrTracedCallback') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, double )*', u'ns3::Packet::SinrTracedCallback*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Ptr< ns3::Packet const >, double )&', u'ns3::Packet::SinrTracedCallback&') ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class] module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['bool', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['ns3::ObjectBase *', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'const ns3::Ipv4Header &', 'ns3::Ptr<const ns3::Packet>', 'ns3::Ipv4L3Protocol::DropReason', 'ns3::Ptr<ns3::Ipv4>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'const ns3::Ipv4Header &', 'ns3::Ptr<const ns3::Packet>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::WifiMacHeader &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'const ns3::WifiMacHeader &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ipv4Address', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<const ns3::Packet>', 'const ns3::Ipv4Header &', 'ns3::Socket::SocketErrno', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<const ns3::Packet>', 'ns3::Ptr<ns3::Ipv4>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<const ns3::Packet>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Ipv4Route>', 'ns3::Ptr<const ns3::Packet>', 'const ns3::Ipv4Header &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<const ns3::Packet>', 'unsigned short', 'const ns3::Address &', 'const ns3::Address &', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> [class] module.add_class('CallbackImpl', import_from_module='ns.core', template_parameters=['void', 'ns3::Ptr<ns3::Socket>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], parent=root_module['ns3::CallbackImplBase']) ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting [class] module.add_class('Ipv4ListRouting', import_from_module='ns.internet', parent=root_module['ns3::Ipv4RoutingProtocol']) module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type=u'vector') module.add_container('std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::Ipv4Header > >', 'std::pair< ns3::Ptr< ns3::Packet >, ns3::Ipv4Header >', container_type=u'list') module.add_container('std::list< ns3::ArpCache::Entry * >', 'ns3::ArpCache::Entry *', container_type=u'list') module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type=u'map') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace 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) ## Register a nested module for the namespace aodv nested_module = module.add_cpp_namespace('aodv') register_types_ns3_aodv(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_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 *, std::size_t const )', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, std::size_t const )*', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, std::size_t const )&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, std::size_t const )', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, std::size_t const )*', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, std::size_t const )&', 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_types_ns3_aodv(module): root_module = module.get_root() ## aodv-rtable.h (module 'aodv'): ns3::aodv::RouteFlags [enumeration] module.add_enum('RouteFlags', ['VALID', 'INVALID', 'IN_SEARCH']) ## aodv-packet.h (module 'aodv'): ns3::aodv::MessageType [enumeration] module.add_enum('MessageType', ['AODVTYPE_RREQ', 'AODVTYPE_RREP', 'AODVTYPE_RERR', 'AODVTYPE_RREP_ACK']) ## aodv-dpd.h (module 'aodv'): ns3::aodv::DuplicatePacketDetection [class] module.add_class('DuplicatePacketDetection') ## aodv-id-cache.h (module 'aodv'): ns3::aodv::IdCache [class] module.add_class('IdCache') ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors [class] module.add_class('Neighbors') ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor [struct] module.add_class('Neighbor', outer_class=root_module['ns3::aodv::Neighbors']) ## aodv-rqueue.h (module 'aodv'): ns3::aodv::QueueEntry [class] module.add_class('QueueEntry') typehandlers.add_type_alias(u'ns3::Ipv4RoutingProtocol::UnicastForwardCallback', u'ns3::aodv::QueueEntry::UnicastForwardCallback') typehandlers.add_type_alias(u'ns3::Ipv4RoutingProtocol::UnicastForwardCallback*', u'ns3::aodv::QueueEntry::UnicastForwardCallback*') typehandlers.add_type_alias(u'ns3::Ipv4RoutingProtocol::UnicastForwardCallback&', u'ns3::aodv::QueueEntry::UnicastForwardCallback&') typehandlers.add_type_alias(u'ns3::Ipv4RoutingProtocol::ErrorCallback', u'ns3::aodv::QueueEntry::ErrorCallback') typehandlers.add_type_alias(u'ns3::Ipv4RoutingProtocol::ErrorCallback*', u'ns3::aodv::QueueEntry::ErrorCallback*') typehandlers.add_type_alias(u'ns3::Ipv4RoutingProtocol::ErrorCallback&', u'ns3::aodv::QueueEntry::ErrorCallback&') ## aodv-rqueue.h (module 'aodv'): ns3::aodv::RequestQueue [class] module.add_class('RequestQueue') ## aodv-packet.h (module 'aodv'): ns3::aodv::RerrHeader [class] module.add_class('RerrHeader', parent=root_module['ns3::Header']) ## aodv-routing-protocol.h (module 'aodv'): ns3::aodv::RoutingProtocol [class] module.add_class('RoutingProtocol', parent=root_module['ns3::Ipv4RoutingProtocol']) ## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTable [class] module.add_class('RoutingTable') ## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTableEntry [class] module.add_class('RoutingTableEntry') ## aodv-packet.h (module 'aodv'): ns3::aodv::RrepAckHeader [class] module.add_class('RrepAckHeader', parent=root_module['ns3::Header']) ## aodv-packet.h (module 'aodv'): ns3::aodv::RrepHeader [class] module.add_class('RrepHeader', parent=root_module['ns3::Header']) ## aodv-packet.h (module 'aodv'): ns3::aodv::RreqHeader [class] module.add_class('RreqHeader', parent=root_module['ns3::Header']) ## aodv-packet.h (module 'aodv'): ns3::aodv::TypeHeader [class] module.add_class('TypeHeader', parent=root_module['ns3::Header']) module.add_container('std::map< ns3::Ipv4Address, unsigned int >', ('ns3::Ipv4Address', 'unsigned int'), container_type=u'map') module.add_container('std::vector< ns3::Ipv4Address >', 'ns3::Ipv4Address', container_type=u'vector') def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3DefaultDeleter__Ns3AttributeAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeAccessor >']) register_Ns3DefaultDeleter__Ns3AttributeChecker_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeChecker >']) register_Ns3DefaultDeleter__Ns3AttributeValue_methods(root_module, root_module['ns3::DefaultDeleter< ns3::AttributeValue >']) register_Ns3DefaultDeleter__Ns3CallbackImplBase_methods(root_module, root_module['ns3::DefaultDeleter< ns3::CallbackImplBase >']) register_Ns3DefaultDeleter__Ns3EventImpl_methods(root_module, root_module['ns3::DefaultDeleter< ns3::EventImpl >']) register_Ns3DefaultDeleter__Ns3HashImplementation_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Hash::Implementation >']) register_Ns3DefaultDeleter__Ns3Ipv4Route_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Ipv4Route >']) register_Ns3DefaultDeleter__Ns3NixVector_methods(root_module, root_module['ns3::DefaultDeleter< ns3::NixVector >']) register_Ns3DefaultDeleter__Ns3Packet_methods(root_module, root_module['ns3::DefaultDeleter< ns3::Packet >']) register_Ns3DefaultDeleter__Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::DefaultDeleter< ns3::TraceSourceAccessor >']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) register_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >']) register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >']) register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >']) register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >']) register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >']) register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >']) register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv4RoutingHelper_methods(root_module, root_module['ns3::Ipv4RoutingHelper']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3Mac8Address_methods(root_module, root_module['ns3::Mac8Address']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3Timer_methods(root_module, root_module['ns3::Timer']) register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3AodvHelper_methods(root_module, root_module['ns3::AodvHelper']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream']) register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<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__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) register_Ns3SocketPriorityTag_methods(root_module, root_module['ns3::SocketPriorityTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable']) register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable']) register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable']) register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable']) register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable']) register_Ns3ArpCache_methods(root_module, root_module['ns3::ArpCache']) register_Ns3ArpCacheEntry_methods(root_module, root_module['ns3::ArpCache::Entry']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable']) register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable']) register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable']) register_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_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker']) register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue']) register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable']) register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable']) register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4Interface_methods(root_module, root_module['ns3::Ipv4Interface']) register_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute']) register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route']) register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Ns3ObjectBase___star___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ipv4L3ProtocolDropReason_Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Const_ns3WifiMacHeader___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, const ns3::WifiMacHeader &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ipv4Address_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Ipv4Header___amp___Ns3SocketSocketErrno_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Ipv4Route__gt___Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Ipv4Header___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, root_module['ns3::CallbackImpl< void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >']) register_Ns3Ipv4ListRouting_methods(root_module, root_module['ns3::Ipv4ListRouting']) 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']) register_Ns3AodvDuplicatePacketDetection_methods(root_module, root_module['ns3::aodv::DuplicatePacketDetection']) register_Ns3AodvIdCache_methods(root_module, root_module['ns3::aodv::IdCache']) register_Ns3AodvNeighbors_methods(root_module, root_module['ns3::aodv::Neighbors']) register_Ns3AodvNeighborsNeighbor_methods(root_module, root_module['ns3::aodv::Neighbors::Neighbor']) register_Ns3AodvQueueEntry_methods(root_module, root_module['ns3::aodv::QueueEntry']) register_Ns3AodvRequestQueue_methods(root_module, root_module['ns3::aodv::RequestQueue']) register_Ns3AodvRerrHeader_methods(root_module, root_module['ns3::aodv::RerrHeader']) register_Ns3AodvRoutingProtocol_methods(root_module, root_module['ns3::aodv::RoutingProtocol']) register_Ns3AodvRoutingTable_methods(root_module, root_module['ns3::aodv::RoutingTable']) register_Ns3AodvRoutingTableEntry_methods(root_module, root_module['ns3::aodv::RoutingTableEntry']) register_Ns3AodvRrepAckHeader_methods(root_module, root_module['ns3::aodv::RrepAckHeader']) register_Ns3AodvRrepHeader_methods(root_module, root_module['ns3::aodv::RrepHeader']) register_Ns3AodvRreqHeader_methods(root_module, root_module['ns3::aodv::RreqHeader']) register_Ns3AodvTypeHeader_methods(root_module, root_module['ns3::aodv::TypeHeader']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_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) [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) [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<const ns3::AttributeChecker> 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'): ns3::AttributeConstructionList::CIterator ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'ns3::AttributeConstructionList::CIterator', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::CIterator ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'ns3::AttributeConstructionList::CIterator', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<const ns3::AttributeChecker> 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) [constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetRemainingSize() const [member function] cls.add_method('GetRemainingSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Adjust(int32_t adjustment) [member function] cls.add_method('Adjust', 'void', [param('int32_t', 'adjustment')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [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_Ns3DefaultDeleter__Ns3AttributeAccessor_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeAccessor>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeAccessor> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeAccessor > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeAccessor>::Delete(ns3::AttributeAccessor * object) [member function] cls.add_method('Delete', 'void', [param('ns3::AttributeAccessor *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3AttributeChecker_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeChecker>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeChecker> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeChecker > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeChecker>::Delete(ns3::AttributeChecker * object) [member function] cls.add_method('Delete', 'void', [param('ns3::AttributeChecker *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3AttributeValue_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::AttributeValue>::DefaultDeleter(ns3::DefaultDeleter<ns3::AttributeValue> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::AttributeValue > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::AttributeValue>::Delete(ns3::AttributeValue * object) [member function] cls.add_method('Delete', 'void', [param('ns3::AttributeValue *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3CallbackImplBase_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::CallbackImplBase>::DefaultDeleter(ns3::DefaultDeleter<ns3::CallbackImplBase> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::CallbackImplBase > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::CallbackImplBase>::Delete(ns3::CallbackImplBase * object) [member function] cls.add_method('Delete', 'void', [param('ns3::CallbackImplBase *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3EventImpl_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::EventImpl>::DefaultDeleter(ns3::DefaultDeleter<ns3::EventImpl> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::EventImpl > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::EventImpl>::Delete(ns3::EventImpl * object) [member function] cls.add_method('Delete', 'void', [param('ns3::EventImpl *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3HashImplementation_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Hash::Implementation>::DefaultDeleter(ns3::DefaultDeleter<ns3::Hash::Implementation> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::Hash::Implementation > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::Hash::Implementation>::Delete(ns3::Hash::Implementation * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Hash::Implementation *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3Ipv4Route_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Ipv4Route>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Ipv4Route>::DefaultDeleter(ns3::DefaultDeleter<ns3::Ipv4Route> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::Ipv4Route > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::Ipv4Route>::Delete(ns3::Ipv4Route * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Ipv4Route *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3NixVector_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::NixVector>::DefaultDeleter(ns3::DefaultDeleter<ns3::NixVector> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::NixVector > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::NixVector>::Delete(ns3::NixVector * object) [member function] cls.add_method('Delete', 'void', [param('ns3::NixVector *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3Packet_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::Packet>::DefaultDeleter(ns3::DefaultDeleter<ns3::Packet> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::Packet > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::Packet>::Delete(ns3::Packet * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Packet *', 'object')], is_static=True) return def register_Ns3DefaultDeleter__Ns3TraceSourceAccessor_methods(root_module, cls): ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor>::DefaultDeleter() [constructor] cls.add_constructor([]) ## default-deleter.h (module 'core'): ns3::DefaultDeleter<ns3::TraceSourceAccessor>::DefaultDeleter(ns3::DefaultDeleter<ns3::TraceSourceAccessor> const & arg0) [constructor] cls.add_constructor([param('ns3::DefaultDeleter< ns3::TraceSourceAccessor > const &', 'arg0')]) ## default-deleter.h (module 'core'): static void ns3::DefaultDeleter<ns3::TraceSourceAccessor>::Delete(ns3::TraceSourceAccessor * object) [member function] cls.add_method('Delete', 'void', [param('ns3::TraceSourceAccessor *', 'object')], is_static=True) return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [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, std::size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('std::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, std::size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('std::size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Inet6SocketAddress_methods(root_module, cls): ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [constructor] cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor] cls.add_constructor([param('char const *', 'ipv6')]) ## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function] cls.add_method('ConvertFrom', 'ns3::Inet6SocketAddress', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function] cls.add_method('GetIpv6', 'ns3::Ipv6Address', [], is_const=True) ## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function] cls.add_method('SetIpv6', 'void', [param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) return def register_Ns3InetSocketAddress_methods(root_module, cls): ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [constructor] cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor] cls.add_constructor([param('char const *', 'ipv4')]) ## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::InetSocketAddress', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function] cls.add_method('GetIpv4', 'ns3::Ipv4Address', [], is_const=True) ## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet-socket-address.h (module 'network'): uint8_t ns3::InetSocketAddress::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ipv4Address', 'address')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3IntToType__0_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType(ns3::IntToType<0> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 0 > const &', 'arg0')]) return def register_Ns3IntToType__1_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType(ns3::IntToType<1> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 1 > const &', 'arg0')]) return def register_Ns3IntToType__2_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType(ns3::IntToType<2> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 2 > const &', 'arg0')]) return def register_Ns3IntToType__3_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType(ns3::IntToType<3> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 3 > const &', 'arg0')]) return def register_Ns3IntToType__4_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType(ns3::IntToType<4> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 4 > const &', 'arg0')]) return def register_Ns3IntToType__5_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType(ns3::IntToType<5> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')]) return def register_Ns3IntToType__6_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType(ns3::IntToType<6> const & arg0) [constructor] cls.add_constructor([param('ns3::IntToType< 6 > const &', 'arg0')]) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [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_Ns3Ipv4InterfaceAddress_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [constructor] cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function] cls.add_method('GetLocal', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function] cls.add_method('GetMask', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function] cls.add_method('IsSecondary', 'bool', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function] cls.add_method('SetBroadcast', 'void', [param('ns3::Ipv4Address', 'broadcast')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv4Address', 'local')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function] cls.add_method('SetMask', 'void', [param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function] cls.add_method('SetPrimary', 'void', []) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function] cls.add_method('SetSecondary', 'void', []) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv4RoutingHelper_methods(root_module, cls): ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper() [constructor] cls.add_constructor([]) ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper(ns3::Ipv4RoutingHelper const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4RoutingHelper const &', 'arg0')]) ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper * ns3::Ipv4RoutingHelper::Copy() const [member function] cls.add_method('Copy', 'ns3::Ipv4RoutingHelper *', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-helper.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4RoutingHelper::Create(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheAllAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheAllEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) [member function] cls.add_method('PrintRoutingTableAllAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) [member function] cls.add_method('PrintRoutingTableAllEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) [member function] cls.add_method('PrintRoutingTableAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) [member function] cls.add_method('PrintRoutingTableEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_static=True) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [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::MakeAutoconfiguredAddress(ns3::Mac8Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac8Address', '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::MakeAutoconfiguredLinkLocalAddress(ns3::Mac8Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac8Address', '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_output_stream_operator() cls.add_binary_comparison_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) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_operator() ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3Mac8Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() ## mac8-address.h (module 'network'): ns3::Mac8Address::Mac8Address(ns3::Mac8Address const & arg0) [constructor] cls.add_constructor([param('ns3::Mac8Address const &', 'arg0')]) ## mac8-address.h (module 'network'): ns3::Mac8Address::Mac8Address() [constructor] cls.add_constructor([]) ## mac8-address.h (module 'network'): ns3::Mac8Address::Mac8Address(uint8_t addr) [constructor] cls.add_constructor([param('uint8_t', 'addr')]) ## mac8-address.h (module 'network'): static ns3::Mac8Address ns3::Mac8Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac8Address', [], is_static=True) ## mac8-address.h (module 'network'): static ns3::Mac8Address ns3::Mac8Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac8Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac8-address.h (module 'network'): void ns3::Mac8Address::CopyFrom(uint8_t const * pBuffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'pBuffer')]) ## mac8-address.h (module 'network'): void ns3::Mac8Address::CopyTo(uint8_t * pBuffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'pBuffer')], is_const=True) ## mac8-address.h (module 'network'): static ns3::Mac8Address ns3::Mac8Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac8Address', [], is_static=True) ## mac8-address.h (module 'network'): static bool ns3::Mac8Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [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'): ns3::NodeContainer::Iterator ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', 'ns3::NodeContainer::Iterator', [], is_const=True) ## node-container.h (module 'network'): bool ns3::NodeContainer::Contains(uint32_t id) const [member function] cls.add_method('Contains', 'bool', [param('uint32_t', 'id')], 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'): ns3::NodeContainer::Iterator ns3::NodeContainer::End() const [member function] cls.add_method('End', 'ns3::NodeContainer::Iterator', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [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) [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) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::type [variable] cls.add_instance_attribute('type', 'ns3::PacketMetadata::Item::ItemType', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 1 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static uint64_t ns3::Simulator::GetEventCount() [member function] cls.add_method('GetEventCount', 'uint64_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & delay) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'delay')], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [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 v) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t v) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'v')]) ## 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) [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_Ns3Timer_methods(root_module, cls): ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [constructor] cls.add_constructor([param('ns3::Timer const &', 'arg0')]) ## timer.h (module 'core'): ns3::Timer::Timer() [constructor] cls.add_constructor([]) ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor] cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')]) ## timer.h (module 'core'): void ns3::Timer::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function] cls.add_method('GetDelay', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function] cls.add_method('GetState', 'ns3::Timer::State', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function] cls.add_method('IsSuspended', 'bool', [], is_const=True) ## timer.h (module 'core'): void ns3::Timer::Remove() [member function] cls.add_method('Remove', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Resume() [member function] cls.add_method('Resume', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule() [member function] cls.add_method('Schedule', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function] cls.add_method('Schedule', 'void', [param('ns3::Time', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function] cls.add_method('SetDelay', 'void', [param('ns3::Time const &', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::Suspend() [member function] cls.add_method('Suspend', 'void', []) return def register_Ns3TimerImpl_methods(root_module, cls): ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor] cls.add_constructor([]) ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [constructor] cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')]) ## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function] cls.add_method('Invoke', 'void', [], is_pure_virtual=True, is_virtual=True) ## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function] cls.add_method('Schedule', 'ns3::EventId', [param('ns3::Time const &', 'delay')], is_pure_virtual=True, is_virtual=True) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('<') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [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<const ns3::AttributeAccessor> accessor, ns3::Ptr<const ns3::AttributeChecker> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SupportLevel::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::SupportLevel::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<const ns3::AttributeAccessor> accessor, ns3::Ptr<const ns3::AttributeChecker> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SupportLevel::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::SupportLevel::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<const ns3::TraceSourceAccessor> 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<const ns3::TraceSourceAccessor> accessor, std::string callback, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SupportLevel::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::SupportLevel::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(std::size_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('std::size_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(std::size_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('std::size_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::size_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'std::size_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'): ns3::TypeId::hash_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'ns3::TypeId::hash_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(uint16_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint16_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint16_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint16_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(std::size_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('std::size_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::size_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'std::size_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(ns3::TypeId::hash_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(ns3::TypeId::hash_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<const ns3::TraceSourceAccessor> 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<const ns3::TraceSourceAccessor> 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(std::size_t i, ns3::Ptr<const ns3::AttributeValue> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('std::size_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) [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) 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) [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_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) [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::Time'], root_module['ns3::int64x64_t'], param('ns3::Time 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_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_comparison_operator('!=') cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('>=') cls.add_output_stream_operator() 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_unary_numeric_operator('-') ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(double const value) [constructor] cls.add_constructor([param('double const', 'value')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long double const value) [constructor] cls.add_constructor([param('long double const', 'value')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(int const v) [constructor] cls.add_constructor([param('int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long int const v) [constructor] cls.add_constructor([param('long int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int const v) [constructor] cls.add_constructor([param('long long int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int const v) [constructor] cls.add_constructor([param('unsigned int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int const v) [constructor] cls.add_constructor([param('long unsigned int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int const v) [constructor] cls.add_constructor([param('long long unsigned int const', 'v')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t const hi, uint64_t const lo) [constructor] cls.add_constructor([param('int64_t const', 'hi'), param('uint64_t const', 'lo')]) ## int64x64-128.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-128.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-128.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-128.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-128.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t const v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t const', 'v')], is_static=True) ## int64x64-128.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-128.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_Ns3AodvHelper_methods(root_module, cls): ## aodv-helper.h (module 'aodv'): ns3::AodvHelper::AodvHelper(ns3::AodvHelper const & arg0) [constructor] cls.add_constructor([param('ns3::AodvHelper const &', 'arg0')]) ## aodv-helper.h (module 'aodv'): ns3::AodvHelper::AodvHelper() [constructor] cls.add_constructor([]) ## aodv-helper.h (module 'aodv'): int64_t ns3::AodvHelper::AssignStreams(ns3::NodeContainer c, int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('ns3::NodeContainer', 'c'), param('int64_t', 'stream')]) ## aodv-helper.h (module 'aodv'): ns3::AodvHelper * ns3::AodvHelper::Copy() const [member function] cls.add_method('Copy', 'ns3::AodvHelper *', [], is_const=True, is_virtual=True) ## aodv-helper.h (module 'aodv'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::AodvHelper::Create(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True, is_virtual=True) ## aodv-helper.h (module 'aodv'): void ns3::AodvHelper::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')], is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Ipv4Header_methods(root_module, cls): ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')]) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor] cls.add_constructor([]) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function] cls.add_method('DscpTypeToString', 'std::string', [param('ns3::Ipv4Header::DscpType', 'dscp')], is_const=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function] cls.add_method('EcnTypeToString', 'std::string', [param('ns3::Ipv4Header::EcnType', 'ecn')], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function] cls.add_method('EnableChecksum', 'void', []) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function] cls.add_method('GetDscp', 'ns3::Ipv4Header::DscpType', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function] cls.add_method('GetEcn', 'ns3::Ipv4Header::EcnType', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function] cls.add_method('GetFragmentOffset', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function] cls.add_method('GetIdentification', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function] cls.add_method('GetPayloadSize', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function] cls.add_method('IsChecksumOk', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function] cls.add_method('IsDontFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function] cls.add_method('IsLastFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'destination')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function] cls.add_method('SetDontFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function] cls.add_method('SetDscp', 'void', [param('ns3::Ipv4Header::DscpType', 'dscp')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function] cls.add_method('SetEcn', 'void', [param('ns3::Ipv4Header::EcnType', 'ecn')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function] cls.add_method('SetFragmentOffset', 'void', [param('uint16_t', 'offsetBytes')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function] cls.add_method('SetIdentification', 'void', [param('uint16_t', 'identification')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function] cls.add_method('SetLastFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function] cls.add_method('SetMayFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function] cls.add_method('SetMoreFragments', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function] cls.add_method('SetPayloadSize', 'void', [param('uint16_t', 'size')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function] cls.add_method('SetProtocol', 'void', [param('uint8_t', 'num')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'source')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) 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) [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) [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<const ns3::Object> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4MulticastRoute > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4Route > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')]) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) 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) [constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) return def register_Ns3Socket_methods(root_module, cls): ## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [constructor] cls.add_constructor([param('ns3::Socket const &', 'arg0')]) ## socket.h (module 'network'): ns3::Socket::Socket() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function] cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind() [member function] cls.add_method('Bind', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind6() [member function] cls.add_method('Bind6', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function] cls.add_method('BindToNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'netdevice')], is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Close() [member function] cls.add_method('Close', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function] cls.add_method('Connect', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function] cls.add_method('GetAllowBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function] cls.add_method('GetBoundNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function] cls.add_method('GetErrno', 'ns3::Socket::SocketErrno', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTos() const [member function] cls.add_method('GetIpTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function] cls.add_method('GetIpTtl', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function] cls.add_method('GetIpv6HopLimit', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function] cls.add_method('GetIpv6Tclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetPeerName(ns3::Address & address) const [member function] cls.add_method('GetPeerName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): static uint8_t ns3::Socket::IpTos2Priority(uint8_t ipTos) [member function] cls.add_method('IpTos2Priority', 'uint8_t', [param('uint8_t', 'ipTos')], is_static=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address, ns3::Socket::Ipv6MulticastFilterMode filterMode, std::vector<ns3::Ipv6Address, std::allocator<ns3::Ipv6Address> > sourceAddresses) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address'), param('ns3::Socket::Ipv6MulticastFilterMode', 'filterMode'), param('std::vector< ns3::Ipv6Address >', 'sourceAddresses')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6LeaveGroup() [member function] cls.add_method('Ipv6LeaveGroup', 'void', [], is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function] cls.add_method('IsIpRecvTos', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function] cls.add_method('IsIpRecvTtl', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function] cls.add_method('IsIpv6RecvHopLimit', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function] cls.add_method('IsIpv6RecvTclass', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function] cls.add_method('IsRecvPktInfo', 'bool', [], is_const=True) ## socket.h (module 'network'): int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Recv', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function] cls.add_method('SendTo', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')]) ## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function] cls.add_method('SetAcceptCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')]) ## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function] cls.add_method('SetCloseCallbacks', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')]) ## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function] cls.add_method('SetConnectCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')]) ## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function] cls.add_method('SetDataSentCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function] cls.add_method('SetIpRecvTos', 'void', [param('bool', 'ipv4RecvTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function] cls.add_method('SetIpRecvTtl', 'void', [param('bool', 'ipv4RecvTtl')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function] cls.add_method('SetIpTos', 'void', [param('uint8_t', 'ipTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function] cls.add_method('SetIpTtl', 'void', [param('uint8_t', 'ipTtl')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function] cls.add_method('SetIpv6HopLimit', 'void', [param('uint8_t', 'ipHopLimit')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function] cls.add_method('SetIpv6RecvHopLimit', 'void', [param('bool', 'ipv6RecvHopLimit')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function] cls.add_method('SetIpv6RecvTclass', 'void', [param('bool', 'ipv6RecvTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function] cls.add_method('SetIpv6Tclass', 'void', [param('int', 'ipTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function] cls.add_method('SetRecvCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function] cls.add_method('SetRecvPktInfo', 'void', [param('bool', 'flag')]) ## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function] cls.add_method('SetSendCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')]) ## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function] cls.add_method('IsManualIpTtl', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function] cls.add_method('IsManualIpv6HopLimit', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function] cls.add_method('IsManualIpv6Tclass', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function] cls.add_method('NotifyConnectionFailed', 'void', [], visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function] cls.add_method('NotifyConnectionRequest', 'bool', [param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function] cls.add_method('NotifyConnectionSucceeded', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function] cls.add_method('NotifyDataRecv', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function] cls.add_method('NotifyDataSent', 'void', [param('uint32_t', 'size')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function] cls.add_method('NotifyErrorClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function] cls.add_method('NotifyNewConnectionCreated', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function] cls.add_method('NotifyNormalClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function] cls.add_method('NotifySend', 'void', [param('uint32_t', 'spaceAvailable')], visibility='protected') return def register_Ns3SocketIpTosTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3SocketIpTtlTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'hopLimit')]) return def register_Ns3SocketIpv6TclassTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function] cls.add_method('GetTclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function] cls.add_method('SetTclass', 'void', [param('uint8_t', 'tclass')]) return def register_Ns3SocketPriorityTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag(ns3::SocketPriorityTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketPriorityTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketPriorityTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketPriorityTag::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::SocketPriorityTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketPriorityTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [constructor] cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function] cls.add_method('Disable', 'void', []) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function] cls.add_method('Enable', 'void', []) ## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('>=') cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') 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_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], 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_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::int64x64_t const &', u'right')) 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() ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [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) [constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')], is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TriangularRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::TriangularRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable::TriangularRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue(double mean, double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger(uint32_t mean, uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3UniformRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3WeibullRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function] cls.add_method('GetScale', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'scale'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZetaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZipfRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'n'), param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'n'), param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ArpCache_methods(root_module, cls): ## arp-cache.h (module 'internet'): ns3::ArpCache::ArpCache() [constructor] cls.add_constructor([]) ## arp-cache.h (module 'internet'): ns3::ArpCache::Entry * ns3::ArpCache::Add(ns3::Ipv4Address to) [member function] cls.add_method('Add', 'ns3::ArpCache::Entry *', [param('ns3::Ipv4Address', 'to')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::Flush() [member function] cls.add_method('Flush', 'void', []) ## arp-cache.h (module 'internet'): ns3::Time ns3::ArpCache::GetAliveTimeout() const [member function] cls.add_method('GetAliveTimeout', 'ns3::Time', [], is_const=True) ## arp-cache.h (module 'internet'): ns3::Time ns3::ArpCache::GetDeadTimeout() const [member function] cls.add_method('GetDeadTimeout', 'ns3::Time', [], is_const=True) ## arp-cache.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::ArpCache::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## arp-cache.h (module 'internet'): ns3::Ptr<ns3::Ipv4Interface> ns3::ArpCache::GetInterface() const [member function] cls.add_method('GetInterface', 'ns3::Ptr< ns3::Ipv4Interface >', [], is_const=True) ## arp-cache.h (module 'internet'): static ns3::TypeId ns3::ArpCache::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## arp-cache.h (module 'internet'): ns3::Time ns3::ArpCache::GetWaitReplyTimeout() const [member function] cls.add_method('GetWaitReplyTimeout', 'ns3::Time', [], is_const=True) ## arp-cache.h (module 'internet'): ns3::ArpCache::Entry * ns3::ArpCache::Lookup(ns3::Ipv4Address destination) [member function] cls.add_method('Lookup', 'ns3::ArpCache::Entry *', [param('ns3::Ipv4Address', 'destination')]) ## arp-cache.h (module 'internet'): std::list<ns3::ArpCache::Entry *, std::allocator<ns3::ArpCache::Entry *> > ns3::ArpCache::LookupInverse(ns3::Address destination) [member function] cls.add_method('LookupInverse', 'std::list< ns3::ArpCache::Entry * >', [param('ns3::Address', 'destination')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::PrintArpCache(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintArpCache', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::Remove(ns3::ArpCache::Entry * entry) [member function] cls.add_method('Remove', 'void', [param('ns3::ArpCache::Entry *', 'entry')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::SetAliveTimeout(ns3::Time aliveTimeout) [member function] cls.add_method('SetAliveTimeout', 'void', [param('ns3::Time', 'aliveTimeout')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::SetArpRequestCallback(ns3::Callback<void, ns3::Ptr<const ns3::ArpCache>, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arpRequestCallback) [member function] cls.add_method('SetArpRequestCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::ArpCache const >, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arpRequestCallback')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::SetDeadTimeout(ns3::Time deadTimeout) [member function] cls.add_method('SetDeadTimeout', 'void', [param('ns3::Time', 'deadTimeout')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::SetDevice(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::Ipv4Interface> interface) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Ipv4Interface >', 'interface')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::SetWaitReplyTimeout(ns3::Time waitReplyTimeout) [member function] cls.add_method('SetWaitReplyTimeout', 'void', [param('ns3::Time', 'waitReplyTimeout')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::StartWaitReplyTimer() [member function] cls.add_method('StartWaitReplyTimer', 'void', []) ## arp-cache.h (module 'internet'): void ns3::ArpCache::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3ArpCacheEntry_methods(root_module, cls): ## arp-cache.h (module 'internet'): ns3::ArpCache::Entry::Entry(ns3::ArpCache::Entry const & arg0) [constructor] cls.add_constructor([param('ns3::ArpCache::Entry const &', 'arg0')]) ## arp-cache.h (module 'internet'): ns3::ArpCache::Entry::Entry(ns3::ArpCache * arp) [constructor] cls.add_constructor([param('ns3::ArpCache *', 'arp')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::ClearPendingPacket() [member function] cls.add_method('ClearPendingPacket', 'void', []) ## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::ClearRetries() [member function] cls.add_method('ClearRetries', 'void', []) ## arp-cache.h (module 'internet'): ns3::ArpCache::Ipv4PayloadHeaderPair ns3::ArpCache::Entry::DequeuePending() [member function] cls.add_method('DequeuePending', 'ns3::ArpCache::Ipv4PayloadHeaderPair', []) ## arp-cache.h (module 'internet'): ns3::Ipv4Address ns3::ArpCache::Entry::GetIpv4Address() const [member function] cls.add_method('GetIpv4Address', 'ns3::Ipv4Address', [], is_const=True) ## arp-cache.h (module 'internet'): ns3::Address ns3::ArpCache::Entry::GetMacAddress() const [member function] cls.add_method('GetMacAddress', 'ns3::Address', [], is_const=True) ## arp-cache.h (module 'internet'): uint32_t ns3::ArpCache::Entry::GetRetries() const [member function] cls.add_method('GetRetries', 'uint32_t', [], is_const=True) ## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::IncrementRetries() [member function] cls.add_method('IncrementRetries', 'void', []) ## arp-cache.h (module 'internet'): bool ns3::ArpCache::Entry::IsAlive() [member function] cls.add_method('IsAlive', 'bool', []) ## arp-cache.h (module 'internet'): bool ns3::ArpCache::Entry::IsDead() [member function] cls.add_method('IsDead', 'bool', []) ## arp-cache.h (module 'internet'): bool ns3::ArpCache::Entry::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## arp-cache.h (module 'internet'): bool ns3::ArpCache::Entry::IsPermanent() [member function] cls.add_method('IsPermanent', 'bool', []) ## arp-cache.h (module 'internet'): bool ns3::ArpCache::Entry::IsWaitReply() [member function] cls.add_method('IsWaitReply', 'bool', []) ## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::MarkAlive(ns3::Address macAddress) [member function] cls.add_method('MarkAlive', 'void', [param('ns3::Address', 'macAddress')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::MarkDead() [member function] cls.add_method('MarkDead', 'void', []) ## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::MarkPermanent() [member function] cls.add_method('MarkPermanent', 'void', []) ## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::MarkWaitReply(ns3::ArpCache::Ipv4PayloadHeaderPair waiting) [member function] cls.add_method('MarkWaitReply', 'void', [param('std::pair< ns3::Ptr< ns3::Packet >, ns3::Ipv4Header >', 'waiting')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::SetIpv4Address(ns3::Ipv4Address destination) [member function] cls.add_method('SetIpv4Address', 'void', [param('ns3::Ipv4Address', 'destination')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::SetMacAddress(ns3::Address macAddress) [member function] cls.add_method('SetMacAddress', 'void', [param('ns3::Address', 'macAddress')]) ## arp-cache.h (module 'internet'): void ns3::ArpCache::Entry::UpdateSeen() [member function] cls.add_method('UpdateSeen', 'void', []) ## arp-cache.h (module 'internet'): bool ns3::ArpCache::Entry::UpdateWaitReply(ns3::ArpCache::Ipv4PayloadHeaderPair waiting) [member function] cls.add_method('UpdateWaitReply', 'bool', [param('std::pair< ns3::Ptr< ns3::Packet >, ns3::Ipv4Header >', 'waiting')]) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [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) [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) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [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) [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<const ns3::CallbackImplBase> 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') ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::ObjectBase*']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'void']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ipv4Address']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::Ipv4Route> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::Packet const> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ipv4Header const&']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Socket::SocketErrno']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::NetDevice> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'unsigned short']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Address const&']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::NetDevice::PacketType']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::Socket> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'bool']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'unsigned int']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ptr<ns3::Ipv4> ']) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::GetCppTypeid() [member function] cls.add_method('GetCppTypeid', 'std::string', [], is_static=True, visibility='protected', template_parameters=[u'ns3::Ipv4L3Protocol::DropReason']) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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, std::size_t length) [member function] cls.add_method('SetValueArray', 'void', [param('double *', 'values'), param('std::size_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) [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) [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) [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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3EnumChecker_methods(root_module, cls): ## enum.h (module 'core'): ns3::EnumChecker::EnumChecker(ns3::EnumChecker const & arg0) [constructor] cls.add_constructor([param('ns3::EnumChecker const &', 'arg0')]) ## enum.h (module 'core'): ns3::EnumChecker::EnumChecker() [constructor] cls.add_constructor([]) ## enum.h (module 'core'): void ns3::EnumChecker::Add(int value, std::string name) [member function] cls.add_method('Add', 'void', [param('int', 'value'), param('std::string', 'name')]) ## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int value, std::string name) [member function] cls.add_method('AddDefault', 'void', [param('int', 'value'), param('std::string', 'name')]) ## enum.h (module 'core'): bool ns3::EnumChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) ## enum.h (module 'core'): bool ns3::EnumChecker::Copy(ns3::AttributeValue const & src, ns3::AttributeValue & dst) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'src'), param('ns3::AttributeValue &', 'dst')], is_const=True, is_virtual=True) ## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): std::string ns3::EnumChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): std::string ns3::EnumChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): bool ns3::EnumChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_const=True, is_virtual=True) return def register_Ns3EnumValue_methods(root_module, cls): ## enum.h (module 'core'): ns3::EnumValue::EnumValue(ns3::EnumValue const & arg0) [constructor] cls.add_constructor([param('ns3::EnumValue const &', 'arg0')]) ## enum.h (module 'core'): ns3::EnumValue::EnumValue() [constructor] cls.add_constructor([]) ## enum.h (module 'core'): ns3::EnumValue::EnumValue(int value) [constructor] cls.add_constructor([param('int', 'value')]) ## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): bool ns3::EnumValue::DeserializeFromString(std::string value, ns3::Ptr<const ns3::AttributeChecker> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## enum.h (module 'core'): int ns3::EnumValue::Get() const [member function] cls.add_method('Get', 'int', [], is_const=True) ## enum.h (module 'core'): std::string ns3::EnumValue::SerializeToString(ns3::Ptr<const ns3::AttributeChecker> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## enum.h (module 'core'): void ns3::EnumValue::Set(int value) [member function] cls.add_method('Set', 'void', [param('int', 'value')]) 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) [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_Ns3Ipv4_methods(root_module, cls): ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')]) ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor] cls.add_constructor([]) ## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): static ns3::TypeId ns3::Ipv4::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsForwarding(uint32_t interface) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsUp(uint32_t interface) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetDown(uint32_t interface) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetForwarding(uint32_t interface, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'interface'), param('bool', 'val')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetMetric(uint32_t interface, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'interface'), param('uint16_t', 'metric')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetUp(uint32_t interface) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SourceAddressSelection(uint32_t interface, ns3::Ipv4Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv4Address', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'dest')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], is_pure_virtual=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], is_pure_virtual=True, visibility='private', is_virtual=True) 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) [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::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3Ipv4Interface_methods(root_module, cls): ## ipv4-interface.h (module 'internet'): static ns3::TypeId ns3::Ipv4Interface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-interface.h (module 'internet'): ns3::Ipv4Interface::Ipv4Interface() [constructor] cls.add_constructor([]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetTrafficControl(ns3::Ptr<ns3::TrafficControlLayer> tc) [member function] cls.add_method('SetTrafficControl', 'void', [param('ns3::Ptr< ns3::TrafficControlLayer >', 'tc')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetArpCache(ns3::Ptr<ns3::ArpCache> arpCache) [member function] cls.add_method('SetArpCache', 'void', [param('ns3::Ptr< ns3::ArpCache >', 'arpCache')]) ## ipv4-interface.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Interface::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-interface.h (module 'internet'): ns3::Ptr<ns3::ArpCache> ns3::Ipv4Interface::GetArpCache() const [member function] cls.add_method('GetArpCache', 'ns3::Ptr< ns3::ArpCache >', [], is_const=True) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetMetric(uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint16_t', 'metric')]) ## ipv4-interface.h (module 'internet'): uint16_t ns3::Ipv4Interface::GetMetric() const [member function] cls.add_method('GetMetric', 'uint16_t', [], is_const=True) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsUp() const [member function] cls.add_method('IsUp', 'bool', [], is_const=True) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsDown() const [member function] cls.add_method('IsDown', 'bool', [], is_const=True) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetUp() [member function] cls.add_method('SetUp', 'void', []) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetDown() [member function] cls.add_method('SetDown', 'void', []) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::IsForwarding() const [member function] cls.add_method('IsForwarding', 'bool', [], is_const=True) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::SetForwarding(bool val) [member function] cls.add_method('SetForwarding', 'void', [param('bool', 'val')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::Send(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & hdr, ns3::Ipv4Address dest) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'hdr'), param('ns3::Ipv4Address', 'dest')]) ## ipv4-interface.h (module 'internet'): bool ns3::Ipv4Interface::AddAddress(ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('ns3::Ipv4InterfaceAddress', 'address')]) ## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::GetAddress(uint32_t index) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'index')], is_const=True) ## ipv4-interface.h (module 'internet'): uint32_t ns3::Ipv4Interface::GetNAddresses() const [member function] cls.add_method('GetNAddresses', 'uint32_t', [], is_const=True) ## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::RemoveAddress(uint32_t index) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'index')]) ## ipv4-interface.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4Interface::RemoveAddress(ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv4InterfaceAddress', [param('ns3::Ipv4Address', 'address')]) ## ipv4-interface.h (module 'internet'): void ns3::Ipv4Interface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Ipv4L3Protocol_methods(root_module, cls): ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::Ipv4L3Protocol() [constructor] cls.add_constructor([]) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::AddAddress(uint32_t i, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'i'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4L3Protocol::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4L3Protocol::GetAddress(uint32_t interfaceIndex, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Interface> ns3::Ipv4L3Protocol::GetInterface(uint32_t i) const [member function] cls.add_method('GetInterface', 'ns3::Ptr< ns3::Ipv4Interface >', [param('uint32_t', 'i')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForAddress(ns3::Ipv4Address addr) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'addr')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForPrefix(ns3::Ipv4Address addr, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'addr'), param('ns3::Ipv4Mask', 'mask')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMetric(uint32_t i) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMtu(uint32_t i) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4L3Protocol::GetNetDevice(uint32_t i) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4L3Protocol::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4L3Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsForwarding(uint32_t i) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUnicast(ns3::Ipv4Address ad) const [member function] cls.add_method('IsUnicast', 'bool', [param('ns3::Ipv4Address', 'ad')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUp(uint32_t i) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Receive(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> p, uint16_t protocol, ns3::Address const & from, ns3::Address const & to, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'p'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'from'), param('ns3::Address const &', 'to'), param('ns3::NetDevice::PacketType', 'packetType')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interfaceIndex, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDefaultTtl(uint8_t ttl) [member function] cls.add_method('SetDefaultTtl', 'void', [param('uint8_t', 'ttl')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDown(uint32_t i) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetForwarding(uint32_t i, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'i'), param('bool', 'val')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetMetric(uint32_t i, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'i'), param('uint16_t', 'metric')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetUp(uint32_t i) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::SourceAddressSelection(uint32_t interface, ns3::Ipv4Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv4Address', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'dest')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::PROT_NUMBER [variable] cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], visibility='private', is_virtual=True) 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) [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::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3Ipv4MulticastRoute_methods(root_module, cls): ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function] cls.add_method('GetGroup', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function] cls.add_method('GetOrigin', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<const unsigned int, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function] cls.add_method('GetOutputTtlMap', 'std::map< unsigned int, unsigned int >', [], is_const=True) ## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function] cls.add_method('GetParent', 'uint32_t', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function] cls.add_method('SetGroup', 'void', [param('ns3::Ipv4Address const', 'group')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function] cls.add_method('SetOrigin', 'void', [param('ns3::Ipv4Address const', 'origin')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function] cls.add_method('SetOutputTtl', 'void', [param('uint32_t', 'oif'), param('uint32_t', 'ttl')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function] cls.add_method('SetParent', 'void', [param('uint32_t', 'iif')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable] cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable] cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True) return def register_Ns3Ipv4Route_methods(root_module, cls): cls.add_output_stream_operator() ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function] cls.add_method('GetGateway', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'dest')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function] cls.add_method('SetGateway', 'void', [param('ns3::Ipv4Address', 'gw')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function] cls.add_method('SetOutputDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'src')]) return def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls): ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor] cls.add_constructor([]) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')]) ## ipv4-routing-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Ipv4RoutingProtocol::UnicastForwardCallback ucb, ns3::Ipv4RoutingProtocol::MulticastForwardCallback mcb, ns3::Ipv4RoutingProtocol::LocalDeliverCallback lcb, ns3::Ipv4RoutingProtocol::ErrorCallback ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_pure_virtual=True, is_virtual=True) 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) [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::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_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_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<const ns3::AttributeChecker> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<const ns3::AttributeChecker> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac48Address const &', 'value')]) return def register_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) [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::NetDevice::PromiscReceiveCallback cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::NetDevice::ReceiveCallback cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [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::Node::DeviceAdditionListener 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::Node::ProtocolHandler 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::Node::DeviceAdditionListener 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::Node::ProtocolHandler 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) [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::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::ios_base::openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::ios_base::openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header, uint32_t size) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header'), param('uint32_t', 'size')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) ## packet.h (module 'network'): std::string ns3::Packet::ToString() const [member function] cls.add_method('ToString', 'std::string', [], is_const=True) return def register_Ns3ParetoRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], deprecated=True, is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetScale() const [member function] cls.add_method('GetScale', '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 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::ParetoRandomVariable::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::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_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## 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::TimeValue::TimeValue(ns3::TimeValue const & arg0) [constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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) [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::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_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) [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::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## 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<const ns3::AttributeChecker> 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<const ns3::AttributeChecker> 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_Ns3CallbackImpl__Bool_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackImpl<bool, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0, ns3::Address const & arg1) [member operator] cls.add_method('operator()', 'bool', [param('ns3::Ptr< ns3::Socket >', 'arg0'), param('ns3::Address const &', 'arg1')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Ns3ObjectBase___star___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): ns3::ObjectBase * ns3::CallbackImpl<ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()() [member operator] cls.add_method('operator()', 'ns3::ObjectBase *', [], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ipv4L3ProtocolDropReason_Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr< ns3::Ipv4 >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ipv4Header const & arg0, ns3::Ptr<const ns3::Packet> arg1, ns3::Ipv4L3Protocol::DropReason arg2, ns3::Ptr<ns3::Ipv4> arg3, unsigned int arg4) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ipv4Header const &', 'arg0'), param('ns3::Ptr< ns3::Packet const >', 'arg1'), param('ns3::Ipv4L3Protocol::DropReason', 'arg2'), param('ns3::Ptr< ns3::Ipv4 >', 'arg3'), param('unsigned int', 'arg4')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Const_ns3Ipv4Header___amp___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ipv4Header const &, ns3::Ptr< ns3::Packet const >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, const ns3::Ipv4Header &, ns3::Ptr<const ns3::Packet>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ipv4Header const & arg0, ns3::Ptr<const ns3::Packet> arg1, unsigned int arg2) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ipv4Header const &', 'arg0'), param('ns3::Ptr< ns3::Packet const >', 'arg1'), param('unsigned int', 'arg2')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Const_ns3WifiMacHeader___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::WifiMacHeader &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, const ns3::WifiMacHeader &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, const ns3::WifiMacHeader &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, const ns3::WifiMacHeader &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, const ns3::WifiMacHeader &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, const ns3::WifiMacHeader &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::WifiMacHeader const & arg0) [member operator] cls.add_method('operator()', 'void', [param('ns3::WifiMacHeader const &', 'arg0')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ipv4Address_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ipv4Address arg0) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ipv4Address', 'arg0')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Ipv4Header___amp___Ns3SocketSocketErrno_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<const ns3::Packet> arg0, ns3::Ipv4Header const & arg1, ns3::Socket::SocketErrno arg2) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Packet const >', 'arg0'), param('ns3::Ipv4Header const &', 'arg1'), param('ns3::Socket::SocketErrno', 'arg2')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Ptr__lt__ns3Ipv4__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Packet const >, ns3::Ptr< ns3::Ipv4 >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::Ptr<ns3::Ipv4>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<const ns3::Packet> arg0, ns3::Ptr<ns3::Ipv4> arg1, unsigned int arg2) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Packet const >', 'arg0'), param('ns3::Ptr< ns3::Ipv4 >', 'arg1'), param('unsigned int', 'arg2')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__const_ns3Packet__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<const ns3::Packet>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<const ns3::Packet> arg0) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Packet const >', 'arg0')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Ipv4Route__gt___Ns3Ptr__lt__const_ns3Packet__gt___Const_ns3Ipv4Header___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Ipv4Route> arg0, ns3::Ptr<const ns3::Packet> arg1, ns3::Ipv4Header const & arg2) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Ipv4Route >', 'arg0'), param('ns3::Ptr< ns3::Packet const >', 'arg1'), param('ns3::Ipv4Header const &', 'arg2')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Ptr__lt__const_ns3Packet__gt___Unsigned_short_Const_ns3Address___amp___Const_ns3Address___amp___Ns3NetDevicePacketType_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< 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 > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<const ns3::Packet>, unsigned short, const ns3::Address &, const ns3::Address &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::NetDevice> arg0, ns3::Ptr<const ns3::Packet> arg1, short unsigned int arg2, ns3::Address const & arg3, ns3::Address const & arg4, ns3::NetDevice::PacketType arg5) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'arg0'), param('ns3::Ptr< ns3::Packet const >', 'arg1'), param('short unsigned int', 'arg2'), param('ns3::Address const &', 'arg3'), param('ns3::Address const &', 'arg4'), param('ns3::NetDevice::PacketType', 'arg5')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3NetDevice__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::NetDevice>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::NetDevice> arg0) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'arg0')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Const_ns3Address___amp___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, const ns3::Address &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0, ns3::Address const & arg1) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Socket >', 'arg0'), param('ns3::Address const &', 'arg1')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Socket >', 'arg0')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3CallbackImpl__Void_Ns3Ptr__lt__ns3Socket__gt___Unsigned_int_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::CallbackImpl(ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> const & arg0) [constructor] cls.add_constructor([param('ns3::CallbackImpl< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty > const &', 'arg0')]) ## callback.h (module 'core'): static std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::DoGetTypeid() [member function] cls.add_method('DoGetTypeid', 'std::string', [], is_static=True) ## callback.h (module 'core'): std::string ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackImpl<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>::operator()(ns3::Ptr<ns3::Socket> arg0, unsigned int arg1) [member operator] cls.add_method('operator()', 'void', [param('ns3::Ptr< ns3::Socket >', 'arg0'), param('unsigned int', 'arg1')], is_pure_virtual=True, is_virtual=True, custom_name=u'__call__') return def register_Ns3Ipv4ListRouting_methods(root_module, cls): ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting(ns3::Ipv4ListRouting const & arg0) [constructor] cls.add_constructor([param('ns3::Ipv4ListRouting const &', 'arg0')]) ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting() [constructor] cls.add_constructor([]) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::AddRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol, int16_t priority) [member function] cls.add_method('AddRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol'), param('int16_t', 'priority')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): uint32_t ns3::Ipv4ListRouting::GetNRoutingProtocols() const [member function] cls.add_method('GetNRoutingProtocols', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4ListRouting::GetRoutingProtocol(uint32_t index, int16_t & priority) const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('uint32_t', 'index'), param('int16_t &', 'priority', direction=2)], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): static ns3::TypeId ns3::Ipv4ListRouting::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): bool ns3::Ipv4ListRouting::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Ipv4RoutingProtocol::UnicastForwardCallback ucb, ns3::Ipv4RoutingProtocol::MulticastForwardCallback mcb, ns3::Ipv4RoutingProtocol::LocalDeliverCallback lcb, ns3::Ipv4RoutingProtocol::ErrorCallback ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4ListRouting::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', 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) [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, std::size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('std::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, std::size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('std::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) [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) [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, std::size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('std::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) [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, std::size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('std::size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, std::size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('std::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) [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, std::size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('std::size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, std::size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('std::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_Ns3AodvDuplicatePacketDetection_methods(root_module, cls): ## aodv-dpd.h (module 'aodv'): ns3::aodv::DuplicatePacketDetection::DuplicatePacketDetection(ns3::aodv::DuplicatePacketDetection const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::DuplicatePacketDetection const &', 'arg0')]) ## aodv-dpd.h (module 'aodv'): ns3::aodv::DuplicatePacketDetection::DuplicatePacketDetection(ns3::Time lifetime) [constructor] cls.add_constructor([param('ns3::Time', 'lifetime')]) ## aodv-dpd.h (module 'aodv'): ns3::Time ns3::aodv::DuplicatePacketDetection::GetLifetime() const [member function] cls.add_method('GetLifetime', 'ns3::Time', [], is_const=True) ## aodv-dpd.h (module 'aodv'): bool ns3::aodv::DuplicatePacketDetection::IsDuplicate(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header) [member function] cls.add_method('IsDuplicate', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header')]) ## aodv-dpd.h (module 'aodv'): void ns3::aodv::DuplicatePacketDetection::SetLifetime(ns3::Time lifetime) [member function] cls.add_method('SetLifetime', 'void', [param('ns3::Time', 'lifetime')]) return def register_Ns3AodvIdCache_methods(root_module, cls): ## aodv-id-cache.h (module 'aodv'): ns3::aodv::IdCache::IdCache(ns3::aodv::IdCache const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::IdCache const &', 'arg0')]) ## aodv-id-cache.h (module 'aodv'): ns3::aodv::IdCache::IdCache(ns3::Time lifetime) [constructor] cls.add_constructor([param('ns3::Time', 'lifetime')]) ## aodv-id-cache.h (module 'aodv'): ns3::Time ns3::aodv::IdCache::GetLifeTime() const [member function] cls.add_method('GetLifeTime', 'ns3::Time', [], is_const=True) ## aodv-id-cache.h (module 'aodv'): uint32_t ns3::aodv::IdCache::GetSize() [member function] cls.add_method('GetSize', 'uint32_t', []) ## aodv-id-cache.h (module 'aodv'): bool ns3::aodv::IdCache::IsDuplicate(ns3::Ipv4Address addr, uint32_t id) [member function] cls.add_method('IsDuplicate', 'bool', [param('ns3::Ipv4Address', 'addr'), param('uint32_t', 'id')]) ## aodv-id-cache.h (module 'aodv'): void ns3::aodv::IdCache::Purge() [member function] cls.add_method('Purge', 'void', []) ## aodv-id-cache.h (module 'aodv'): void ns3::aodv::IdCache::SetLifetime(ns3::Time lifetime) [member function] cls.add_method('SetLifetime', 'void', [param('ns3::Time', 'lifetime')]) return def register_Ns3AodvNeighbors_methods(root_module, cls): ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbors(ns3::aodv::Neighbors const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::Neighbors const &', 'arg0')]) ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbors(ns3::Time delay) [constructor] cls.add_constructor([param('ns3::Time', 'delay')]) ## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::AddArpCache(ns3::Ptr<ns3::ArpCache> a) [member function] cls.add_method('AddArpCache', 'void', [param('ns3::Ptr< ns3::ArpCache >', 'a')]) ## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::Clear() [member function] cls.add_method('Clear', 'void', []) ## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::DelArpCache(ns3::Ptr<ns3::ArpCache> a) [member function] cls.add_method('DelArpCache', 'void', [param('ns3::Ptr< ns3::ArpCache >', 'a')]) ## aodv-neighbor.h (module 'aodv'): ns3::Callback<void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::aodv::Neighbors::GetCallback() const [member function] cls.add_method('GetCallback', 'ns3::Callback< void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## aodv-neighbor.h (module 'aodv'): ns3::Time ns3::aodv::Neighbors::GetExpireTime(ns3::Ipv4Address addr) [member function] cls.add_method('GetExpireTime', 'ns3::Time', [param('ns3::Ipv4Address', 'addr')]) ## aodv-neighbor.h (module 'aodv'): ns3::Callback<void, const ns3::WifiMacHeader &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::aodv::Neighbors::GetTxErrorCallback() const [member function] cls.add_method('GetTxErrorCallback', 'ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## aodv-neighbor.h (module 'aodv'): bool ns3::aodv::Neighbors::IsNeighbor(ns3::Ipv4Address addr) [member function] cls.add_method('IsNeighbor', 'bool', [param('ns3::Ipv4Address', 'addr')]) ## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::Purge() [member function] cls.add_method('Purge', 'void', []) ## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::ScheduleTimer() [member function] cls.add_method('ScheduleTimer', 'void', []) ## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::SetCallback(ns3::Callback<void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetCallback', 'void', [param('ns3::Callback< void, ns3::Ipv4Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')]) ## aodv-neighbor.h (module 'aodv'): void ns3::aodv::Neighbors::Update(ns3::Ipv4Address addr, ns3::Time expire) [member function] cls.add_method('Update', 'void', [param('ns3::Ipv4Address', 'addr'), param('ns3::Time', 'expire')]) return def register_Ns3AodvNeighborsNeighbor_methods(root_module, cls): ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor::Neighbor(ns3::aodv::Neighbors::Neighbor const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::Neighbors::Neighbor const &', 'arg0')]) ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor::Neighbor(ns3::Ipv4Address ip, ns3::Mac48Address mac, ns3::Time t) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ip'), param('ns3::Mac48Address', 'mac'), param('ns3::Time', 't')]) ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor::close [variable] cls.add_instance_attribute('close', 'bool', is_const=False) ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor::m_expireTime [variable] cls.add_instance_attribute('m_expireTime', 'ns3::Time', is_const=False) ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor::m_hardwareAddress [variable] cls.add_instance_attribute('m_hardwareAddress', 'ns3::Mac48Address', is_const=False) ## aodv-neighbor.h (module 'aodv'): ns3::aodv::Neighbors::Neighbor::m_neighborAddress [variable] cls.add_instance_attribute('m_neighborAddress', 'ns3::Ipv4Address', is_const=False) return def register_Ns3AodvQueueEntry_methods(root_module, cls): cls.add_binary_comparison_operator('==') ## aodv-rqueue.h (module 'aodv'): ns3::aodv::QueueEntry::QueueEntry(ns3::aodv::QueueEntry const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::QueueEntry const &', 'arg0')]) ## aodv-rqueue.h (module 'aodv'): ns3::aodv::QueueEntry::QueueEntry(ns3::Ptr<const ns3::Packet> pa=0, ns3::Ipv4Header const & h=ns3::Ipv4Header(), ns3::aodv::QueueEntry::UnicastForwardCallback ucb=::ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>( ), ns3::aodv::QueueEntry::ErrorCallback ecb=::ns3::Callback<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>( ), ns3::Time exp=ns3::Simulator::Now()) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet const >', 'pa', default_value='0'), param('ns3::Ipv4Header const &', 'h', default_value='ns3::Ipv4Header()'), param('ns3::aodv::QueueEntry::UnicastForwardCallback', 'ucb', default_value='::ns3::Callback<void, ns3::Ptr<ns3::Ipv4Route>, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>( )'), param('ns3::aodv::QueueEntry::ErrorCallback', 'ecb', default_value='::ns3::Callback<void, ns3::Ptr<const ns3::Packet>, const ns3::Ipv4Header &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty>( )'), param('ns3::Time', 'exp', default_value='ns3::Simulator::Now()')]) ## aodv-rqueue.h (module 'aodv'): ns3::aodv::QueueEntry::ErrorCallback ns3::aodv::QueueEntry::GetErrorCallback() const [member function] cls.add_method('GetErrorCallback', 'ns3::aodv::QueueEntry::ErrorCallback', [], is_const=True) ## aodv-rqueue.h (module 'aodv'): ns3::Time ns3::aodv::QueueEntry::GetExpireTime() const [member function] cls.add_method('GetExpireTime', 'ns3::Time', [], is_const=True) ## aodv-rqueue.h (module 'aodv'): ns3::Ipv4Header ns3::aodv::QueueEntry::GetIpv4Header() const [member function] cls.add_method('GetIpv4Header', 'ns3::Ipv4Header', [], is_const=True) ## aodv-rqueue.h (module 'aodv'): ns3::Ptr<const ns3::Packet> ns3::aodv::QueueEntry::GetPacket() const [member function] cls.add_method('GetPacket', 'ns3::Ptr< ns3::Packet const >', [], is_const=True) ## aodv-rqueue.h (module 'aodv'): ns3::aodv::QueueEntry::UnicastForwardCallback ns3::aodv::QueueEntry::GetUnicastForwardCallback() const [member function] cls.add_method('GetUnicastForwardCallback', 'ns3::aodv::QueueEntry::UnicastForwardCallback', [], is_const=True) ## aodv-rqueue.h (module 'aodv'): void ns3::aodv::QueueEntry::SetErrorCallback(ns3::aodv::QueueEntry::ErrorCallback ecb) [member function] cls.add_method('SetErrorCallback', 'void', [param('ns3::Ipv4RoutingProtocol::ErrorCallback', 'ecb')]) ## aodv-rqueue.h (module 'aodv'): void ns3::aodv::QueueEntry::SetExpireTime(ns3::Time exp) [member function] cls.add_method('SetExpireTime', 'void', [param('ns3::Time', 'exp')]) ## aodv-rqueue.h (module 'aodv'): void ns3::aodv::QueueEntry::SetIpv4Header(ns3::Ipv4Header h) [member function] cls.add_method('SetIpv4Header', 'void', [param('ns3::Ipv4Header', 'h')]) ## aodv-rqueue.h (module 'aodv'): void ns3::aodv::QueueEntry::SetPacket(ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('SetPacket', 'void', [param('ns3::Ptr< ns3::Packet const >', 'p')]) ## aodv-rqueue.h (module 'aodv'): void ns3::aodv::QueueEntry::SetUnicastForwardCallback(ns3::aodv::QueueEntry::UnicastForwardCallback ucb) [member function] cls.add_method('SetUnicastForwardCallback', 'void', [param('ns3::Ipv4RoutingProtocol::UnicastForwardCallback', 'ucb')]) return def register_Ns3AodvRequestQueue_methods(root_module, cls): ## aodv-rqueue.h (module 'aodv'): ns3::aodv::RequestQueue::RequestQueue(ns3::aodv::RequestQueue const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::RequestQueue const &', 'arg0')]) ## aodv-rqueue.h (module 'aodv'): ns3::aodv::RequestQueue::RequestQueue(uint32_t maxLen, ns3::Time routeToQueueTimeout) [constructor] cls.add_constructor([param('uint32_t', 'maxLen'), param('ns3::Time', 'routeToQueueTimeout')]) ## aodv-rqueue.h (module 'aodv'): bool ns3::aodv::RequestQueue::Dequeue(ns3::Ipv4Address dst, ns3::aodv::QueueEntry & entry) [member function] cls.add_method('Dequeue', 'bool', [param('ns3::Ipv4Address', 'dst'), param('ns3::aodv::QueueEntry &', 'entry')]) ## aodv-rqueue.h (module 'aodv'): void ns3::aodv::RequestQueue::DropPacketWithDst(ns3::Ipv4Address dst) [member function] cls.add_method('DropPacketWithDst', 'void', [param('ns3::Ipv4Address', 'dst')]) ## aodv-rqueue.h (module 'aodv'): bool ns3::aodv::RequestQueue::Enqueue(ns3::aodv::QueueEntry & entry) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::aodv::QueueEntry &', 'entry')]) ## aodv-rqueue.h (module 'aodv'): bool ns3::aodv::RequestQueue::Find(ns3::Ipv4Address dst) [member function] cls.add_method('Find', 'bool', [param('ns3::Ipv4Address', 'dst')]) ## aodv-rqueue.h (module 'aodv'): uint32_t ns3::aodv::RequestQueue::GetMaxQueueLen() const [member function] cls.add_method('GetMaxQueueLen', 'uint32_t', [], is_const=True) ## aodv-rqueue.h (module 'aodv'): ns3::Time ns3::aodv::RequestQueue::GetQueueTimeout() const [member function] cls.add_method('GetQueueTimeout', 'ns3::Time', [], is_const=True) ## aodv-rqueue.h (module 'aodv'): uint32_t ns3::aodv::RequestQueue::GetSize() [member function] cls.add_method('GetSize', 'uint32_t', []) ## aodv-rqueue.h (module 'aodv'): void ns3::aodv::RequestQueue::SetMaxQueueLen(uint32_t len) [member function] cls.add_method('SetMaxQueueLen', 'void', [param('uint32_t', 'len')]) ## aodv-rqueue.h (module 'aodv'): void ns3::aodv::RequestQueue::SetQueueTimeout(ns3::Time t) [member function] cls.add_method('SetQueueTimeout', 'void', [param('ns3::Time', 't')]) return def register_Ns3AodvRerrHeader_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## aodv-packet.h (module 'aodv'): ns3::aodv::RerrHeader::RerrHeader(ns3::aodv::RerrHeader const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::RerrHeader const &', 'arg0')]) ## aodv-packet.h (module 'aodv'): ns3::aodv::RerrHeader::RerrHeader() [constructor] cls.add_constructor([]) ## aodv-packet.h (module 'aodv'): bool ns3::aodv::RerrHeader::AddUnDestination(ns3::Ipv4Address dst, uint32_t seqNo) [member function] cls.add_method('AddUnDestination', 'bool', [param('ns3::Ipv4Address', 'dst'), param('uint32_t', 'seqNo')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RerrHeader::Clear() [member function] cls.add_method('Clear', 'void', []) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RerrHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## aodv-packet.h (module 'aodv'): uint8_t ns3::aodv::RerrHeader::GetDestCount() const [member function] cls.add_method('GetDestCount', 'uint8_t', [], is_const=True) ## aodv-packet.h (module 'aodv'): ns3::TypeId ns3::aodv::RerrHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): bool ns3::aodv::RerrHeader::GetNoDelete() const [member function] cls.add_method('GetNoDelete', 'bool', [], is_const=True) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RerrHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): static ns3::TypeId ns3::aodv::RerrHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RerrHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): bool ns3::aodv::RerrHeader::RemoveUnDestination(std::pair<ns3::Ipv4Address, unsigned int> & un) [member function] cls.add_method('RemoveUnDestination', 'bool', [param('std::pair< ns3::Ipv4Address, unsigned int > &', 'un')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RerrHeader::Serialize(ns3::Buffer::Iterator i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'i')], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RerrHeader::SetNoDelete(bool f) [member function] cls.add_method('SetNoDelete', 'void', [param('bool', 'f')]) return def register_Ns3AodvRoutingProtocol_methods(root_module, cls): ## aodv-routing-protocol.h (module 'aodv'): ns3::aodv::RoutingProtocol::RoutingProtocol(ns3::aodv::RoutingProtocol const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::RoutingProtocol const &', 'arg0')]) ## aodv-routing-protocol.h (module 'aodv'): ns3::aodv::RoutingProtocol::RoutingProtocol() [constructor] cls.add_constructor([]) ## aodv-routing-protocol.h (module 'aodv'): int64_t ns3::aodv::RoutingProtocol::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## aodv-routing-protocol.h (module 'aodv'): bool ns3::aodv::RoutingProtocol::GetBroadcastEnable() const [member function] cls.add_method('GetBroadcastEnable', 'bool', [], is_const=True) ## aodv-routing-protocol.h (module 'aodv'): bool ns3::aodv::RoutingProtocol::GetDestinationOnlyFlag() const [member function] cls.add_method('GetDestinationOnlyFlag', 'bool', [], is_const=True) ## aodv-routing-protocol.h (module 'aodv'): bool ns3::aodv::RoutingProtocol::GetGratuitousReplyFlag() const [member function] cls.add_method('GetGratuitousReplyFlag', 'bool', [], is_const=True) ## aodv-routing-protocol.h (module 'aodv'): bool ns3::aodv::RoutingProtocol::GetHelloEnable() const [member function] cls.add_method('GetHelloEnable', 'bool', [], is_const=True) ## aodv-routing-protocol.h (module 'aodv'): uint32_t ns3::aodv::RoutingProtocol::GetMaxQueueLen() const [member function] cls.add_method('GetMaxQueueLen', 'uint32_t', [], is_const=True) ## aodv-routing-protocol.h (module 'aodv'): ns3::Time ns3::aodv::RoutingProtocol::GetMaxQueueTime() const [member function] cls.add_method('GetMaxQueueTime', 'ns3::Time', [], is_const=True) ## aodv-routing-protocol.h (module 'aodv'): static ns3::TypeId ns3::aodv::RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Time::Unit unit=::ns3::Time::Unit::S) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Time::Unit', 'unit', default_value='::ns3::Time::Unit::S')], is_const=True, is_virtual=True) ## aodv-routing-protocol.h (module 'aodv'): bool ns3::aodv::RoutingProtocol::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Ipv4RoutingProtocol::UnicastForwardCallback ucb, ns3::Ipv4RoutingProtocol::MulticastForwardCallback mcb, ns3::Ipv4RoutingProtocol::LocalDeliverCallback lcb, ns3::Ipv4RoutingProtocol::ErrorCallback ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_virtual=True) ## aodv-routing-protocol.h (module 'aodv'): ns3::Ptr<ns3::Ipv4Route> ns3::aodv::RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_virtual=True) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetBroadcastEnable(bool f) [member function] cls.add_method('SetBroadcastEnable', 'void', [param('bool', 'f')]) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetDestinationOnlyFlag(bool f) [member function] cls.add_method('SetDestinationOnlyFlag', 'void', [param('bool', 'f')]) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetGratuitousReplyFlag(bool f) [member function] cls.add_method('SetGratuitousReplyFlag', 'void', [param('bool', 'f')]) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetHelloEnable(bool f) [member function] cls.add_method('SetHelloEnable', 'void', [param('bool', 'f')]) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_virtual=True) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetMaxQueueLen(uint32_t len) [member function] cls.add_method('SetMaxQueueLen', 'void', [param('uint32_t', 'len')]) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::SetMaxQueueTime(ns3::Time t) [member function] cls.add_method('SetMaxQueueTime', 'void', [param('ns3::Time', 't')]) ## aodv-routing-protocol.h (module 'aodv'): ns3::aodv::RoutingProtocol::AODV_PORT [variable] cls.add_static_attribute('AODV_PORT', 'uint32_t const', is_const=True) ## aodv-routing-protocol.h (module 'aodv'): void ns3::aodv::RoutingProtocol::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3AodvRoutingTable_methods(root_module, cls): ## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTable::RoutingTable(ns3::aodv::RoutingTable const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::RoutingTable const &', 'arg0')]) ## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTable::RoutingTable(ns3::Time t) [constructor] cls.add_constructor([param('ns3::Time', 't')]) ## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::AddRoute(ns3::aodv::RoutingTableEntry & r) [member function] cls.add_method('AddRoute', 'bool', [param('ns3::aodv::RoutingTableEntry &', 'r')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::Clear() [member function] cls.add_method('Clear', 'void', []) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::DeleteAllRoutesFromInterface(ns3::Ipv4InterfaceAddress iface) [member function] cls.add_method('DeleteAllRoutesFromInterface', 'void', [param('ns3::Ipv4InterfaceAddress', 'iface')]) ## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::DeleteRoute(ns3::Ipv4Address dst) [member function] cls.add_method('DeleteRoute', 'bool', [param('ns3::Ipv4Address', 'dst')]) ## aodv-rtable.h (module 'aodv'): ns3::Time ns3::aodv::RoutingTable::GetBadLinkLifetime() const [member function] cls.add_method('GetBadLinkLifetime', 'ns3::Time', [], is_const=True) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::GetListOfDestinationWithNextHop(ns3::Ipv4Address nextHop, std::map<ns3::Ipv4Address, unsigned int, std::less<ns3::Ipv4Address>, std::allocator<std::pair<const ns3::Ipv4Address, unsigned int> > > & unreachable) [member function] cls.add_method('GetListOfDestinationWithNextHop', 'void', [param('ns3::Ipv4Address', 'nextHop'), param('std::map< ns3::Ipv4Address, unsigned int > &', 'unreachable')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::InvalidateRoutesWithDst(std::map<ns3::Ipv4Address, unsigned int, std::less<ns3::Ipv4Address>, std::allocator<std::pair<const ns3::Ipv4Address, unsigned int> > > const & unreachable) [member function] cls.add_method('InvalidateRoutesWithDst', 'void', [param('std::map< ns3::Ipv4Address, unsigned int > const &', 'unreachable')]) ## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::LookupRoute(ns3::Ipv4Address dst, ns3::aodv::RoutingTableEntry & rt) [member function] cls.add_method('LookupRoute', 'bool', [param('ns3::Ipv4Address', 'dst'), param('ns3::aodv::RoutingTableEntry &', 'rt')]) ## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::LookupValidRoute(ns3::Ipv4Address dst, ns3::aodv::RoutingTableEntry & rt) [member function] cls.add_method('LookupValidRoute', 'bool', [param('ns3::Ipv4Address', 'dst'), param('ns3::aodv::RoutingTableEntry &', 'rt')]) ## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::MarkLinkAsUnidirectional(ns3::Ipv4Address neighbor, ns3::Time blacklistTimeout) [member function] cls.add_method('MarkLinkAsUnidirectional', 'bool', [param('ns3::Ipv4Address', 'neighbor'), param('ns3::Time', 'blacklistTimeout')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::Print(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('Print', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::Purge() [member function] cls.add_method('Purge', 'void', []) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTable::SetBadLinkLifetime(ns3::Time t) [member function] cls.add_method('SetBadLinkLifetime', 'void', [param('ns3::Time', 't')]) ## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::SetEntryState(ns3::Ipv4Address dst, ns3::aodv::RouteFlags state) [member function] cls.add_method('SetEntryState', 'bool', [param('ns3::Ipv4Address', 'dst'), param('ns3::aodv::RouteFlags', 'state')]) ## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTable::Update(ns3::aodv::RoutingTableEntry & rt) [member function] cls.add_method('Update', 'bool', [param('ns3::aodv::RoutingTableEntry &', 'rt')]) return def register_Ns3AodvRoutingTableEntry_methods(root_module, cls): ## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTableEntry::RoutingTableEntry(ns3::aodv::RoutingTableEntry const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::RoutingTableEntry const &', 'arg0')]) ## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTableEntry::RoutingTableEntry(ns3::Ptr<ns3::NetDevice> dev=0, ns3::Ipv4Address dst=ns3::Ipv4Address(), bool vSeqNo=false, uint32_t seqNo=0, ns3::Ipv4InterfaceAddress iface=ns3::Ipv4InterfaceAddress(), uint16_t hops=0, ns3::Ipv4Address nextHop=ns3::Ipv4Address(), ns3::Time lifetime=ns3::Simulator::Now()) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev', default_value='0'), param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('bool', 'vSeqNo', default_value='false'), param('uint32_t', 'seqNo', default_value='0'), param('ns3::Ipv4InterfaceAddress', 'iface', default_value='ns3::Ipv4InterfaceAddress()'), param('uint16_t', 'hops', default_value='0'), param('ns3::Ipv4Address', 'nextHop', default_value='ns3::Ipv4Address()'), param('ns3::Time', 'lifetime', default_value='ns3::Simulator::Now()')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::DeleteAllPrecursors() [member function] cls.add_method('DeleteAllPrecursors', 'void', []) ## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTableEntry::DeletePrecursor(ns3::Ipv4Address id) [member function] cls.add_method('DeletePrecursor', 'bool', [param('ns3::Ipv4Address', 'id')]) ## aodv-rtable.h (module 'aodv'): ns3::Time ns3::aodv::RoutingTableEntry::GetBlacklistTimeout() const [member function] cls.add_method('GetBlacklistTimeout', 'ns3::Time', [], is_const=True) ## aodv-rtable.h (module 'aodv'): ns3::Ipv4Address ns3::aodv::RoutingTableEntry::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## aodv-rtable.h (module 'aodv'): ns3::aodv::RouteFlags ns3::aodv::RoutingTableEntry::GetFlag() const [member function] cls.add_method('GetFlag', 'ns3::aodv::RouteFlags', [], is_const=True) ## aodv-rtable.h (module 'aodv'): uint16_t ns3::aodv::RoutingTableEntry::GetHop() const [member function] cls.add_method('GetHop', 'uint16_t', [], is_const=True) ## aodv-rtable.h (module 'aodv'): ns3::Ipv4InterfaceAddress ns3::aodv::RoutingTableEntry::GetInterface() const [member function] cls.add_method('GetInterface', 'ns3::Ipv4InterfaceAddress', [], is_const=True) ## aodv-rtable.h (module 'aodv'): ns3::Time ns3::aodv::RoutingTableEntry::GetLifeTime() const [member function] cls.add_method('GetLifeTime', 'ns3::Time', [], is_const=True) ## aodv-rtable.h (module 'aodv'): ns3::Ipv4Address ns3::aodv::RoutingTableEntry::GetNextHop() const [member function] cls.add_method('GetNextHop', 'ns3::Ipv4Address', [], is_const=True) ## aodv-rtable.h (module 'aodv'): ns3::Ptr<ns3::NetDevice> ns3::aodv::RoutingTableEntry::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::GetPrecursors(std::vector<ns3::Ipv4Address, std::allocator<ns3::Ipv4Address> > & prec) const [member function] cls.add_method('GetPrecursors', 'void', [param('std::vector< ns3::Ipv4Address > &', 'prec')], is_const=True) ## aodv-rtable.h (module 'aodv'): ns3::Ptr<ns3::Ipv4Route> ns3::aodv::RoutingTableEntry::GetRoute() const [member function] cls.add_method('GetRoute', 'ns3::Ptr< ns3::Ipv4Route >', [], is_const=True) ## aodv-rtable.h (module 'aodv'): uint8_t ns3::aodv::RoutingTableEntry::GetRreqCnt() const [member function] cls.add_method('GetRreqCnt', 'uint8_t', [], is_const=True) ## aodv-rtable.h (module 'aodv'): uint32_t ns3::aodv::RoutingTableEntry::GetSeqNo() const [member function] cls.add_method('GetSeqNo', 'uint32_t', [], is_const=True) ## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTableEntry::GetValidSeqNo() const [member function] cls.add_method('GetValidSeqNo', 'bool', [], is_const=True) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::IncrementRreqCnt() [member function] cls.add_method('IncrementRreqCnt', 'void', []) ## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTableEntry::InsertPrecursor(ns3::Ipv4Address id) [member function] cls.add_method('InsertPrecursor', 'bool', [param('ns3::Ipv4Address', 'id')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::Invalidate(ns3::Time badLinkLifetime) [member function] cls.add_method('Invalidate', 'void', [param('ns3::Time', 'badLinkLifetime')]) ## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTableEntry::IsPrecursorListEmpty() const [member function] cls.add_method('IsPrecursorListEmpty', 'bool', [], is_const=True) ## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTableEntry::IsUnidirectional() const [member function] cls.add_method('IsUnidirectional', 'bool', [], is_const=True) ## aodv-rtable.h (module 'aodv'): bool ns3::aodv::RoutingTableEntry::LookupPrecursor(ns3::Ipv4Address id) [member function] cls.add_method('LookupPrecursor', 'bool', [param('ns3::Ipv4Address', 'id')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::Print(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('Print', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetBlacklistTimeout(ns3::Time t) [member function] cls.add_method('SetBlacklistTimeout', 'void', [param('ns3::Time', 't')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetFlag(ns3::aodv::RouteFlags flag) [member function] cls.add_method('SetFlag', 'void', [param('ns3::aodv::RouteFlags', 'flag')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetHop(uint16_t hop) [member function] cls.add_method('SetHop', 'void', [param('uint16_t', 'hop')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetInterface(ns3::Ipv4InterfaceAddress iface) [member function] cls.add_method('SetInterface', 'void', [param('ns3::Ipv4InterfaceAddress', 'iface')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetLifeTime(ns3::Time lt) [member function] cls.add_method('SetLifeTime', 'void', [param('ns3::Time', 'lt')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetNextHop(ns3::Ipv4Address nextHop) [member function] cls.add_method('SetNextHop', 'void', [param('ns3::Ipv4Address', 'nextHop')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetOutputDevice(ns3::Ptr<ns3::NetDevice> dev) [member function] cls.add_method('SetOutputDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetRoute(ns3::Ptr<ns3::Ipv4Route> r) [member function] cls.add_method('SetRoute', 'void', [param('ns3::Ptr< ns3::Ipv4Route >', 'r')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetRreqCnt(uint8_t n) [member function] cls.add_method('SetRreqCnt', 'void', [param('uint8_t', 'n')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetSeqNo(uint32_t sn) [member function] cls.add_method('SetSeqNo', 'void', [param('uint32_t', 'sn')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetUnidirectional(bool u) [member function] cls.add_method('SetUnidirectional', 'void', [param('bool', 'u')]) ## aodv-rtable.h (module 'aodv'): void ns3::aodv::RoutingTableEntry::SetValidSeqNo(bool s) [member function] cls.add_method('SetValidSeqNo', 'void', [param('bool', 's')]) ## aodv-rtable.h (module 'aodv'): ns3::aodv::RoutingTableEntry::m_ackTimer [variable] cls.add_instance_attribute('m_ackTimer', 'ns3::Timer', is_const=False) return def register_Ns3AodvRrepAckHeader_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## aodv-packet.h (module 'aodv'): ns3::aodv::RrepAckHeader::RrepAckHeader(ns3::aodv::RrepAckHeader const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::RrepAckHeader const &', 'arg0')]) ## aodv-packet.h (module 'aodv'): ns3::aodv::RrepAckHeader::RrepAckHeader() [constructor] cls.add_constructor([]) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RrepAckHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## aodv-packet.h (module 'aodv'): ns3::TypeId ns3::aodv::RrepAckHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RrepAckHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): static ns3::TypeId ns3::aodv::RrepAckHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepAckHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepAckHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_Ns3AodvRrepHeader_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## aodv-packet.h (module 'aodv'): ns3::aodv::RrepHeader::RrepHeader(ns3::aodv::RrepHeader const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::RrepHeader const &', 'arg0')]) ## aodv-packet.h (module 'aodv'): ns3::aodv::RrepHeader::RrepHeader(uint8_t prefixSize=0, uint8_t hopCount=0, ns3::Ipv4Address dst=ns3::Ipv4Address(), uint32_t dstSeqNo=0, ns3::Ipv4Address origin=ns3::Ipv4Address(), ns3::Time lifetime=ns3::MilliSeconds(0)) [constructor] cls.add_constructor([param('uint8_t', 'prefixSize', default_value='0'), param('uint8_t', 'hopCount', default_value='0'), param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('uint32_t', 'dstSeqNo', default_value='0'), param('ns3::Ipv4Address', 'origin', default_value='ns3::Ipv4Address()'), param('ns3::Time', 'lifetime', default_value='ns3::MilliSeconds(0)')]) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RrepHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## aodv-packet.h (module 'aodv'): bool ns3::aodv::RrepHeader::GetAckRequired() const [member function] cls.add_method('GetAckRequired', 'bool', [], is_const=True) ## aodv-packet.h (module 'aodv'): ns3::Ipv4Address ns3::aodv::RrepHeader::GetDst() const [member function] cls.add_method('GetDst', 'ns3::Ipv4Address', [], is_const=True) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RrepHeader::GetDstSeqno() const [member function] cls.add_method('GetDstSeqno', 'uint32_t', [], is_const=True) ## aodv-packet.h (module 'aodv'): uint8_t ns3::aodv::RrepHeader::GetHopCount() const [member function] cls.add_method('GetHopCount', 'uint8_t', [], is_const=True) ## aodv-packet.h (module 'aodv'): ns3::TypeId ns3::aodv::RrepHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): ns3::Time ns3::aodv::RrepHeader::GetLifeTime() const [member function] cls.add_method('GetLifeTime', 'ns3::Time', [], is_const=True) ## aodv-packet.h (module 'aodv'): ns3::Ipv4Address ns3::aodv::RrepHeader::GetOrigin() const [member function] cls.add_method('GetOrigin', 'ns3::Ipv4Address', [], is_const=True) ## aodv-packet.h (module 'aodv'): uint8_t ns3::aodv::RrepHeader::GetPrefixSize() const [member function] cls.add_method('GetPrefixSize', 'uint8_t', [], is_const=True) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RrepHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): static ns3::TypeId ns3::aodv::RrepHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetAckRequired(bool f) [member function] cls.add_method('SetAckRequired', 'void', [param('bool', 'f')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetDst(ns3::Ipv4Address a) [member function] cls.add_method('SetDst', 'void', [param('ns3::Ipv4Address', 'a')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetDstSeqno(uint32_t s) [member function] cls.add_method('SetDstSeqno', 'void', [param('uint32_t', 's')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetHello(ns3::Ipv4Address src, uint32_t srcSeqNo, ns3::Time lifetime) [member function] cls.add_method('SetHello', 'void', [param('ns3::Ipv4Address', 'src'), param('uint32_t', 'srcSeqNo'), param('ns3::Time', 'lifetime')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetHopCount(uint8_t count) [member function] cls.add_method('SetHopCount', 'void', [param('uint8_t', 'count')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetLifeTime(ns3::Time t) [member function] cls.add_method('SetLifeTime', 'void', [param('ns3::Time', 't')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetOrigin(ns3::Ipv4Address a) [member function] cls.add_method('SetOrigin', 'void', [param('ns3::Ipv4Address', 'a')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RrepHeader::SetPrefixSize(uint8_t sz) [member function] cls.add_method('SetPrefixSize', 'void', [param('uint8_t', 'sz')]) return def register_Ns3AodvRreqHeader_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## aodv-packet.h (module 'aodv'): ns3::aodv::RreqHeader::RreqHeader(ns3::aodv::RreqHeader const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::RreqHeader const &', 'arg0')]) ## aodv-packet.h (module 'aodv'): ns3::aodv::RreqHeader::RreqHeader(uint8_t flags=0, uint8_t reserved=0, uint8_t hopCount=0, uint32_t requestID=0, ns3::Ipv4Address dst=ns3::Ipv4Address(), uint32_t dstSeqNo=0, ns3::Ipv4Address origin=ns3::Ipv4Address(), uint32_t originSeqNo=0) [constructor] cls.add_constructor([param('uint8_t', 'flags', default_value='0'), param('uint8_t', 'reserved', default_value='0'), param('uint8_t', 'hopCount', default_value='0'), param('uint32_t', 'requestID', default_value='0'), param('ns3::Ipv4Address', 'dst', default_value='ns3::Ipv4Address()'), param('uint32_t', 'dstSeqNo', default_value='0'), param('ns3::Ipv4Address', 'origin', default_value='ns3::Ipv4Address()'), param('uint32_t', 'originSeqNo', default_value='0')]) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RreqHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## aodv-packet.h (module 'aodv'): bool ns3::aodv::RreqHeader::GetDestinationOnly() const [member function] cls.add_method('GetDestinationOnly', 'bool', [], is_const=True) ## aodv-packet.h (module 'aodv'): ns3::Ipv4Address ns3::aodv::RreqHeader::GetDst() const [member function] cls.add_method('GetDst', 'ns3::Ipv4Address', [], is_const=True) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RreqHeader::GetDstSeqno() const [member function] cls.add_method('GetDstSeqno', 'uint32_t', [], is_const=True) ## aodv-packet.h (module 'aodv'): bool ns3::aodv::RreqHeader::GetGratuitousRrep() const [member function] cls.add_method('GetGratuitousRrep', 'bool', [], is_const=True) ## aodv-packet.h (module 'aodv'): uint8_t ns3::aodv::RreqHeader::GetHopCount() const [member function] cls.add_method('GetHopCount', 'uint8_t', [], is_const=True) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RreqHeader::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## aodv-packet.h (module 'aodv'): ns3::TypeId ns3::aodv::RreqHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): ns3::Ipv4Address ns3::aodv::RreqHeader::GetOrigin() const [member function] cls.add_method('GetOrigin', 'ns3::Ipv4Address', [], is_const=True) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RreqHeader::GetOriginSeqno() const [member function] cls.add_method('GetOriginSeqno', 'uint32_t', [], is_const=True) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::RreqHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): static ns3::TypeId ns3::aodv::RreqHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## aodv-packet.h (module 'aodv'): bool ns3::aodv::RreqHeader::GetUnknownSeqno() const [member function] cls.add_method('GetUnknownSeqno', 'bool', [], is_const=True) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetDestinationOnly(bool f) [member function] cls.add_method('SetDestinationOnly', 'void', [param('bool', 'f')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetDst(ns3::Ipv4Address a) [member function] cls.add_method('SetDst', 'void', [param('ns3::Ipv4Address', 'a')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetDstSeqno(uint32_t s) [member function] cls.add_method('SetDstSeqno', 'void', [param('uint32_t', 's')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetGratuitousRrep(bool f) [member function] cls.add_method('SetGratuitousRrep', 'void', [param('bool', 'f')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetHopCount(uint8_t count) [member function] cls.add_method('SetHopCount', 'void', [param('uint8_t', 'count')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetId(uint32_t id) [member function] cls.add_method('SetId', 'void', [param('uint32_t', 'id')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetOrigin(ns3::Ipv4Address a) [member function] cls.add_method('SetOrigin', 'void', [param('ns3::Ipv4Address', 'a')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetOriginSeqno(uint32_t s) [member function] cls.add_method('SetOriginSeqno', 'void', [param('uint32_t', 's')]) ## aodv-packet.h (module 'aodv'): void ns3::aodv::RreqHeader::SetUnknownSeqno(bool f) [member function] cls.add_method('SetUnknownSeqno', 'void', [param('bool', 'f')]) return def register_Ns3AodvTypeHeader_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## aodv-packet.h (module 'aodv'): ns3::aodv::TypeHeader::TypeHeader(ns3::aodv::TypeHeader const & arg0) [constructor] cls.add_constructor([param('ns3::aodv::TypeHeader const &', 'arg0')]) ## aodv-packet.h (module 'aodv'): ns3::aodv::TypeHeader::TypeHeader(ns3::aodv::MessageType t=::ns3::aodv::MessageType::AODVTYPE_RREQ) [constructor] cls.add_constructor([param('ns3::aodv::MessageType', 't', default_value='::ns3::aodv::MessageType::AODVTYPE_RREQ')]) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::TypeHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## aodv-packet.h (module 'aodv'): ns3::aodv::MessageType ns3::aodv::TypeHeader::Get() const [member function] cls.add_method('Get', 'ns3::aodv::MessageType', [], is_const=True) ## aodv-packet.h (module 'aodv'): ns3::TypeId ns3::aodv::TypeHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): uint32_t ns3::aodv::TypeHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): static ns3::TypeId ns3::aodv::TypeHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## aodv-packet.h (module 'aodv'): bool ns3::aodv::TypeHeader::IsValid() const [member function] cls.add_method('IsValid', 'bool', [], is_const=True) ## aodv-packet.h (module 'aodv'): void ns3::aodv::TypeHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## aodv-packet.h (module 'aodv'): void ns3::aodv::TypeHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.add_cpp_namespace('FatalImpl'), root_module) register_functions_ns3_Hash(module.add_cpp_namespace('Hash'), root_module) register_functions_ns3_TracedValueCallback(module.add_cpp_namespace('TracedValueCallback'), root_module) register_functions_ns3_aodv(module.add_cpp_namespace('aodv'), 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.add_cpp_namespace('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def register_functions_ns3_TracedValueCallback(module, root_module): return def register_functions_ns3_aodv(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()
unknown
codeparrot/codeparrot-clean
import unittest from django.core.management.color import no_style from django.db import connection from django.test import SimpleTestCase from ..models import Person, Tag @unittest.skipUnless(connection.vendor == "mysql", "MySQL tests.") class MySQLOperationsTests(SimpleTestCase): def test_sql_flush(self): # allow_cascade doesn't change statements on MySQL. for allow_cascade in [False, True]: with self.subTest(allow_cascade=allow_cascade): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], allow_cascade=allow_cascade, ), [ "SET FOREIGN_KEY_CHECKS = 0;", "DELETE FROM `backends_person`;", "DELETE FROM `backends_tag`;", "SET FOREIGN_KEY_CHECKS = 1;", ], ) def test_sql_flush_sequences(self): # allow_cascade doesn't change statements on MySQL. for allow_cascade in [False, True]: with self.subTest(allow_cascade=allow_cascade): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], reset_sequences=True, allow_cascade=allow_cascade, ), [ "SET FOREIGN_KEY_CHECKS = 0;", "TRUNCATE `backends_person`;", "TRUNCATE `backends_tag`;", "SET FOREIGN_KEY_CHECKS = 1;", ], )
python
github
https://github.com/django/django
tests/backends/mysql/test_operations.py
from django.conf import settings from django.contrib.staticfiles.handlers import StaticFilesHandler from django.core.management.commands.runserver import \ Command as RunserverCommand class Command(RunserverCommand): help = "Starts a lightweight Web server for development and also serves static files." def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument('--nostatic', action="store_false", dest='use_static_handler', default=True, help='Tells Django to NOT automatically serve static files at STATIC_URL.') parser.add_argument('--insecure', action="store_true", dest='insecure_serving', default=False, help='Allows serving static files even if DEBUG is False.') def get_handler(self, *args, **options): """ Returns the static files serving handler wrapping the default handler, if static files should be served. Otherwise just returns the default handler. """ handler = super(Command, self).get_handler(*args, **options) use_static_handler = options.get('use_static_handler', True) insecure_serving = options.get('insecure_serving', False) if use_static_handler and (settings.DEBUG or insecure_serving): return StaticFilesHandler(handler) return handler
unknown
codeparrot/codeparrot-clean
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_UNARYSTATICASSERTCHECK_H #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_UNARYSTATICASSERTCHECK_H #include "../ClangTidyCheck.h" namespace clang::tidy::modernize { /// Replaces a static_assert declaration with an empty message /// with the unary version. /// /// For the user-facing documentation see: /// https://clang.llvm.org/extra/clang-tidy/checks/modernize/unary-static-assert.html class UnaryStaticAssertCheck : public ClangTidyCheck { public: UnaryStaticAssertCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context) {} bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { return LangOpts.CPlusPlus17; } void registerMatchers(ast_matchers::MatchFinder *Finder) override; void check(const ast_matchers::MatchFinder::MatchResult &Result) override; }; } // namespace clang::tidy::modernize #endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_UNARYSTATICASSERTCHECK_H
c
github
https://github.com/llvm/llvm-project
clang-tools-extra/clang-tidy/modernize/UnaryStaticAssertCheck.h
<?php namespace Illuminate\Tests\Queue; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Support\Facades\Queue; use Orchestra\Testbench\TestCase; class QueueSizeTest extends TestCase { public function test_queue_size() { Queue::fake(); $this->assertEquals(0, Queue::size()); $this->assertEquals(0, Queue::size('Q2')); $job = new TestJob1; dispatch($job); dispatch(new TestJob2); dispatch($job)->onQueue('Q2'); $this->assertEquals(2, Queue::size()); $this->assertEquals(1, Queue::size('Q2')); } } class TestJob1 implements ShouldQueue { use Queueable; } class TestJob2 implements ShouldQueue { use Queueable; }
php
github
https://github.com/laravel/framework
tests/Queue/QueueSizeTest.php
import pytest from scrapy import Request, Spider from scrapy.http import FormRequest, JsonRequest from scrapy.utils.request import request_from_dict class CustomRequest(Request): pass class TestRequestSerialization: def setup_method(self): self.spider = MethodsSpider() def test_basic(self): r = Request("http://www.example.com") self._assert_serializes_ok(r) def test_all_attributes(self): r = Request( url="http://www.example.com", callback=self.spider.parse_item, errback=self.spider.handle_error, method="POST", body=b"some body", headers={"content-encoding": "text/html; charset=latin-1"}, cookies={"currency": "руб"}, encoding="latin-1", priority=20, meta={"a": "b"}, cb_kwargs={"k": "v"}, flags=["testFlag"], ) self._assert_serializes_ok(r, spider=self.spider) def test_latin1_body(self): r = Request("http://www.example.com", body=b"\xa3") self._assert_serializes_ok(r) def test_utf8_body(self): r = Request("http://www.example.com", body=b"\xc2\xa3") self._assert_serializes_ok(r) def _assert_serializes_ok(self, request, spider=None): d = request.to_dict(spider=spider) request2 = request_from_dict(d, spider=spider) self._assert_same_request(request, request2) def _assert_same_request(self, r1, r2): assert r1.__class__ == r2.__class__ assert r1.url == r2.url assert r1.callback == r2.callback assert r1.errback == r2.errback assert r1.method == r2.method assert r1.body == r2.body assert r1.headers == r2.headers assert r1.cookies == r2.cookies assert r1.meta == r2.meta assert r1.cb_kwargs == r2.cb_kwargs assert r1.encoding == r2.encoding assert r1._encoding == r2._encoding assert r1.priority == r2.priority assert r1.dont_filter == r2.dont_filter assert r1.flags == r2.flags if isinstance(r1, JsonRequest): assert r1.dumps_kwargs == r2.dumps_kwargs def test_request_class(self): r1 = FormRequest("http://www.example.com") self._assert_serializes_ok(r1, spider=self.spider) r2 = CustomRequest("http://www.example.com") self._assert_serializes_ok(r2, spider=self.spider) r3 = JsonRequest("http://www.example.com", dumps_kwargs={"indent": 4}) self._assert_serializes_ok(r3, spider=self.spider) def test_callback_serialization(self): r = Request( "http://www.example.com", callback=self.spider.parse_item, errback=self.spider.handle_error, ) self._assert_serializes_ok(r, spider=self.spider) def test_reference_callback_serialization(self): r = Request( "http://www.example.com", callback=self.spider.parse_item_reference, errback=self.spider.handle_error_reference, ) self._assert_serializes_ok(r, spider=self.spider) request_dict = r.to_dict(spider=self.spider) assert request_dict["callback"] == "parse_item_reference" assert request_dict["errback"] == "handle_error_reference" def test_private_reference_callback_serialization(self): r = Request( "http://www.example.com", callback=self.spider._MethodsSpider__parse_item_reference, errback=self.spider._MethodsSpider__handle_error_reference, ) self._assert_serializes_ok(r, spider=self.spider) request_dict = r.to_dict(spider=self.spider) assert request_dict["callback"] == "_MethodsSpider__parse_item_reference" assert request_dict["errback"] == "_MethodsSpider__handle_error_reference" def test_private_callback_serialization(self): r = Request( "http://www.example.com", callback=self.spider._MethodsSpider__parse_item_private, errback=self.spider.handle_error, ) self._assert_serializes_ok(r, spider=self.spider) def test_mixin_private_callback_serialization(self): r = Request( "http://www.example.com", callback=self.spider._SpiderMixin__mixin_callback, errback=self.spider.handle_error, ) self._assert_serializes_ok(r, spider=self.spider) def test_delegated_callback_serialization(self): r = Request( "http://www.example.com", callback=self.spider.delegated_callback, errback=self.spider.handle_error, ) self._assert_serializes_ok(r, spider=self.spider) def test_unserializable_callback1(self): r = Request("http://www.example.com", callback=lambda x: x) with pytest.raises( ValueError, match="is not an instance method in: <MethodsSpider" ): r.to_dict(spider=self.spider) def test_unserializable_callback2(self): r = Request("http://www.example.com", callback=self.spider.parse_item) with pytest.raises(ValueError, match="is not an instance method in: None"): r.to_dict(spider=None) def test_unserializable_callback3(self): """Parser method is removed or replaced dynamically.""" class MySpider(Spider): name = "my_spider" def parse(self, response): pass spider = MySpider() r = Request("http://www.example.com", callback=spider.parse) spider.parse = None with pytest.raises(ValueError, match="is not an instance method in: <MySpider"): r.to_dict(spider=spider) def test_callback_not_available(self): """Callback method is not available in the spider passed to from_dict""" spider = SpiderDelegation() r = Request("http://www.example.com", callback=spider.delegated_callback) d = r.to_dict(spider=spider) with pytest.raises( ValueError, match="Method 'delegated_callback' not found in: <Spider" ): request_from_dict(d, spider=Spider("foo")) class SpiderMixin: def __mixin_callback(self, response): # pylint: disable=unused-private-member pass class SpiderDelegation: def delegated_callback(self, response): pass def parse_item(response): pass def handle_error(failure): pass def private_parse_item(response): pass def private_handle_error(failure): pass class MethodsSpider(Spider, SpiderMixin): name = "test" parse_item_reference = parse_item handle_error_reference = handle_error __parse_item_reference = private_parse_item __handle_error_reference = private_handle_error def __init__(self, **kwargs): super().__init__(**kwargs) self.delegated_callback = SpiderDelegation().delegated_callback def parse_item(self, response): pass def handle_error(self, failure): pass def __parse_item_private(self, response): # pylint: disable=unused-private-member pass
python
github
https://github.com/scrapy/scrapy
tests/test_request_dict.py
import Container from "./container"; import { EXAMPLE_PATH } from "../lib/constants"; export default function Footer() { return ( <footer className="bg-accent-1 border-t border-accent-2"> <Container> <div className="py-28 flex flex-col lg:flex-row items-center"> <h3 className="text-4xl lg:text-5xl font-bold tracking-tighter leading-tight text-center lg:text-left mb-10 lg:mb-0 lg:pr-4 lg:w-1/2"> Statically Generated with Next.js. </h3> <div className="flex flex-col lg:flex-row justify-center items-center lg:pl-4 lg:w-1/2"> <a href="https://nextjs.org/docs/basic-features/pages" className="mx-3 bg-black hover:bg-white hover:text-black border border-black text-white font-bold py-3 px-12 lg:px-8 duration-200 transition-colors mb-6 lg:mb-0" > Read Documentation </a> <a href={`https://github.com/vercel/next.js/tree/canary/examples/${EXAMPLE_PATH}`} className="mx-3 font-bold hover:underline" > View on GitHub </a> </div> </div> </Container> </footer> ); }
typescript
github
https://github.com/vercel/next.js
examples/cms-agilitycms/components/footer.tsx
/* * Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.api.fir.types import org.jetbrains.kotlin.analysis.api.KaExperimentalApi import org.jetbrains.kotlin.analysis.api.KaImplementationDetail import org.jetbrains.kotlin.analysis.api.KaSession import org.jetbrains.kotlin.analysis.api.annotations.KaAnnotationList import org.jetbrains.kotlin.analysis.api.base.KaContextReceiver import org.jetbrains.kotlin.analysis.api.fir.KaFirSession import org.jetbrains.kotlin.analysis.api.fir.KaSymbolByFirBuilder import org.jetbrains.kotlin.analysis.api.fir.annotations.KaFirAnnotationListForType import org.jetbrains.kotlin.analysis.api.fir.types.qualifiers.UsualClassTypeQualifierBuilder import org.jetbrains.kotlin.analysis.api.fir.utils.buildAbbreviatedType import org.jetbrains.kotlin.analysis.api.fir.utils.createPointer import org.jetbrains.kotlin.analysis.api.impl.base.KaBaseContextReceiver import org.jetbrains.kotlin.analysis.api.impl.base.resolution.KaBaseFunctionValueParameter import org.jetbrains.kotlin.analysis.api.lifetime.KaLifetimeToken import org.jetbrains.kotlin.analysis.api.lifetime.withValidityAssertion import org.jetbrains.kotlin.analysis.api.symbols.KaClassLikeSymbol import org.jetbrains.kotlin.analysis.api.types.* import org.jetbrains.kotlin.analysis.low.level.api.fir.util.errorWithFirSpecificEntries import org.jetbrains.kotlin.analysis.utils.errors.requireIsInstance import org.jetbrains.kotlin.fir.declarations.FirResolvePhase import org.jetbrains.kotlin.fir.resolve.transformers.ensureResolvedTypeDeclaration import org.jetbrains.kotlin.fir.types.* import org.jetbrains.kotlin.fir.types.impl.ConeClassLikeTypeImpl import org.jetbrains.kotlin.name.ClassId internal class KaFirFunctionType( override val coneType: ConeClassLikeTypeImpl, private val builder: KaSymbolByFirBuilder, ) : KaFunctionType(), KaFirType { override val token: KaLifetimeToken get() = builder.token override val classId: ClassId get() = withValidityAssertion { coneType.lookupTag.classId } override val symbol: KaClassLikeSymbol get() = withValidityAssertion { builder.classifierBuilder.buildClassLikeSymbolByLookupTag(coneType.lookupTag) ?: errorWithFirSpecificEntries("Class was not found", coneType = coneType) } override val typeArguments: List<KaTypeProjection> get() = withValidityAssertion { qualifiers.last().typeArguments } override val qualifiers: List<KaResolvedClassTypeQualifier> get() = withValidityAssertion { UsualClassTypeQualifierBuilder.buildQualifiers(coneType, builder) } override val annotations: KaAnnotationList get() = withValidityAssertion { KaFirAnnotationListForType.create(coneType, builder) } @Deprecated( "Use `isMarkedNullable`, `isNullable` or `hasFlexibleNullability` instead. See KDocs for the migration guide", replaceWith = ReplaceWith("this.isMarkedNullable") ) @Suppress("Deprecation") override val nullability: KaTypeNullability get() = withValidityAssertion { KaTypeNullability.create(coneType.isMarkedNullable) } override val abbreviation: KaUsualClassType? get() = withValidityAssertion { builder.buildAbbreviatedType(coneType) } override val isSuspend: Boolean get() = withValidityAssertion { coneType.isSuspendOrKSuspendFunctionType(builder.rootSession) } override val isReflectType: Boolean get() = withValidityAssertion { coneType.functionTypeKind(builder.rootSession)?.isReflectType == true } @Deprecated("Use `parameters.size` instead. See KT-80545", replaceWith = ReplaceWith("parameters.size")) override val arity: Int get() = withValidityAssertion { parameterTypes.size } @KaExperimentalApi override val contextReceivers: List<KaContextReceiver> get() = withValidityAssertion { coneType.contextParameterTypes(builder.rootSession) .map { // Context receivers in function types may not have labels, hence the `null` label. KaBaseContextReceiver(it.buildKtType(), label = null, token) } } override val hasContextReceivers: Boolean get() = withValidityAssertion { contextReceivers.isNotEmpty() } override val receiverType: KaType? get() = withValidityAssertion { coneType.receiverType(builder.rootSession)?.buildKtType() } override val hasReceiver: Boolean get() = withValidityAssertion { receiverType != null } override val parameterTypes: List<KaType> get() = withValidityAssertion { coneType.valueParameterTypesWithoutReceivers(builder.rootSession).map { it.buildKtType() } } override val parameters: List<KaFunctionValueParameter> get() = withValidityAssertion { parameterTypes.map { parameterType -> val parameterConeType = (parameterType as? KaFirType)?.coneType // Parameters have to be resolved to FirResolvePhase.ANNOTATION_ARGUMENTS // as parameter names can be explicitly provided via @ParameterName annotations. parameterConeType.ensureResolvedTypeDeclaration(builder.rootSession, FirResolvePhase.ANNOTATION_ARGUMENTS) val name = parameterConeType?.valueParameterName(builder.rootSession) KaBaseFunctionValueParameter(name, parameterType) } } override val returnType: KaType get() = withValidityAssertion { coneType.returnType(builder.rootSession).buildKtType() } override fun equals(other: Any?) = typeEquals(other) override fun hashCode() = typeHashcode() override fun toString() = coneType.renderForDebugging() private fun ConeKotlinType.buildKtType(): KaType = builder.typeBuilder.buildKtType(this) @KaExperimentalApi override fun createPointer(): KaTypePointer<KaFunctionType> = withValidityAssertion { return KaFirFunctionalClassTypePointer(coneType, builder) } } private class KaFirFunctionalClassTypePointer( coneType: ConeClassLikeTypeImpl, builder: KaSymbolByFirBuilder, ) : KaTypePointer<KaFunctionType> { private val coneTypePointer = coneType.createPointer(builder) @KaImplementationDetail override fun restore(session: KaSession): KaFunctionType? { requireIsInstance<KaFirSession>(session) val coneType = coneTypePointer.restore(session) ?: return null if (!coneType.isSomeFunctionType(session.resolutionFacade.useSiteFirSession)) { return null } return KaFirFunctionType(coneType, session.firSymbolBuilder) } }
kotlin
github
https://github.com/JetBrains/kotlin
analysis/analysis-api-fir/src/org/jetbrains/kotlin/analysis/api/fir/types/KaFirFunctionType.kt
# -*- coding: utf-8 -*- # # jams documentation build configuration file, created by # sphinx-quickstart on Mon Dec 8 10:34:40 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # -- General configuration ------------------------------------------------ import os import sys sys.path.insert(0, os.path.abspath('../')) # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = '1.2' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.doctest', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'numpydoc' ] import glob autosummary_generate = glob.glob('*.rst') numpydoc_show_class_members = False intersphinx_mapping = {'numpy': ('https://docs.scipy.org/doc/numpy/', None), 'np': ('https://docs.scipy.org/doc/numpy/', None), 'pandas': ('http://pandas.pydata.org/pandas-docs/stable/', None), 'pd': ('http://pandas.pydata.org/pandas-docs/stable/', None), 'mir_eval': ('https://craffel.github.io/mir_eval/', None), 'json': ('https://docs.python.org/2/', None), 'jsonschema': ('https://python-jsonschema.readthedocs.io/en/latest/', None)} # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] exclude_trees = ['_templates', '_build'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'jams' copyright = u'2015, JAMS development team' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. import imp jams_version = imp.load_source('jams.version', '../jams/version.py') version = jams_version.short_version # The full version, including alpha/beta/rc tags. release = jams_version.version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. default_role = 'autolink' # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = False # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # Mock from mock import Mock as MagicMock class Mock(MagicMock): @classmethod def __getattr__(cls, name): return Mock() MOCK_MODULES = (['jsonschema', 'mir_eval', 'pandas', 'numpy', 'mir_eval.sonify', 'mir_eval.util', 'mir_eval.display', 'decorator', 'matplotlib', 'matplotlib.pyplot', 'matplotlib.offsetbox', 'sortedcontainers']) sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. #html_theme = 'default' import sphinx_rtd_theme on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if on_rtd: html_theme = 'default' # MOCK_MODULES = ['numpy', 'pandas'] # sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) else: html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. html_domain_indices = True # If false, no index is generated. html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'jamsdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'jams.tex', u'jams Documentation', u'JAMS development team', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'jams', u'jams Documentation', [u'JAMS development team'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'jams', u'jams Documentation', u'JAMS development team', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
unknown
codeparrot/codeparrot-clean
/* 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. ==============================================================================*/ package org.tensorflow; /** * Base class for {@link Operation} implementations. * * <p>As opposed to {@link Operation} itself, this class is package private and therefore its usage * is limited to internal purposes only. */ abstract class AbstractOperation implements Operation { @Override public Output<?>[] outputList(int idx, int length) { Output<?>[] outputs = new Output<?>[length]; for (int i = 0; i < length; ++i) { outputs[i] = output(idx + i); } return outputs; } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public <T> Output<T> output(int idx) { return new Output(this, idx); } @Override public String toString() { return String.format("<%s '%s'>", type(), name()); } /** * Returns the native handle of the {@code outputIdx}th output of this operation. * * <p>The nature of the returned value varies depending on current the execution environment. * * <ul> * <li>In eager mode, the value is a handle to the tensor returned at this output. * <li>In graph mode, the value is a handle to the operation itself, which should be paired with * the index of the output when calling the native layer. * </ul> * * @param outputIdx index of the output in this operation * @return a native handle, see method description for more details */ abstract long getUnsafeNativeHandle(int outputIdx); /** * Returns the shape of the tensor of the {@code outputIdx}th output of this operation. * * @param outputIdx index of the output of this operation * @return output tensor shape */ abstract long[] shape(int outputIdx); /** * Returns the datatype of the tensor of the {@code outputIdx}th output of this operation. * * @param outputIdx index of the output of this operation * @return output tensor datatype */ abstract DataType dtype(int outputIdx); /** * Returns the tensor of the {@code outputIdx}th output of this operation. * * <p>This is only supported in an eager execution environment. * * @param outputIdx index of the output of this operation * @return output tensor */ abstract Tensor<?> tensor(int outputIdx); }
java
github
https://github.com/tensorflow/tensorflow
tensorflow/java/src/main/java/org/tensorflow/AbstractOperation.java
# -*- coding: utf-8 -*- """ *************************************************************************** SetVectorStyle.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' from qgis.core import (QgsProcessingAlgorithm, QgsProcessingParameterFile, QgsProcessingParameterVectorLayer, QgsProcessingOutputVectorLayer) from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm class SetVectorStyle(QgisAlgorithm): INPUT = 'INPUT' STYLE = 'STYLE' OUTPUT = 'OUTPUT' def group(self): return self.tr('Vector general') def groupId(self): return 'vectorgeneral' def __init__(self): super().__init__() def flags(self): return super().flags() | QgsProcessingAlgorithm.FlagNoThreading | QgsProcessingAlgorithm.FlagDeprecated | QgsProcessingAlgorithm.FlagNotAvailableInStandaloneTool def initAlgorithm(self, config=None): self.addParameter(QgsProcessingParameterVectorLayer(self.INPUT, self.tr('Vector layer'))) self.addParameter(QgsProcessingParameterFile(self.STYLE, self.tr('Style file'), extension='qml')) self.addOutput(QgsProcessingOutputVectorLayer(self.INPUT, self.tr('Styled'))) def name(self): return 'setstyleforvectorlayer' def displayName(self): return self.tr('Set style for vector layer') def processAlgorithm(self, parameters, context, feedback): layer = self.parameterAsVectorLayer(parameters, self.INPUT, context) style = self.parameterAsFile(parameters, self.STYLE, context) layer.loadNamedStyle(style) layer.triggerRepaint() return {self.INPUT: layer}
unknown
codeparrot/codeparrot-clean
/** * 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. */ package org.apache.hadoop.security.alias; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.util.Shell; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.util.EnumSet; import java.util.Set; import java.util.StringTokenizer; /** * CredentialProvider based on Java's KeyStore file format. The file may be * stored only on the local filesystem using the following name mangling: * localjceks://file/home/larry/creds.jceks {@literal ->} * file:///home/larry/creds.jceks */ @InterfaceAudience.Private public abstract class LocalKeyStoreProvider extends AbstractJavaKeyStoreProvider { private File file; private Set<PosixFilePermission> permissions; protected LocalKeyStoreProvider(URI uri, Configuration conf) throws IOException { super(uri, conf); } @Override protected OutputStream getOutputStreamForKeystore() throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("using '" + file + "' for output stream."); } OutputStream out = Files.newOutputStream(file.toPath()); return out; } @Override protected boolean keystoreExists() throws IOException { /* The keystore loader doesn't handle zero length files. */ return file.exists() && (file.length() > 0); } @Override protected InputStream getInputStreamForFile() throws IOException { InputStream is = Files.newInputStream(file.toPath()); return is; } @Override protected void createPermissions(String perms) throws IOException { int mode = 700; try { mode = Integer.parseInt(perms, 8); } catch (NumberFormatException nfe) { throw new IOException("Invalid permissions mode provided while " + "trying to createPermissions", nfe); } permissions = modeToPosixFilePermission(mode); } @Override protected void stashOriginalFilePermissions() throws IOException { // save off permissions in case we need to // rewrite the keystore in flush() if (!Shell.WINDOWS) { Path path = Paths.get(file.getCanonicalPath()); permissions = Files.getPosixFilePermissions(path); } else { // On Windows, the JDK does not support the POSIX file permission APIs. // Instead, we can do a winutils call and translate. String[] cmd = Shell.getGetPermissionCommand(); String[] args = new String[cmd.length + 1]; System.arraycopy(cmd, 0, args, 0, cmd.length); args[cmd.length] = file.getCanonicalPath(); String out = Shell.execCommand(args); StringTokenizer t = new StringTokenizer(out, Shell.TOKEN_SEPARATOR_REGEX); // The winutils output consists of 10 characters because of the leading // directory indicator, i.e. "drwx------". The JDK parsing method expects // a 9-character string, so remove the leading character. String permString = t.nextToken().substring(1); permissions = PosixFilePermissions.fromString(permString); } } @Override protected void initFileSystem(URI uri) throws IOException { super.initFileSystem(uri); try { file = new File(new URI(getPath().toString())); if (LOG.isDebugEnabled()) { LOG.debug("initialized local file as '" + file + "'."); if (file.exists()) { LOG.debug("the local file exists and is size " + file.length()); if (LOG.isTraceEnabled()) { if (file.canRead()) { LOG.trace("we can read the local file."); } if (file.canWrite()) { LOG.trace("we can write the local file."); } } } else { LOG.debug("the local file does not exist."); } } } catch (URISyntaxException e) { throw new IOException(e); } } @Override public void flush() throws IOException { super.flush(); if (LOG.isDebugEnabled()) { LOG.debug("Resetting permissions to '" + permissions + "'"); } if (!Shell.WINDOWS) { Files.setPosixFilePermissions(Paths.get(file.getCanonicalPath()), permissions); } else { // FsPermission expects a 10-character string because of the leading // directory indicator, i.e. "drwx------". The JDK toString method returns // a 9-character string, so prepend a leading character. FsPermission fsPermission = FsPermission.valueOf( "-" + PosixFilePermissions.toString(permissions)); FileUtil.setPermission(file, fsPermission); } } private static Set<PosixFilePermission> modeToPosixFilePermission( int mode) { Set<PosixFilePermission> perms = EnumSet.noneOf(PosixFilePermission.class); if ((mode & 0001) != 0) { perms.add(PosixFilePermission.OTHERS_EXECUTE); } if ((mode & 0002) != 0) { perms.add(PosixFilePermission.OTHERS_WRITE); } if ((mode & 0004) != 0) { perms.add(PosixFilePermission.OTHERS_READ); } if ((mode & 0010) != 0) { perms.add(PosixFilePermission.GROUP_EXECUTE); } if ((mode & 0020) != 0) { perms.add(PosixFilePermission.GROUP_WRITE); } if ((mode & 0040) != 0) { perms.add(PosixFilePermission.GROUP_READ); } if ((mode & 0100) != 0) { perms.add(PosixFilePermission.OWNER_EXECUTE); } if ((mode & 0200) != 0) { perms.add(PosixFilePermission.OWNER_WRITE); } if ((mode & 0400) != 0) { perms.add(PosixFilePermission.OWNER_READ); } return perms; } }
java
github
https://github.com/apache/hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/alias/LocalKeyStoreProvider.java
// Copyright 2015 The Cockroach Authors. // // Use of this software is governed by the CockroachDB Software License // included in the /LICENSE file. package gossip import ( "testing" "github.com/cockroachdb/cockroach/pkg/roachpb" "github.com/cockroachdb/cockroach/pkg/util/leaktest" "github.com/cockroachdb/cockroach/pkg/util/metric" ) func TestNodeSetMaxSize(t *testing.T) { defer leaktest.AfterTest(t)() nodes := makeNodeSet(1, metric.NewGauge(metric.Metadata{Name: ""})) if !nodes.hasSpace() { t.Error("set should have space") } nodes.addNode(roachpb.NodeID(1)) if nodes.hasSpace() { t.Error("set should have no space") } } func TestNodeSetHasNode(t *testing.T) { defer leaktest.AfterTest(t)() nodes := makeNodeSet(2, metric.NewGauge(metric.Metadata{Name: ""})) node := roachpb.NodeID(1) if nodes.hasNode(node) { t.Error("node wasn't added and should not be valid") } // Add node and verify it's valid. nodes.addNode(node) if !nodes.hasNode(node) { t.Error("empty node wasn't added and should not be valid") } } func TestNodeSetAddAndRemoveNode(t *testing.T) { defer leaktest.AfterTest(t)() nodes := makeNodeSet(2, metric.NewGauge(metric.Metadata{Name: ""})) node0 := roachpb.NodeID(1) node1 := roachpb.NodeID(2) nodes.addNode(node0) nodes.addNode(node1) if !nodes.hasNode(node0) || !nodes.hasNode(node1) { t.Error("failed to locate added nodes") } nodes.removeNode(node0) if nodes.hasNode(node0) || !nodes.hasNode(node1) { t.Error("failed to remove node0", nodes) } nodes.removeNode(node1) if nodes.hasNode(node0) || nodes.hasNode(node1) { t.Error("failed to remove node1", nodes) } } func TestNodeSetFilter(t *testing.T) { defer leaktest.AfterTest(t)() nodes1 := makeNodeSet(2, metric.NewGauge(metric.Metadata{Name: ""})) node0 := roachpb.NodeID(1) node1 := roachpb.NodeID(2) nodes1.addNode(node0) nodes1.addNode(node1) nodes2 := makeNodeSet(1, metric.NewGauge(metric.Metadata{Name: ""})) nodes2.addNode(node1) filtered := nodes1.filter(func(a roachpb.NodeID) bool { return !nodes2.hasNode(a) }) if filtered.len() != 1 || filtered.hasNode(node1) || !filtered.hasNode(node0) { t.Errorf("expected filter to leave node0: %+v", filtered) } } func TestNodeSetAsSlice(t *testing.T) { defer leaktest.AfterTest(t)() nodes := makeNodeSet(2, metric.NewGauge(metric.Metadata{Name: ""})) node0 := roachpb.NodeID(1) node1 := roachpb.NodeID(2) nodes.addNode(node0) nodes.addNode(node1) nodeArr := nodes.asSlice() if len(nodeArr) != 2 { t.Error("expected slice of length 2:", nodeArr) } if (nodeArr[0] != node0 && nodeArr[0] != node1) || (nodeArr[1] != node1 && nodeArr[1] != node0) { t.Error("expected slice to contain both node0 and node1:", nodeArr) } }
go
github
https://github.com/cockroachdb/cockroach
pkg/gossip/node_set_test.go
// Copyright 2025 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build unix package bufio_test import ( "bufio" "io" "net" "path/filepath" "strings" "sync" "testing" ) // TestCopyUnixpacket tests that we can use bufio when copying // across a unixpacket socket. This used to fail due to an unnecessary // empty Write call that was interpreted as an EOF. func TestCopyUnixpacket(t *testing.T) { tmpDir := t.TempDir() socket := filepath.Join(tmpDir, "unixsock") // Start a unixpacket server. addr := &net.UnixAddr{ Name: socket, Net: "unixpacket", } server, err := net.ListenUnix("unixpacket", addr) if err != nil { t.Skipf("skipping test because opening a unixpacket socket failed: %v", err) } // Start a goroutine for the server to accept one connection // and read all the data sent on the connection, // reporting the number of bytes read on ch. ch := make(chan int, 1) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() tot := 0 defer func() { ch <- tot }() serverConn, err := server.Accept() if err != nil { t.Error(err) return } buf := make([]byte, 1024) for { n, err := serverConn.Read(buf) tot += n if err == io.EOF { return } if err != nil { t.Error(err) return } } }() clientConn, err := net.DialUnix("unixpacket", nil, addr) if err != nil { // Leaves the server goroutine hanging. Oh well. t.Fatal(err) } defer wg.Wait() defer clientConn.Close() const data = "data" r := bufio.NewReader(strings.NewReader(data)) n, err := io.Copy(clientConn, r) if err != nil { t.Fatal(err) } if n != int64(len(data)) { t.Errorf("io.Copy returned %d, want %d", n, len(data)) } clientConn.Close() tot := <-ch if tot != len(data) { t.Errorf("server read %d, want %d", tot, len(data)) } }
go
github
https://github.com/golang/go
src/bufio/net_test.go
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016, Red Hat | Ansible # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # This is a windows documentation stub. Actual code lives in the .ps1 # file of the same name ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = r''' --- module: win_path version_added: "2.3" short_description: Manage Windows path environment variables description: - Allows element-based ordering, addition, and removal of Windows path environment variables. options: name: description: - Target path environment variable name. type: str default: PATH elements: description: - A single path element, or a list of path elements (ie, directories) to add or remove. - When multiple elements are included in the list (and C(state) is C(present)), the elements are guaranteed to appear in the same relative order in the resultant path value. - Variable expansions (eg, C(%VARNAME%)) are allowed, and are stored unexpanded in the target path element. - Any existing path elements not mentioned in C(elements) are always preserved in their current order. - New path elements are appended to the path, and existing path elements may be moved closer to the end to satisfy the requested ordering. - Paths are compared in a case-insensitive fashion, and trailing backslashes are ignored for comparison purposes. However, note that trailing backslashes in YAML require quotes. type: list required: yes state: description: - Whether the path elements specified in C(elements) should be present or absent. type: str choices: [ absent, present ] scope: description: - The level at which the environment variable specified by C(name) should be managed (either for the current user or global machine scope). type: str choices: [ machine, user ] default: machine notes: - This module is for modifying individual elements of path-like environment variables. For general-purpose management of other environment vars, use the M(win_environment) module. - This module does not broadcast change events. This means that the minority of windows applications which can have their environment changed without restarting will not be notified and therefore will need restarting to pick up new environment settings. - User level environment variables will require an interactive user to log out and in again before they become available. seealso: - module: win_environment author: - Matt Davis (@nitzmahone) ''' EXAMPLES = r''' - name: Ensure that system32 and Powershell are present on the global system path, and in the specified order win_path: elements: - '%SystemRoot%\system32' - '%SystemRoot%\system32\WindowsPowerShell\v1.0' - name: Ensure that C:\Program Files\MyJavaThing is not on the current user's CLASSPATH win_path: name: CLASSPATH elements: C:\Program Files\MyJavaThing scope: user state: absent '''
unknown
codeparrot/codeparrot-clean
//go:build !ignore_autogenerated // +build !ignore_autogenerated /* Copyright The Kubernetes Authors. 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. */ // Code generated by deepcopy-gen. DO NOT EDIT. package config // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CSRSigningConfiguration) DeepCopyInto(out *CSRSigningConfiguration) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CSRSigningConfiguration. func (in *CSRSigningConfiguration) DeepCopy() *CSRSigningConfiguration { if in == nil { return nil } out := new(CSRSigningConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CSRSigningControllerConfiguration) DeepCopyInto(out *CSRSigningControllerConfiguration) { *out = *in out.KubeletServingSignerConfiguration = in.KubeletServingSignerConfiguration out.KubeletClientSignerConfiguration = in.KubeletClientSignerConfiguration out.KubeAPIServerClientSignerConfiguration = in.KubeAPIServerClientSignerConfiguration out.LegacyUnknownSignerConfiguration = in.LegacyUnknownSignerConfiguration out.ClusterSigningDuration = in.ClusterSigningDuration return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CSRSigningControllerConfiguration. func (in *CSRSigningControllerConfiguration) DeepCopy() *CSRSigningControllerConfiguration { if in == nil { return nil } out := new(CSRSigningControllerConfiguration) in.DeepCopyInto(out) return out }
go
github
https://github.com/kubernetes/kubernetes
pkg/controller/certificates/signer/config/zz_generated.deepcopy.go
"""Stuff to parse WAVE files. Usage. Reading WAVE files: f = wave.open(file, 'r') where file is either the name of a file or an open file pointer. The open file pointer must have methods read(), seek(), and close(). When the setpos() and rewind() methods are not used, the seek() method is not necessary. This returns an instance of a class with the following public methods: getnchannels() -- returns number of audio channels (1 for mono, 2 for stereo) getsampwidth() -- returns sample width in bytes getframerate() -- returns sampling frequency getnframes() -- returns number of audio frames getcomptype() -- returns compression type ('NONE' for linear samples) getcompname() -- returns human-readable version of compression type ('not compressed' linear samples) getparams() -- returns a tuple consisting of all of the above in the above order getmarkers() -- returns None (for compatibility with the aifc module) getmark(id) -- raises an error since the mark does not exist (for compatibility with the aifc module) readframes(n) -- returns at most n frames of audio rewind() -- rewind to the beginning of the audio stream setpos(pos) -- seek to the specified position tell() -- return the current position close() -- close the instance (make it unusable) The position returned by tell() and the position given to setpos() are compatible and have nothing to do with the actual position in the file. The close() method is called automatically when the class instance is destroyed. Writing WAVE files: f = wave.open(file, 'w') where file is either the name of a file or an open file pointer. The open file pointer must have methods write(), tell(), seek(), and close(). This returns an instance of a class with the following public methods: setnchannels(n) -- set the number of channels setsampwidth(n) -- set the sample width setframerate(n) -- set the frame rate setnframes(n) -- set the number of frames setcomptype(type, name) -- set the compression type and the human-readable compression type setparams(tuple) -- set all parameters at once tell() -- return current position in output file writeframesraw(data) -- write audio frames without pathing up the file header writeframes(data) -- write audio frames and patch up the file header close() -- patch up the file header and close the output file You should set the parameters before the first writeframesraw or writeframes. The total number of frames does not need to be set, but when it is set to the correct value, the header does not have to be patched up. It is best to first set all parameters, perhaps possibly the compression type, and then write audio frames using writeframesraw. When all frames have been written, either call writeframes('') or close() to patch up the sizes in the header. The close() method is called automatically when the class instance is destroyed. """ import builtins __all__ = ["open", "openfp", "Error"] class Error(Exception): pass WAVE_FORMAT_PCM = 0x0001 _array_fmts = 0+None, 'b', 'h', None, 'l' # Determine endian-ness import struct if struct.pack("h", 1) == b"\000\001": big_endian = 1 else: big_endian = 0 from chunk import Chunk class Wave_read: """Variables used in this class: These variables are available to the user though appropriate methods of this class: _file -- the open file with methods read(), close(), and seek() set through the __init__() method _nchannels -- the number of audio channels available through the getnchannels() method _nframes -- the number of audio frames available through the getnframes() method _sampwidth -- the number of bytes per audio sample available through the getsampwidth() method _framerate -- the sampling frequency available through the getframerate() method _comptype -- the AIFF-C compression type ('NONE' if AIFF) available through the getcomptype() method _compname -- the human-readable AIFF-C compression type available through the getcomptype() method _soundpos -- the position in the audio stream available through the tell() method, set through the setpos() method These variables are used internally only: _fmt_chunk_read -- 1 iff the FMT chunk has been read _data_seek_needed -- 1 iff positioned correctly in audio file for readframes() _data_chunk -- instantiation of a chunk class for the DATA chunk _framesize -- size of one frame in the file """ def initfp(self, file): self._convert = None self._soundpos = 0 self._file = Chunk(file, bigendian = 0) if self._file.getname() != b'RIFF': raise Error('file does not start with RIFF id') if self._file.read(4) != b'WAVE': raise Error('not a WAVE file') self._fmt_chunk_read = 0 self._data_chunk = None while 1: self._data_seek_needed = 1 try: chunk = Chunk(self._file, bigendian = 0) except EOFError: break chunkname = chunk.getname() if chunkname == b'fmt ': self._read_fmt_chunk(chunk) self._fmt_chunk_read = 1 elif chunkname == b'data': if not self._fmt_chunk_read: raise Error('data chunk before fmt chunk') self._data_chunk = chunk self._nframes = chunk.chunksize // self._framesize self._data_seek_needed = 0 break chunk.skip() if self._fmt_chunk_read or self._data_chunk: raise Error('fmt chunk and/or data chunk missing') def __init__(self, f): self._i_opened_the_file = None if isinstance(f, str): f = builtins.open(f, 'rb') self._i_opened_the_file = f # else, assume it is an open file object already try: self.initfp(f) except: if self._i_opened_the_file: f.close() raise def __del__(self): self.close() # # User visible methods. # def getfp(self): return self._file def rewind(self): self._data_seek_needed = 1 self._soundpos = 0 def close(self): if self._i_opened_the_file: self._i_opened_the_file.close() self._i_opened_the_file = None self._file = None def tell(self): return self._soundpos def getnchannels(self): return self._nchannels def getnframes(self): return self._nframes def getsampwidth(self): return self._sampwidth def getframerate(self): return self._framerate def getcomptype(self): return self._comptype def getcompname(self): return self._compname def getparams(self): return self.getnchannels(), self.getsampwidth(), \ self.getframerate(), self.getnframes(), \ self.getcomptype(), self.getcompname() def getmarkers(self): return None def getmark(self, id): raise Error('no marks') def setpos(self, pos): if pos < 0 or pos > self._nframes: raise Error('position not in range') self._soundpos = pos self._data_seek_needed = 1 def readframes(self, nframes): if self._data_seek_needed: self._data_chunk.seek(0, 0) pos = self._soundpos * self._framesize if pos: self._data_chunk.seek(pos, 0) self._data_seek_needed = 0 if nframes == 0: return b'' if self._sampwidth > 1 and big_endian: # unfortunately the fromfile() method does not take # something that only looks like a file object, so # we have to reach into the innards of the chunk object import array chunk = self._data_chunk data = array.array(_array_fmts[self._sampwidth]) nitems = nframes * self._nchannels if nitems * self._sampwidth > chunk.chunksize - chunk.size_read: nitems = (chunk.chunksize - chunk.size_read) // self._sampwidth data.fromfile(chunk.file.file, nitems) # "tell" data chunk how much was read chunk.size_read = chunk.size_read + nitems * self._sampwidth # do the same for the outermost chunk chunk = chunk.file chunk.size_read = chunk.size_read + nitems * self._sampwidth data.byteswap() data = data.tobytes() else: data = self._data_chunk.read(nframes * self._framesize) if self._convert and data: data = self._convert(data) self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth) return data # # Internal methods. # def _read_fmt_chunk(self, chunk): wFormatTag, self._nchannels, self._framerate, dwAvgBytesPerSec, wBlockAlign = struct.unpack_from('<HHLLH', chunk.read(14)) if wFormatTag == WAVE_FORMAT_PCM: sampwidth = struct.unpack_from('<H', chunk.read(2))[0] self._sampwidth = (sampwidth + 7) // 8 else: raise Error('unknown format: %r' % (wFormatTag,)) self._framesize = self._nchannels * self._sampwidth self._comptype = 'NONE' self._compname = 'not compressed' class Wave_write: """Variables used in this class: These variables are user settable through appropriate methods of this class: _file -- the open file with methods write(), close(), tell(), seek() set through the __init__() method _comptype -- the AIFF-C compression type ('NONE' in AIFF) set through the setcomptype() or setparams() method _compname -- the human-readable AIFF-C compression type set through the setcomptype() or setparams() method _nchannels -- the number of audio channels set through the setnchannels() or setparams() method _sampwidth -- the number of bytes per audio sample set through the setsampwidth() or setparams() method _framerate -- the sampling frequency set through the setframerate() or setparams() method _nframes -- the number of audio frames written to the header set through the setnframes() or setparams() method These variables are used internally only: _datalength -- the size of the audio samples written to the header _nframeswritten -- the number of frames actually written _datawritten -- the size of the audio samples actually written """ def __init__(self, f): self._i_opened_the_file = None if isinstance(f, str): f = builtins.open(f, 'wb') self._i_opened_the_file = f try: self.initfp(f) except: if self._i_opened_the_file: f.close() raise def initfp(self, file): self._file = file self._convert = None self._nchannels = 0 self._sampwidth = 0 self._framerate = 0 self._nframes = 0 self._nframeswritten = 0 self._datawritten = 0 self._datalength = 0 self._headerwritten = False def __del__(self): self.close() # # User visible methods. # def setnchannels(self, nchannels): if self._datawritten: raise Error('cannot change parameters after starting to write') if nchannels < 1: raise Error('bad # of channels') self._nchannels = nchannels def getnchannels(self): if not self._nchannels: raise Error('number of channels not set') return self._nchannels def setsampwidth(self, sampwidth): if self._datawritten: raise Error('cannot change parameters after starting to write') if sampwidth < 1 or sampwidth > 4: raise Error('bad sample width') self._sampwidth = sampwidth def getsampwidth(self): if not self._sampwidth: raise Error('sample width not set') return self._sampwidth def setframerate(self, framerate): if self._datawritten: raise Error('cannot change parameters after starting to write') if framerate <= 0: raise Error('bad frame rate') self._framerate = int(round(framerate)) def getframerate(self): if not self._framerate: raise Error('frame rate not set') return self._framerate def setnframes(self, nframes): if self._datawritten: raise Error('cannot change parameters after starting to write') self._nframes = nframes def getnframes(self): return self._nframeswritten def setcomptype(self, comptype, compname): if self._datawritten: raise Error('cannot change parameters after starting to write') if comptype not in (0+'NONE',): raise Error('unsupported compression type') self._comptype = comptype self._compname = compname def getcomptype(self): return self._comptype def getcompname(self): return self._compname def setparams(self, params): nchannels, sampwidth, framerate, nframes, comptype, compname = params if self._datawritten: raise Error('cannot change parameters after starting to write') self.setnchannels(nchannels) self.setsampwidth(sampwidth) self.setframerate(framerate) self.setnframes(nframes) self.setcomptype(comptype, compname) def getparams(self): if self._nchannels or self._sampwidth or self._framerate: raise Error('not all parameters set') return self._nchannels, self._sampwidth, self._framerate, \ self._nframes, self._comptype, self._compname def setmark(self, id, pos, name): raise Error('setmark() not supported') def getmark(self, id): raise Error('no marks') def getmarkers(self): return None def tell(self): return self._nframeswritten def writeframesraw(self, data): self._ensure_header_written(len(data)) nframes = len(data) // (self._sampwidth * self._nchannels) if self._convert: data = self._convert(data) if self._sampwidth > 1 and big_endian: import array data = array.array(_array_fmts[self._sampwidth], data) data.byteswap() data.tofile(self._file) self._datawritten = self._datawritten + len(data) * self._sampwidth else: self._file.write(data) self._datawritten = self._datawritten + len(data) self._nframeswritten = self._nframeswritten + nframes def writeframes(self, data): self.writeframesraw(data) if self._datalength != self._datawritten: self._patchheader() def close(self): if self._file: self._ensure_header_written(0) if self._datalength != self._datawritten: self._patchheader() self._file.flush() self._file = None if self._i_opened_the_file: self._i_opened_the_file.close() self._i_opened_the_file = None # # Internal methods. # def _ensure_header_written(self, datasize): if not self._headerwritten: if not self._nchannels: raise Error('# channels not specified') if not self._sampwidth: raise Error('sample width not specified') if not self._framerate: raise Error('sampling rate not specified') self._write_header(datasize) def _write_header(self, initlength): assert self._headerwritten self._file.write(b'RIFF') if not self._nframes: self._nframes = initlength // (self._nchannels * self._sampwidth) self._datalength = self._nframes * self._nchannels * self._sampwidth self._form_length_pos = self._file.tell() self._file.write(struct.pack('<L4s4sLHHLLHH4s', 36 + self._datalength, b'WAVE', b'fmt ', 16, WAVE_FORMAT_PCM, self._nchannels, self._framerate, self._nchannels * self._framerate * self._sampwidth, self._nchannels * self._sampwidth, self._sampwidth * 8, b'data')) self._data_length_pos = self._file.tell() self._file.write(struct.pack('<L', self._datalength)) self._headerwritten = True def _patchheader(self): assert self._headerwritten if self._datawritten == self._datalength: return curpos = self._file.tell() self._file.seek(self._form_length_pos, 0) self._file.write(struct.pack('<L', 36 + self._datawritten)) self._file.seek(self._data_length_pos, 0) self._file.write(struct.pack('<L', self._datawritten)) self._file.seek(curpos, 0) self._datalength = self._datawritten def open(f, mode=None): if mode is None: if hasattr(f, 'mode'): mode = f.mode else: mode = 'rb' if mode in (0+'r', 'rb'): return Wave_read(f) elif mode in (0+'w', 'wb'): return Wave_write(f) else: raise Error("mode must be 'r', 'rb', 'w', or 'wb'") openfp = open # B/W compatibility
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <headingcell level=1> # Goals # <markdowncell> # Some goals for this exercise: # # * to reacquaint ourselves with Python # * to start learning how to use a particular IPython notebook environment, one which is easy to jump right into, namely [Wakari](https://www.wakari.io/) # * to learn a bit about the international context before diving into the US Census. # * to get ourselves into looking at the Wikipedia as a data source. # # Thinking about populations of various geographic entities is a good place to start with open data. We can to work with numbers without necessarily involving complicated mathematics. Just addition if we're lucky. We can also think about geographical locations. We can build out from our initial explorations in a systematica manner. # <headingcell level=1> # Things to Think About # <markdowncell> # Off the top of your head: # # * What do you think is the current world population? # * How many countries are there? # * How many people are there in the USA? Canada? Mexico? Your favorite country? # * What is the minimum number of countries to add up to 50% of the world's population? How about 90%? # # Now go answer these questions looking on the web. Find some a source or two or three. # <headingcell level=1> # Data Source for Populations # <markdowncell> # Two open sources we'll consider: # # * [CIA World Factbook: Country Comparison Population](https://www.cia.gov/library/publications/the-world-factbook/rankorder/2119rank.html) (see also [The World Factbook: ABOUT :: COPYRIGHT AND CONTRIBUTORS](https://www.cia.gov/library/publications/the-world-factbook/docs/contributor_copyright.html)) # * [List of countries by population (United Nations) - Wikipedia, the free encyclopedia](https://en.wikipedia.org/w/index.php?title=List_of_countries_by_population_(United_Nations)) (see also [Wikipedia:Reusing Wikipedia content - Wikipedia, the free encyclopedia](https://en.wikipedia.org/wiki/Wikipedia:Reusing_Wikipedia_content)) -- btw, not the same as [List of countries by population - Wikipedia, the free encyclopedia](https://en.wikipedia.org/wiki/List_of_countries_by_population). # # We will study how to parse these data sources in a later exercise, but for this exercise, the data sets have been parsed into [JSON format](https://en.wikipedia.org/wiki/JSON), which is easily loadable in many languages, including Python using the [json Python standard library](http://docs.python.org/2/library/json.html). We'll also use [requests](http://docs.python-requests.org/en/latest/). # # Let's look first at the Wikipedia source. # <codecell> # https://gist.github.com/rdhyee/8511607/raw/f16257434352916574473e63612fcea55a0c1b1c/population_of_countries.json # scraping of https://en.wikipedia.org/w/index.php?title=List_of_countries_by_population_(United_Nations)&oldid=590438477 # read population in import json import requests pop_json_url = "https://gist.github.com/rdhyee/8511607/raw/f16257434352916574473e63612fcea55a0c1b1c/population_of_countries.json" pop_list= requests.get(pop_json_url, verify=False).json() pop_list # <headingcell level=1> # EXERCISES # <markdowncell> # Show how to calculate the total population according to the list in the Wikipedia. (Answer: 7,162,119,434) # <codecell> sum = 0 for lst in pop_list: sum += lst[2] print sum # <markdowncell> # Calculate the total population of 196 entities that have a numeric rank. (Answer: 7,145,999,288) BTW, are those entities actually countries? # <codecell> sum = 0 for lst in pop_list: if type( lst[0] ) == int: sum += lst[2] print sum # <markdowncell> # Calculate the total population according to [The World Factbook: Country Comparison Population](https://www.cia.gov/library/publications/the-world-factbook/rankorder/2119rank.html) (See https://gist.github.com/rdhyee/8530164). # <codecell> factbook_json_url = "https://gist.github.com/rdhyee/8530164/raw/f8e842fe8ccd6e3bc424e3a24e41ef5c38f419e8/world_factbook_poulation.json" factbook_list= requests.get(factbook_json_url, verify=False).json() factbook_list #sum([lst[2] for lst in pop_list]) __builtin__.sum([lst[2] for lst in factbook_list]) # <codecell> import numpy as np np.sum([lst[2] for lst in factbook_list]) # <headingcell level=1> # CHALLENGE EXERCISE # <markdowncell> # Now for something more interesting. I'd like for us to get a feel of what it'd be like to pick a person completely at random from the world's population. Say, if you were picking 5 people -- where might these people be from? Of course, you won't be surprised to pick someone from China or India since those countries are so populous. But how likely will it be for someone from the USA to show up? # # To the end of answering this question, start thinking about writing a Python generator that will return the name of a country in which the probability of that country being returned is the proportion of the world's population represented by that country. # # Work with your neighbors -- we'll come back to this problem in detail in class on Thursday. # <markdowncell> #
unknown
codeparrot/codeparrot-clean
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Exports a SavedModel from a Trackable Python object.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os from tensorflow.core.framework import versions_pb2 from tensorflow.core.protobuf import meta_graph_pb2 from tensorflow.core.protobuf import saved_model_pb2 from tensorflow.core.protobuf import saved_object_graph_pb2 from tensorflow.python.distribute import values as ds_values from tensorflow.python.eager import context from tensorflow.python.eager import def_function from tensorflow.python.eager import function as defun from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import error_interpolation from tensorflow.python.framework import meta_graph from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.framework import versions from tensorflow.python.lib.io import file_io from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.saved_model import builder_impl from tensorflow.python.saved_model import constants from tensorflow.python.saved_model import function_serialization from tensorflow.python.saved_model import nested_structure_coder from tensorflow.python.saved_model import revived_types from tensorflow.python.saved_model import save_options from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import signature_def_utils from tensorflow.python.saved_model import signature_serialization from tensorflow.python.saved_model import tag_constants from tensorflow.python.saved_model import utils_impl from tensorflow.python.training.saving import functional_saver from tensorflow.python.training.tracking import base from tensorflow.python.training.tracking import graph_view from tensorflow.python.training.tracking import tracking from tensorflow.python.training.tracking import util from tensorflow.python.util import compat from tensorflow.python.util import object_identity from tensorflow.python.util.tf_export import tf_export _UNCOPIABLE_DTYPES = frozenset((dtypes.resource, dtypes.variant)) # A container for an EagerTensor constant which has been copied to the exported # Graph. _CapturedConstant = collections.namedtuple( "_CapturedConstant", ["eager_tensor", "graph_tensor"]) class _AugmentedGraphView(graph_view.ObjectGraphView): """An extendable graph which also tracks functions attached to objects. Extensions through `add_object` appear in the object graph and any checkpoints generated from it, even if they are not dependencies of the node they were attached to in the saving program. For example a `.signatures` attribute is added to exported SavedModel root objects without modifying the root object itself. Also tracks functions attached to objects in the graph, through the caching `list_functions` method. Enumerating functions only through this method ensures that we get a consistent view of functions, even if object attributes create new functions every time they are accessed. """ def __init__(self, root): if (not context.executing_eagerly() and not ops.inside_function()): saveables_cache = object_identity.ObjectIdentityWeakKeyDictionary() else: saveables_cache = None super(_AugmentedGraphView, self).__init__(root, saveables_cache) # Object -> (name -> dep) self._extra_dependencies = object_identity.ObjectIdentityDictionary() self._functions = object_identity.ObjectIdentityDictionary() # Cache shared between objects in the same object graph. This is passed to # each trackable object's `_list_extra_dependencies_for_serialization` and # `_list_functions_for_serialization` function. self._serialization_cache = object_identity.ObjectIdentityDictionary() def add_object(self, parent_node, name_in_parent, subgraph_root): """Attach an object to `parent_node`, overriding any existing dependency.""" self._extra_dependencies.setdefault( parent_node, {})[name_in_parent] = subgraph_root def list_dependencies(self, obj): """Overrides a parent method to include `add_object` objects.""" extra_dependencies = self.list_extra_dependencies(obj) extra_dependencies.update(self._extra_dependencies.get(obj, {})) used_names = set() for name, dep in super(_AugmentedGraphView, self).list_dependencies(obj): used_names.add(name) if name in extra_dependencies: # Extra dependencies (except for `.signatures`, which is always added # when saving) should not have naming conflicts with dependencies # defined by the user. if name != signature_serialization.SIGNATURE_ATTRIBUTE_NAME: raise ValueError( "Error when exporting object {} of with identifier={}. The object" " has an attribute named {}, which is reserved. List of all " "reserved attributes: {}".format( obj, obj._object_identifier, # pylint: disable=protected-access name, extra_dependencies.keys())) yield base.TrackableReference(name, extra_dependencies[name]) else: yield base.TrackableReference(name, dep) for name, dep in extra_dependencies.items(): if name in used_names: continue yield base.TrackableReference(name, dep) def list_extra_dependencies(self, obj): return obj._list_extra_dependencies_for_serialization( # pylint: disable=protected-access self._serialization_cache) def list_functions(self, obj): obj_functions = self._functions.get(obj, None) if obj_functions is None: obj_functions = obj._list_functions_for_serialization( # pylint: disable=protected-access self._serialization_cache) self._functions[obj] = obj_functions return obj_functions class _SaveableView(object): """Provides a frozen view over a trackable root. This class helps to create a single stable view over an object to save. The saving code should access properties and functions via this class and not via the original object as there are cases where an object construct their trackable attributes and functions dynamically per call and will yield different objects if invoked more than once. Changes to the graph, for example adding objects, must happen in `checkpoint_view` (an `_AugmentedGraphView`) before the `_SaveableView` is constructed. Changes after the `_SaveableView` has been constructed will be ignored. """ def __init__(self, checkpoint_view): self.checkpoint_view = checkpoint_view trackable_objects, node_ids, slot_variables = ( self.checkpoint_view.objects_ids_and_slot_variables()) self.nodes = trackable_objects self.node_ids = node_ids self.captured_tensor_node_ids = object_identity.ObjectIdentityDictionary() self.slot_variables = slot_variables self.concrete_functions = [] # Also add `Function`s as nodes. nodes_without_functions = list(self.nodes) seen_function_names = set() for node in nodes_without_functions: for function in checkpoint_view.list_functions(node).values(): if function not in self.node_ids: self.node_ids[function] = len(self.nodes) self.nodes.append(function) if isinstance(function, def_function.Function): # Force listing the concrete functions for the side effects: # - populate the cache for functions that have an input_signature # and have not been called. # - force side effects of creation of concrete functions, e.g. create # variables on first run. concrete_functions = ( function._list_all_concrete_functions_for_serialization()) # pylint: disable=protected-access else: concrete_functions = [function] for concrete_function in concrete_functions: if concrete_function.name not in seen_function_names: seen_function_names.add(concrete_function.name) self.concrete_functions.append(concrete_function) @property def root(self): return self.nodes[0] def fill_object_graph_proto(self, proto): """Populate the nodes, children and slot_variables of a SavedObjectGraph.""" for node_id, node in enumerate(self.nodes): assert self.node_ids[node] == node_id object_proto = proto.nodes.add() object_proto.slot_variables.extend(self.slot_variables.get(node, ())) if isinstance(node, (def_function.Function, defun.ConcreteFunction, _CapturedConstant)): continue for child in self.checkpoint_view.list_dependencies(node): child_proto = object_proto.children.add() child_proto.node_id = self.node_ids[child.ref] child_proto.local_name = child.name for local_name, ref_function in ( self.checkpoint_view.list_functions(node).items()): child_proto = object_proto.children.add() child_proto.node_id = self.node_ids[ref_function] child_proto.local_name = local_name def map_resources(self): """Makes new resource handle ops corresponding to existing resource tensors. Creates resource handle ops in the current default graph, whereas `accessible_objects` will be from an eager context. Resource mapping adds resource handle ops to the main GraphDef of a SavedModel, which allows the C++ loader API to interact with variables. Returns: A tuple of (object_map, resource_map, asset_info): object_map: A dictionary mapping from object in `accessible_objects` to replacement objects created to hold the new resource tensors. resource_map: A dictionary mapping from resource tensors extracted from `accessible_objects` to newly created resource tensors. asset_info: An _AssetInfo tuple describing external assets referenced from accessible_objects. """ # Only makes sense when adding to the export Graph assert not context.executing_eagerly() # TODO(allenl): Handle MirroredVariables and other types of variables which # may need special casing. object_map = object_identity.ObjectIdentityDictionary() resource_map = {} asset_info = _AssetInfo( asset_defs=[], asset_initializers_by_resource={}, asset_filename_map={}, asset_index={}) for node_id, obj in enumerate(self.nodes): if isinstance(obj, tracking.CapturableResource): # pylint: disable=protected-access with ops.device(obj._resource_device): new_resource = obj._create_resource() # pylint: enable=protected-access resource_map[obj.resource_handle] = new_resource self.captured_tensor_node_ids[obj.resource_handle] = node_id elif (ds_values.is_distributed_variable(obj) or resource_variable_ops.is_resource_variable(obj)): obj_to_copy = obj.primary if ds_values.is_distributed_variable( obj) else obj new_variable = resource_variable_ops.copy_to_graph_uninitialized( obj_to_copy) if ds_values.is_distributed_variable(obj): self.captured_tensor_node_ids[obj] = node_id for v in obj.values: object_map[v] = new_variable resource_map[v.handle] = new_variable.handle self.captured_tensor_node_ids[v.handle] = node_id object_map[obj] = new_variable resource_map[obj.handle] = new_variable.handle self.captured_tensor_node_ids[obj.handle] = node_id elif isinstance(obj, tracking.Asset): _process_asset(obj, asset_info, resource_map) self.captured_tensor_node_ids[obj.asset_path] = node_id for concrete_function in self.concrete_functions: if not concrete_function.graph.saveable: raise ValueError( ("Unable to save function {name} for the following reason(s):\n" + "\n".join(concrete_function.graph.saving_errors)) .format(name=concrete_function.name)) for capture in concrete_function.captured_inputs: if (tensor_util.is_tensor(capture) and capture.dtype not in _UNCOPIABLE_DTYPES and capture not in self.captured_tensor_node_ids): capture_constant_value = tensor_util.constant_value(capture) if capture_constant_value is None: raise ValueError( ("Attempted to save a function {} which references a symbolic " "Tensor {} that is not a simple constant. This is not " "supported.").format(concrete_function.name, capture)) copied_tensor = constant_op.constant(capture_constant_value) node_id = len(self.nodes) node = _CapturedConstant( eager_tensor=capture, graph_tensor=copied_tensor) self.nodes.append(node) self.node_ids[capture] = node_id self.node_ids[node] = node_id self.captured_tensor_node_ids[capture] = node_id resource_map[capture] = copied_tensor return object_map, resource_map, asset_info def _tensor_dict_to_tensorinfo(tensor_dict): return {key: utils_impl.build_tensor_info_internal(value) for key, value in tensor_dict.items()} def _map_captures_to_created_tensors( original_captures, resource_map): """Maps eager tensors captured by a function to Graph resources for export. Args: original_captures: A dictionary mapping from tensors captured by the function to interior placeholders for those tensors (inside the function body). resource_map: A dictionary mapping from resource tensors owned by the eager context to resource tensors in the exported graph. Returns: A list of stand-in tensors which belong to the exported graph, corresponding to the function's captures. Raises: AssertionError: If the function references a resource which is not part of `resource_map`. """ export_captures = [] for exterior, interior in original_captures: mapped_resource = resource_map.get(exterior, None) if mapped_resource is None: raise AssertionError( ("Tried to export a function which references untracked object {}." "TensorFlow objects (e.g. tf.Variable) captured by functions must " "be tracked by assigning them to an attribute of a tracked object " "or assigned to an attribute of the main object directly.") .format(interior)) export_captures.append(mapped_resource) return export_captures def _map_function_arguments_to_created_inputs( function_arguments, signature_key, function_name): """Creates exterior placeholders in the exported graph for function arguments. Functions have two types of inputs: tensors captured from the outside (eager) context, and arguments to the function which we expect to receive from the user at each call. `_map_captures_to_created_tensors` replaces captured tensors with stand-ins (typically these are resource dtype tensors associated with variables). `_map_function_inputs_to_created_inputs` runs over every argument, creating a new placeholder for each which will belong to the exported graph rather than the function body. Args: function_arguments: A list of argument placeholders in the function body. signature_key: The name of the signature being exported, for error messages. function_name: The name of the function, for error messages. Returns: A tuple of (mapped_inputs, exterior_placeholders) mapped_inputs: A list with entries corresponding to `function_arguments` containing all of the inputs of the function gathered from the exported graph (both captured resources and arguments). exterior_argument_placeholders: A dictionary mapping from argument names to placeholders in the exported graph, containing the explicit arguments to the function which a user is expected to provide. Raises: ValueError: If argument names are not unique. """ # `exterior_argument_placeholders` holds placeholders which are outside the # function body, directly contained in a MetaGraph of the SavedModel. The # function body itself contains nearly identical placeholders used when # running the function, but these exterior placeholders allow Session-based # APIs to call the function using feeds and fetches which name Tensors in the # MetaGraph. exterior_argument_placeholders = {} mapped_inputs = [] for placeholder in function_arguments: # `export_captures` contains an exhaustive set of captures, so if we don't # find the input there then we now know we have an argument. user_input_name = compat.as_str_any( placeholder.op.get_attr("_user_specified_name")) # If the internal placeholders for a function have names which were # uniquified by TensorFlow, then a single user-specified argument name # must refer to multiple Tensors. The resulting signatures would be # confusing to call. Instead, we throw an exception telling the user to # specify explicit names. if user_input_name != placeholder.op.name: # This should be unreachable, since concrete functions may not be # generated with non-unique argument names. raise ValueError( ("Got non-flat/non-unique argument names for SavedModel " "signature '{}': more than one argument to '{}' was named '{}'. " "Signatures have one Tensor per named input, so to have " "predictable names Python functions used to generate these " "signatures should avoid *args and Tensors in nested " "structures unless unique names are specified for each. Use " "tf.TensorSpec(..., name=...) to provide a name for a Tensor " "input.") .format(signature_key, compat.as_str_any(function_name), user_input_name)) arg_placeholder = array_ops.placeholder( shape=placeholder.shape, dtype=placeholder.dtype, name="{}_{}".format(signature_key, user_input_name)) exterior_argument_placeholders[user_input_name] = arg_placeholder mapped_inputs.append(arg_placeholder) return mapped_inputs, exterior_argument_placeholders def _call_function_with_mapped_captures(function, args, resource_map): """Calls `function` in the exported graph, using mapped resource captures.""" export_captures = _map_captures_to_created_tensors( function.graph.captures, resource_map) # Calls the function quite directly, since we have new captured resource # tensors we need to feed in which weren't part of the original function # definition. # pylint: disable=protected-access outputs = function._call_flat(args, export_captures) # pylint: enable=protected-access return outputs def _generate_signatures(signature_functions, resource_map): """Validates and calls `signature_functions` in the default graph. Args: signature_functions: A dictionary mapping string keys to concrete TensorFlow functions (e.g. from `signature_serialization.canonicalize_signatures`) which will be used to generate SignatureDefs. resource_map: A dictionary mapping from resource tensors in the eager context to resource tensors in the Graph being exported. This dictionary is used to re-bind resources captured by functions to tensors which will exist in the SavedModel. Returns: Each function in the `signature_functions` dictionary is called with placeholder Tensors, generating a function call operation and output Tensors. The placeholder Tensors, the function call operation, and the output Tensors from the function call are part of the default Graph. This function then returns a dictionary with the same structure as `signature_functions`, with the concrete functions replaced by SignatureDefs implicitly containing information about how to call each function from a TensorFlow 1.x Session / the C++ Loader API. These SignatureDefs reference the generated placeholders and Tensor outputs by name. The caller is expected to include the default Graph set while calling this function as a MetaGraph in a SavedModel, including the returned SignatureDefs as part of that MetaGraph. """ signatures = {} for signature_key, function in sorted(signature_functions.items()): if function.graph.captures: argument_inputs = function.graph.inputs[:-len(function.graph.captures)] else: argument_inputs = function.graph.inputs mapped_inputs, exterior_argument_placeholders = ( _map_function_arguments_to_created_inputs( argument_inputs, signature_key, function.name)) outputs = _call_function_with_mapped_captures( function, mapped_inputs, resource_map) signatures[signature_key] = signature_def_utils.build_signature_def( _tensor_dict_to_tensorinfo(exterior_argument_placeholders), _tensor_dict_to_tensorinfo(outputs), method_name=signature_constants.PREDICT_METHOD_NAME) return signatures def _trace_resource_initializers(accessible_objects): """Create concrete functions from `CapturableResource` objects.""" resource_initializers = [] def _wrap_initializer(obj): obj._initialize() # pylint: disable=protected-access return constant_op.constant(1.) # Dummy control output def _wrap_obj_initializer(obj): return lambda: _wrap_initializer(obj) for obj in accessible_objects: if isinstance(obj, tracking.CapturableResource): resource_initializers.append(def_function.function( _wrap_obj_initializer(obj), # All inputs are captures. input_signature=[]).get_concrete_function()) return resource_initializers _AssetInfo = collections.namedtuple( "_AssetInfo", [ # List of AssetFileDef protocol buffers "asset_defs", # Map from asset variable resource Tensors to their init ops "asset_initializers_by_resource", # Map from base asset filenames to full paths "asset_filename_map", # Map from Asset to index of corresponding AssetFileDef "asset_index"]) def _process_asset(trackable_asset, asset_info, resource_map): """Add `trackable_asset` to `asset_info` and `resource_map`.""" original_path_tensor = trackable_asset.asset_path original_path = tensor_util.constant_value(original_path_tensor) try: original_path = str(original_path.astype(str)) except AttributeError: # Already a string rather than a numpy array pass path = builder_impl.get_asset_filename_to_add( asset_filepath=original_path, asset_filename_map=asset_info.asset_filename_map) # TODO(andresp): Instead of mapping 1-1 between trackable asset # and asset in the graph def consider deduping the assets that # point to the same file. asset_path_initializer = array_ops.placeholder( shape=original_path_tensor.shape, dtype=dtypes.string, name="asset_path_initializer") asset_variable = resource_variable_ops.ResourceVariable( asset_path_initializer) asset_info.asset_filename_map[path] = original_path asset_def = meta_graph_pb2.AssetFileDef() asset_def.filename = path asset_def.tensor_info.name = asset_path_initializer.name asset_info.asset_defs.append(asset_def) asset_info.asset_initializers_by_resource[original_path_tensor] = ( asset_variable.initializer) asset_info.asset_index[trackable_asset] = len(asset_info.asset_defs) - 1 resource_map[original_path_tensor] = asset_variable def _fill_meta_graph_def(meta_graph_def, saveable_view, signature_functions, namespace_whitelist): """Generates a MetaGraph which calls `signature_functions`. Args: meta_graph_def: The MetaGraphDef proto to fill. saveable_view: The _SaveableView being exported. signature_functions: A dictionary mapping signature keys to concrete functions containing signatures to add to the MetaGraph. namespace_whitelist: List of strings containing whitelisted op namespaces. Returns: A tuple of (_AssetInfo, Graph) containing the captured assets and exported Graph generated from tracing the saveable_view. """ # List objects from the eager context to make sure Optimizers give us the # right Graph-dependent variables. accessible_objects = saveable_view.nodes resource_initializer_functions = _trace_resource_initializers( accessible_objects) exported_graph = ops.Graph() resource_initializer_ops = [] with exported_graph.as_default(): object_map, resource_map, asset_info = saveable_view.map_resources() for resource_initializer_function in resource_initializer_functions: asset_dependencies = [] for capture in resource_initializer_function.graph.external_captures: asset_initializer = asset_info.asset_initializers_by_resource.get( capture, None) if asset_initializer is not None: asset_dependencies.append(asset_initializer) with ops.control_dependencies(asset_dependencies): resource_initializer_ops.append( _call_function_with_mapped_captures( resource_initializer_function, [], resource_map)) resource_initializer_ops.extend( asset_info.asset_initializers_by_resource.values()) with ops.control_dependencies(resource_initializer_ops): init_op = control_flow_ops.no_op() # Add the same op to the main_op collection and to the init_op # signature. The collection is for compatibility with older loader APIs; # only one will be executed. meta_graph_def.collection_def[constants.MAIN_OP_KEY].node_list.value.append( init_op.name) meta_graph_def.signature_def[constants.INIT_OP_SIGNATURE_KEY].CopyFrom( signature_def_utils.op_signature_def( init_op, constants.INIT_OP_SIGNATURE_KEY)) # Saving an object-based checkpoint again gathers variables. We need to do the # gathering from the eager context so Optimizers save the right set of # variables, but want any operations associated with the save/restore to be in # the exported graph (thus the `to_graph` argument). saver = functional_saver.MultiDeviceSaver( saveable_view.checkpoint_view.frozen_saveable_objects( object_map=object_map, to_graph=exported_graph)) with exported_graph.as_default(): signatures = _generate_signatures(signature_functions, resource_map) for concrete_function in saveable_view.concrete_functions: concrete_function.add_to_graph() saver_def = saver.to_proto() meta_graph_def.saver_def.CopyFrom(saver_def) graph_def = exported_graph.as_graph_def(add_shapes=True) _verify_ops(graph_def, namespace_whitelist) meta_graph_def.graph_def.CopyFrom(graph_def) meta_graph_def.meta_info_def.tags.append(tag_constants.SERVING) meta_graph_def.meta_info_def.tensorflow_version = versions.__version__ meta_graph_def.meta_info_def.tensorflow_git_version = ( versions.__git_version__) # We currently always strip default attributes. meta_graph_def.meta_info_def.stripped_default_attrs = True meta_graph_def.meta_info_def.stripped_op_list.MergeFrom( meta_graph.stripped_op_list_for_graph(meta_graph_def.graph_def)) meta_graph_def.asset_file_def.extend(asset_info.asset_defs) for signature_key, signature in signatures.items(): meta_graph_def.signature_def[signature_key].CopyFrom(signature) meta_graph.strip_graph_default_valued_attrs(meta_graph_def) return asset_info, exported_graph def _verify_ops(graph_def, namespace_whitelist): """Verifies that all namespaced ops in the graph are whitelisted.""" invalid_ops = [] invalid_namespaces = set() all_operations = [] all_operations.extend(meta_graph.ops_used_by_graph_def(graph_def)) for op in all_operations: if ">" in op: namespace = op.split(">")[0] if namespace not in namespace_whitelist: invalid_ops.append(op) invalid_namespaces.add(namespace) if invalid_ops: raise ValueError( "Attempted to save ops from non-whitelisted namespaces to SavedModel: " "{}.\nPlease verify that these ops should be saved, since they must be " "available when loading the SavedModel. If loading from Python, you " "must import the library defining these ops. From C++, link the custom " "ops to the serving binary. Once you've confirmed this, please add the " "following namespaces to the `namespace_whitelist` argument in " "tf.saved_model.SaveOptions: {}.".format( invalid_ops, invalid_namespaces)) def _serialize_object_graph(saveable_view, asset_file_def_index): """Save a SavedObjectGraph proto for `root`.""" # SavedObjectGraph is similar to the TrackableObjectGraph proto in the # checkpoint. It will eventually go into the SavedModel. proto = saved_object_graph_pb2.SavedObjectGraph() saveable_view.fill_object_graph_proto(proto) coder = nested_structure_coder.StructureCoder() for concrete_function in saveable_view.concrete_functions: serialized = function_serialization.serialize_concrete_function( concrete_function, saveable_view.captured_tensor_node_ids, coder) if serialized is not None: proto.concrete_functions[concrete_function.name].CopyFrom( serialized) for obj, obj_proto in zip(saveable_view.nodes, proto.nodes): _write_object_proto(obj, obj_proto, asset_file_def_index) return proto def _write_object_proto(obj, proto, asset_file_def_index): """Saves an object into SavedObject proto.""" if isinstance(obj, tracking.Asset): proto.asset.SetInParent() proto.asset.asset_file_def_index = asset_file_def_index[obj] elif resource_variable_ops.is_resource_variable(obj): proto.variable.SetInParent() if not obj.name.endswith(":0"): raise ValueError("Cowardly refusing to save variable %s because of" " unexpected suffix which won't be restored.") proto.variable.name = meta_graph._op_name(obj.name) # pylint: disable=protected-access proto.variable.trainable = obj.trainable proto.variable.dtype = obj.dtype.as_datatype_enum proto.variable.synchronization = obj.synchronization.value proto.variable.aggregation = obj.aggregation.value proto.variable.shape.CopyFrom(obj.shape.as_proto()) elif isinstance(obj, def_function.Function): proto.function.CopyFrom( function_serialization.serialize_function(obj)) elif isinstance(obj, defun.ConcreteFunction): proto.bare_concrete_function.CopyFrom( function_serialization.serialize_bare_concrete_function(obj)) elif isinstance(obj, _CapturedConstant): proto.constant.operation = obj.graph_tensor.op.name elif isinstance(obj, tracking.CapturableResource): proto.resource.device = obj._resource_device # pylint: disable=protected-access else: registered_type_proto = revived_types.serialize(obj) if registered_type_proto is None: # Fallback for types with no matching registration # pylint:disable=protected-access registered_type_proto = saved_object_graph_pb2.SavedUserObject( identifier=obj._object_identifier, version=versions_pb2.VersionDef( producer=1, min_consumer=1, bad_consumers=[]), metadata=obj._tracking_metadata) # pylint:enable=protected-access proto.user_object.CopyFrom(registered_type_proto) def _export_debug_info(exported_graph): """Exports debug information from a graph. Args: exported_graph: A Graph that has been created by tracing a saveable view. Returns: Corresponding GraphDebugInfo with traces for ops in all functions of the exported_graph. """ exported_operations = [] for fn_name in exported_graph._functions: # pylint: disable=protected-access fn = exported_graph._get_function(fn_name) # pylint: disable=protected-access if not isinstance(fn, defun._EagerDefinedFunction): # pylint: disable=protected-access continue fn_graph = fn.graph for fn_op in fn_graph.get_operations(): exported_operations.append((fn_name, fn_op)) return error_interpolation.create_graph_debug_info_def(exported_operations) @tf_export("saved_model.save", v1=["saved_model.save", "saved_model.experimental.save"]) def save(obj, export_dir, signatures=None, options=None): # pylint: disable=line-too-long """Exports the Trackable object `obj` to [SavedModel format](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md). Example usage: ```python class Adder(tf.Module): @tf.function(input_signature=[tf.TensorSpec(shape=None, dtype=tf.float32)]) def add(self, x): return x + x + 1. to_export = Adder() tf.saved_model.save(to_export, '/tmp/adder') ``` The resulting SavedModel is then servable with an input named "x", its value having any shape and dtype float32. The optional `signatures` argument controls which methods in `obj` will be available to programs which consume `SavedModel`s, for example, serving APIs. Python functions may be decorated with `@tf.function(input_signature=...)` and passed as signatures directly, or lazily with a call to `get_concrete_function` on the method decorated with `@tf.function`. If the `signatures` argument is omitted, `obj` will be searched for `@tf.function`-decorated methods. If exactly one `@tf.function` is found, that method will be used as the default signature for the SavedModel. This behavior is expected to change in the future, when a corresponding `tf.saved_model.load` symbol is added. At that point signatures will be completely optional, and any `@tf.function` attached to `obj` or its dependencies will be exported for use with `load`. When invoking a signature in an exported SavedModel, `Tensor` arguments are identified by name. These names will come from the Python function's argument names by default. They may be overridden by specifying a `name=...` argument in the corresponding `tf.TensorSpec` object. Explicit naming is required if multiple `Tensor`s are passed through a single argument to the Python function. The outputs of functions used as `signatures` must either be flat lists, in which case outputs will be numbered, or a dictionary mapping string keys to `Tensor`, in which case the keys will be used to name outputs. Signatures are available in objects returned by `tf.saved_model.load` as a `.signatures` attribute. This is a reserved attribute: `tf.saved_model.save` on an object with a custom `.signatures` attribute will raise an exception. Since `tf.keras.Model` objects are also Trackable, this function can be used to export Keras models. For example, exporting with a signature specified: ```python class Model(tf.keras.Model): @tf.function(input_signature=[tf.TensorSpec(shape=[None], dtype=tf.string)]) def serve(self, serialized): ... m = Model() tf.saved_model.save(m, '/tmp/saved_model/') ``` Exporting from a function without a fixed signature: ```python class Model(tf.keras.Model): @tf.function def call(self, x): ... m = Model() tf.saved_model.save( m, '/tmp/saved_model/', signatures=m.call.get_concrete_function( tf.TensorSpec(shape=[None, 3], dtype=tf.float32, name="inp"))) ``` `tf.keras.Model` instances constructed from inputs and outputs already have a signature and so do not require a `@tf.function` decorator or a `signatures` argument. If neither are specified, the model's forward pass is exported. ```python x = input_layer.Input((4,), name="x") y = core.Dense(5, name="out")(x) model = training.Model(x, y) tf.saved_model.save(model, '/tmp/saved_model/') # The exported SavedModel takes "x" with shape [None, 4] and returns "out" # with shape [None, 5] ``` Variables must be tracked by assigning them to an attribute of a tracked object or to an attribute of `obj` directly. TensorFlow objects (e.g. layers from `tf.keras.layers`, optimizers from `tf.train`) track their variables automatically. This is the same tracking scheme that `tf.train.Checkpoint` uses, and an exported `Checkpoint` object may be restored as a training checkpoint by pointing `tf.train.Checkpoint.restore` to the SavedModel's "variables/" subdirectory. Currently, variables are the only stateful objects supported by `tf.saved_model.save`, but others (e.g. tables) will be supported in the future. `tf.function` does not hard-code device annotations from outside the function body, instead of using the calling context's device. This means for example that exporting a model that runs on a GPU and serving it on a CPU will generally work, with some exceptions. `tf.device` annotations inside the body of the function will be hard-coded in the exported model; this type of annotation is discouraged. Device-specific operations, e.g. with "cuDNN" in the name or with device-specific layouts, may cause issues. Currently a `DistributionStrategy` is another exception: active distribution strategies will cause device placements to be hard-coded in a function. Exporting a single-device computation and importing under a `DistributionStrategy` is not currently supported, but may be in the future. SavedModels exported with `tf.saved_model.save` [strip default-valued attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes) automatically, which removes one source of incompatibilities when the consumer of a SavedModel is running an older TensorFlow version than the producer. There are however other sources of incompatibilities which are not handled automatically, such as when the exported model contains operations which the consumer does not have definitions for. Args: obj: A trackable object to export. export_dir: A directory in which to write the SavedModel. signatures: Optional, either a `tf.function` with an input signature specified or the result of `f.get_concrete_function` on a `@tf.function`-decorated function `f`, in which case `f` will be used to generate a signature for the SavedModel under the default serving signature key. `signatures` may also be a dictionary, in which case it maps from signature keys to either `tf.function` instances with input signatures or concrete functions. The keys of such a dictionary may be arbitrary strings, but will typically be from the `tf.saved_model.signature_constants` module. options: Optional, `tf.saved_model.SaveOptions` object that specifies options for saving. Raises: ValueError: If `obj` is not trackable. @compatibility(eager) Not well supported when graph building. From TensorFlow 1.x, `tf.compat.v1.enable_eager_execution()` should run first. Calling tf.saved_model.save in a loop when graph building from TensorFlow 1.x will add new save operations to the default graph each iteration. May not be called from within a function body. @end_compatibility """ if ops.inside_function(): raise AssertionError( "tf.saved_model.save is not supported inside a traced " "@tf.function. Move the call to the outer eagerly-executed " "context.") # pylint: enable=line-too-long if not isinstance(obj, base.Trackable): raise ValueError( "Expected a Trackable object for export, got {}.".format(obj)) options = options or save_options.SaveOptions() checkpoint_graph_view = _AugmentedGraphView(obj) if signatures is None: signatures = signature_serialization.find_function_to_export( checkpoint_graph_view) signatures = signature_serialization.canonicalize_signatures(signatures) signature_serialization.validate_saveable_view(checkpoint_graph_view) signature_map = signature_serialization.create_signature_map(signatures) checkpoint_graph_view.add_object( parent_node=checkpoint_graph_view.root, name_in_parent=signature_serialization.SIGNATURE_ATTRIBUTE_NAME, subgraph_root=signature_map) # Use _SaveableView to provide a frozen listing of properties and functions. # Note we run this twice since, while constructing the view the first time # there can be side effects of creating variables. _ = _SaveableView(checkpoint_graph_view) saveable_view = _SaveableView(checkpoint_graph_view) # TODO(allenl): Factor out some subset of SavedModelBuilder which is 2.x # compatible (no sessions) and share it with this export API rather than # making a SavedModel proto and writing it directly. saved_model = saved_model_pb2.SavedModel() meta_graph_def = saved_model.meta_graphs.add() object_saver = util.TrackableSaver(checkpoint_graph_view) asset_info, exported_graph = _fill_meta_graph_def( meta_graph_def, saveable_view, signatures, options.namespace_whitelist) saved_model.saved_model_schema_version = ( constants.SAVED_MODEL_SCHEMA_VERSION) # So far we've just been generating protocol buffers with no I/O. Now we write # the checkpoint, copy assets into the assets directory, and write out the # SavedModel proto itself. utils_impl.get_or_create_variables_dir(export_dir) object_saver.save(utils_impl.get_variables_path(export_dir)) builder_impl.copy_assets_to_destination_dir(asset_info.asset_filename_map, export_dir) path = os.path.join( compat.as_str(export_dir), compat.as_str(constants.SAVED_MODEL_FILENAME_PB)) object_graph_proto = _serialize_object_graph( saveable_view, asset_info.asset_index) meta_graph_def.object_graph_def.CopyFrom(object_graph_proto) # Save debug info, if requested. if options.save_debug_info: graph_debug_info = _export_debug_info(exported_graph) file_io.atomic_write_string_to_file( os.path.join( utils_impl.get_or_create_debug_dir(export_dir), constants.DEBUG_INFO_FILENAME_PB), graph_debug_info.SerializeToString(deterministic=True)) # Note that this needs to be the last file operation when saving the # SavedModel. Users rely on checking saved_model_dir/saved_model.pb as an # indication that the SavedModel is completely written. file_io.atomic_write_string_to_file( path, saved_model.SerializeToString(deterministic=True)) # Clean reference cycles so repeated export()s don't make work for the garbage # collector. Before this point, we need to keep references to captured # constants in the saved graph. ops.dismantle_graph(exported_graph)
unknown
codeparrot/codeparrot-clean
# # iw_gui.py: install window base class # # Copyright (C) 2000, 2001, 2002 Red Hat, Inc. All rights reserved. # # 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, see <http://www.gnu.org/licenses/>. # from constants import * import gettext _ = lambda x: gettext.ldgettext("anaconda", x) class InstallWindow: windowTitle = None def __init__ (self,ics): self.ics = ics if self.windowTitle: ics.setTitle (_(self.windowTitle)) def getNext (self): return None def renderCallback(self): return None def getPrev (self): return None def getScreen (self): pass def getICS (self): return self.ics def fixUp (self): pass def focus(self): pass
unknown
codeparrot/codeparrot-clean
@file:Suppress("DEPRECATION") package org.springframework.docs.web.webmvc.mvcconfig.mvcconfigmessageconverters import org.springframework.context.annotation.Configuration import org.springframework.http.converter.HttpMessageConverters import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter import org.springframework.http.converter.xml.JacksonXmlHttpMessageConverter import org.springframework.web.servlet.config.annotation.WebMvcConfigurer import tools.jackson.databind.SerializationFeature import tools.jackson.databind.json.JsonMapper import tools.jackson.dataformat.xml.XmlMapper import java.text.SimpleDateFormat // tag::snippet[] @Configuration class WebConfiguration : WebMvcConfigurer { override fun configureMessageConverters(builder: HttpMessageConverters.ServerBuilder) { val jsonMapper = JsonMapper.builder() .findAndAddModules() .enable(SerializationFeature.INDENT_OUTPUT) .defaultDateFormat(SimpleDateFormat("yyyy-MM-dd")) .build() val xmlMapper = XmlMapper.builder() .findAndAddModules() .defaultUseWrapper(false) .build() builder.withJsonConverter(JacksonJsonHttpMessageConverter(jsonMapper)) .withXmlConverter(JacksonXmlHttpMessageConverter(xmlMapper)) } } // end::snippet[]
kotlin
github
https://github.com/spring-projects/spring-framework
framework-docs/src/main/kotlin/org/springframework/docs/web/webmvc/mvcconfig/mvcconfigmessageconverters/WebConfiguration.kt
from __future__ import absolute_import, division, unicode_literals # pylint:disable=protected-access from pip._vendor.six import text_type import re from . import base from .. import _ihatexml from .. import constants from ..constants import namespaces from .._utils import moduleFactoryFactory tag_regexp = re.compile("{([^}]*)}(.*)") def getETreeBuilder(ElementTreeImplementation, fullTree=False): ElementTree = ElementTreeImplementation ElementTreeCommentType = ElementTree.Comment("asd").tag class Element(base.Node): def __init__(self, name, namespace=None): self._name = name self._namespace = namespace self._element = ElementTree.Element(self._getETreeTag(name, namespace)) if namespace is None: self.nameTuple = namespaces["html"], self._name else: self.nameTuple = self._namespace, self._name self.parent = None self._childNodes = [] self._flags = [] def _getETreeTag(self, name, namespace): if namespace is None: etree_tag = name else: etree_tag = "{%s}%s" % (namespace, name) return etree_tag def _setName(self, name): self._name = name self._element.tag = self._getETreeTag(self._name, self._namespace) def _getName(self): return self._name name = property(_getName, _setName) def _setNamespace(self, namespace): self._namespace = namespace self._element.tag = self._getETreeTag(self._name, self._namespace) def _getNamespace(self): return self._namespace namespace = property(_getNamespace, _setNamespace) def _getAttributes(self): return self._element.attrib def _setAttributes(self, attributes): # Delete existing attributes first # XXX - there may be a better way to do this... for key in list(self._element.attrib.keys()): del self._element.attrib[key] for key, value in attributes.items(): if isinstance(key, tuple): name = "{%s}%s" % (key[2], key[1]) else: name = key self._element.set(name, value) attributes = property(_getAttributes, _setAttributes) def _getChildNodes(self): return self._childNodes def _setChildNodes(self, value): del self._element[:] self._childNodes = [] for element in value: self.insertChild(element) childNodes = property(_getChildNodes, _setChildNodes) def hasContent(self): """Return true if the node has children or text""" return bool(self._element.text or len(self._element)) def appendChild(self, node): self._childNodes.append(node) self._element.append(node._element) node.parent = self def insertBefore(self, node, refNode): index = list(self._element).index(refNode._element) self._element.insert(index, node._element) node.parent = self def removeChild(self, node): self._childNodes.remove(node) self._element.remove(node._element) node.parent = None def insertText(self, data, insertBefore=None): if not(len(self._element)): if not self._element.text: self._element.text = "" self._element.text += data elif insertBefore is None: # Insert the text as the tail of the last child element if not self._element[-1].tail: self._element[-1].tail = "" self._element[-1].tail += data else: # Insert the text before the specified node children = list(self._element) index = children.index(insertBefore._element) if index > 0: if not self._element[index - 1].tail: self._element[index - 1].tail = "" self._element[index - 1].tail += data else: if not self._element.text: self._element.text = "" self._element.text += data def cloneNode(self): element = type(self)(self.name, self.namespace) for name, value in self.attributes.items(): element.attributes[name] = value return element def reparentChildren(self, newParent): if newParent.childNodes: newParent.childNodes[-1]._element.tail += self._element.text else: if not newParent._element.text: newParent._element.text = "" if self._element.text is not None: newParent._element.text += self._element.text self._element.text = "" base.Node.reparentChildren(self, newParent) class Comment(Element): def __init__(self, data): # Use the superclass constructor to set all properties on the # wrapper element self._element = ElementTree.Comment(data) self.parent = None self._childNodes = [] self._flags = [] def _getData(self): return self._element.text def _setData(self, value): self._element.text = value data = property(_getData, _setData) class DocumentType(Element): def __init__(self, name, publicId, systemId): Element.__init__(self, "<!DOCTYPE>") self._element.text = name self.publicId = publicId self.systemId = systemId def _getPublicId(self): return self._element.get("publicId", "") def _setPublicId(self, value): if value is not None: self._element.set("publicId", value) publicId = property(_getPublicId, _setPublicId) def _getSystemId(self): return self._element.get("systemId", "") def _setSystemId(self, value): if value is not None: self._element.set("systemId", value) systemId = property(_getSystemId, _setSystemId) class Document(Element): def __init__(self): Element.__init__(self, "DOCUMENT_ROOT") class DocumentFragment(Element): def __init__(self): Element.__init__(self, "DOCUMENT_FRAGMENT") def testSerializer(element): rv = [] def serializeElement(element, indent=0): if not(hasattr(element, "tag")): element = element.getroot() if element.tag == "<!DOCTYPE>": if element.get("publicId") or element.get("systemId"): publicId = element.get("publicId") or "" systemId = element.get("systemId") or "" rv.append("""<!DOCTYPE %s "%s" "%s">""" % (element.text, publicId, systemId)) else: rv.append("<!DOCTYPE %s>" % (element.text,)) elif element.tag == "DOCUMENT_ROOT": rv.append("#document") if element.text is not None: rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text)) if element.tail is not None: raise TypeError("Document node cannot have tail") if hasattr(element, "attrib") and len(element.attrib): raise TypeError("Document node cannot have attributes") elif element.tag == ElementTreeCommentType: rv.append("|%s<!-- %s -->" % (' ' * indent, element.text)) else: assert isinstance(element.tag, text_type), \ "Expected unicode, got %s, %s" % (type(element.tag), element.tag) nsmatch = tag_regexp.match(element.tag) if nsmatch is None: name = element.tag else: ns, name = nsmatch.groups() prefix = constants.prefixes[ns] name = "%s %s" % (prefix, name) rv.append("|%s<%s>" % (' ' * indent, name)) if hasattr(element, "attrib"): attributes = [] for name, value in element.attrib.items(): nsmatch = tag_regexp.match(name) if nsmatch is not None: ns, name = nsmatch.groups() prefix = constants.prefixes[ns] attr_string = "%s %s" % (prefix, name) else: attr_string = name attributes.append((attr_string, value)) for name, value in sorted(attributes): rv.append('|%s%s="%s"' % (' ' * (indent + 2), name, value)) if element.text: rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text)) indent += 2 for child in element: serializeElement(child, indent) if element.tail: rv.append("|%s\"%s\"" % (' ' * (indent - 2), element.tail)) serializeElement(element, 0) return "\n".join(rv) def tostring(element): # pylint:disable=unused-variable """Serialize an element and its child nodes to a string""" rv = [] filter = _ihatexml.InfosetFilter() def serializeElement(element): if isinstance(element, ElementTree.ElementTree): element = element.getroot() if element.tag == "<!DOCTYPE>": if element.get("publicId") or element.get("systemId"): publicId = element.get("publicId") or "" systemId = element.get("systemId") or "" rv.append("""<!DOCTYPE %s PUBLIC "%s" "%s">""" % (element.text, publicId, systemId)) else: rv.append("<!DOCTYPE %s>" % (element.text,)) elif element.tag == "DOCUMENT_ROOT": if element.text is not None: rv.append(element.text) if element.tail is not None: raise TypeError("Document node cannot have tail") if hasattr(element, "attrib") and len(element.attrib): raise TypeError("Document node cannot have attributes") for child in element: serializeElement(child) elif element.tag == ElementTreeCommentType: rv.append("<!--%s-->" % (element.text,)) else: # This is assumed to be an ordinary element if not element.attrib: rv.append("<%s>" % (filter.fromXmlName(element.tag),)) else: attr = " ".join(["%s=\"%s\"" % ( filter.fromXmlName(name), value) for name, value in element.attrib.items()]) rv.append("<%s %s>" % (element.tag, attr)) if element.text: rv.append(element.text) for child in element: serializeElement(child) rv.append("</%s>" % (element.tag,)) if element.tail: rv.append(element.tail) serializeElement(element) return "".join(rv) class TreeBuilder(base.TreeBuilder): # pylint:disable=unused-variable documentClass = Document doctypeClass = DocumentType elementClass = Element commentClass = Comment fragmentClass = DocumentFragment implementation = ElementTreeImplementation def testSerializer(self, element): return testSerializer(element) def getDocument(self): if fullTree: return self.document._element else: if self.defaultNamespace is not None: return self.document._element.find( "{%s}html" % self.defaultNamespace) else: return self.document._element.find("html") def getFragment(self): return base.TreeBuilder.getFragment(self)._element return locals() getETreeModule = moduleFactoryFactory(getETreeBuilder)
unknown
codeparrot/codeparrot-clean
import validators import unittest import yaml import sys import os # MAKING SURE THAT SETTINGS.YAML IS GOING TO BE FOUND! TEEKA_SETTINGS = os.getenv('TEEKA_SETTINGS', "../settings.yaml") # ADDING PARENT AND CURRENT DIRECTORIES INTO SYSTEM PATH CURREN_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(CURREN_DIR, os.pardir)) sys.path.append(CURREN_DIR) from server.setting_parser import SettingsParser class TestStringMethods(unittest.TestCase): def setUp(self): self.settings_file = TEEKA_SETTINGS self.settings_parser_instance = SettingsParser(self.settings_file) def tearDown(self): pass def test_port(self): self.assertIsInstance(self.settings_parser_instance.get_port(), int) self.assertLess(self.settings_parser_instance.get_port(), 65536) self.assertGreater(self.settings_parser_instance.get_port(), 0) def test_ip(self): self.assertTrue(validators.ipv4(self.settings_parser_instance.get_ip())) def test_data_path(self): self.assertTrue(os.path.exists(self.settings_parser_instance.get_data_path())) self.assertTrue(os.path.isdir(self.settings_parser_instance.get_data_path())) self.assertTrue(os.access(self.settings_parser_instance.get_data_path(), os.W_OK)) self.assertTrue(os.access(self.settings_parser_instance.get_data_path(), os.R_OK)) def test_meta_store_engine(self): meta_stores = ["sqlite3"] self.assertIsInstance(self.settings_parser_instance.get_meta_store_engine(), str) self.assertIn(self.settings_parser_instance.get_meta_store_engine(), meta_stores) def test_meta_store_name(self): self.assertIsInstance(self.settings_parser_instance.get_meta_store_name(), str) self.assertGreater(len(self.settings_parser_instance.get_meta_store_name()), 0) if __name__ == '__main__': unittest.main()
unknown
codeparrot/codeparrot-clean
/* * Copyright 2012-present the original author or authors. * * 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 * * https://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. */ package org.springframework.boot.build.springframework; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.gradle.api.DefaultTask; import org.gradle.api.Task; import org.gradle.api.file.DirectoryProperty; import org.gradle.api.file.FileCollection; import org.gradle.api.file.FileTree; import org.gradle.api.tasks.Classpath; import org.gradle.api.tasks.InputFiles; import org.gradle.api.tasks.OutputDirectory; import org.gradle.api.tasks.PathSensitive; import org.gradle.api.tasks.PathSensitivity; import org.gradle.api.tasks.SkipWhenEmpty; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.VerificationException; import org.gradle.language.base.plugins.LifecycleBasePlugin; import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.util.StringUtils; /** * {@link Task} that checks files loaded by {@link SpringFactoriesLoader}. * * @author Andy Wilkinson */ public abstract class CheckFactoriesFile extends DefaultTask { private final String path; private FileCollection sourceFiles = getProject().getObjects().fileCollection(); private FileCollection classpath = getProject().getObjects().fileCollection(); protected CheckFactoriesFile(String path) { this.path = path; getOutputDirectory().convention(getProject().getLayout().getBuildDirectory().dir(getName())); setGroup(LifecycleBasePlugin.VERIFICATION_GROUP); } @InputFiles @SkipWhenEmpty @PathSensitive(PathSensitivity.RELATIVE) public FileTree getSource() { return this.sourceFiles.getAsFileTree().matching((filter) -> filter.include(this.path)); } public void setSource(Object source) { this.sourceFiles = getProject().getObjects().fileCollection().from(source); } @Classpath public FileCollection getClasspath() { return this.classpath; } public void setClasspath(Object classpath) { this.classpath = getProject().getObjects().fileCollection().from(classpath); } @OutputDirectory public abstract DirectoryProperty getOutputDirectory(); @TaskAction void execute() { getSource().forEach(this::check); } private void check(File factoriesFile) { Properties properties = load(factoriesFile); Map<String, List<String>> problems = new LinkedHashMap<>(); for (String name : properties.stringPropertyNames()) { String value = properties.getProperty(name); List<String> classNames = Arrays.asList(StringUtils.commaDelimitedListToStringArray(value)); collectProblems(problems, name, classNames); List<String> sortedValues = new ArrayList<>(classNames); Collections.sort(sortedValues); if (!sortedValues.equals(classNames)) { List<String> problemsForClassName = problems.computeIfAbsent(name, (k) -> new ArrayList<>()); problemsForClassName.add("Entries should be sorted alphabetically"); } } File outputFile = getOutputDirectory().file("failure-report.txt").get().getAsFile(); writeReport(factoriesFile, problems, outputFile); if (!problems.isEmpty()) { throw new VerificationException("%s check failed. See '%s' for details".formatted(this.path, outputFile)); } } private void collectProblems(Map<String, List<String>> problems, String key, List<String> classNames) { for (String className : classNames) { if (!find(className)) { addNoFoundProblem(className, problems.computeIfAbsent(key, (k) -> new ArrayList<>())); } } } private void addNoFoundProblem(String className, List<String> problemsForClassName) { String binaryName = binaryNameOf(className); boolean foundBinaryForm = find(binaryName); problemsForClassName.add(!foundBinaryForm ? "'%s' was not found".formatted(className) : "'%s' should be listed using its binary name '%s'".formatted(className, binaryName)); } private boolean find(String className) { for (File root : this.classpath.getFiles()) { String classFilePath = className.replace(".", "/") + ".class"; if (new File(root, classFilePath).isFile()) { return true; } } return false; } private String binaryNameOf(String className) { int lastDotIndex = className.lastIndexOf('.'); return className.substring(0, lastDotIndex) + "$" + className.substring(lastDotIndex + 1); } private Properties load(File aotFactories) { Properties properties = new Properties(); try (FileInputStream input = new FileInputStream(aotFactories)) { properties.load(input); return properties; } catch (IOException ex) { throw new UncheckedIOException(ex); } } private void writeReport(File factoriesFile, Map<String, List<String>> problems, File outputFile) { outputFile.getParentFile().mkdirs(); StringBuilder report = new StringBuilder(); if (!problems.isEmpty()) { report.append("Found problems in '%s':%n".formatted(factoriesFile)); problems.forEach((key, problemsForKey) -> { report.append(" - %s:%n".formatted(key)); problemsForKey.forEach((problem) -> report.append(" - %s%n".formatted(problem))); }); } try { Files.writeString(outputFile.toPath(), report.toString(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException ex) { throw new UncheckedIOException(ex); } } }
java
github
https://github.com/spring-projects/spring-boot
buildSrc/src/main/java/org/springframework/boot/build/springframework/CheckFactoriesFile.java
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of FLOSS Talks. # # FLOSS Talks 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. # # FLOSS Talks 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 FLOSS Talks. If not, see <http://www.gnu.org/licenses/>. from flosstalks_app.models import Series, SeriesFeedURL, Project, \ Resource, ResourceDownloadURL from django.contrib import admin from django.conf.urls import patterns from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.http import HttpResponseRedirect from django.utils.http import urlquote from django import forms from django.forms.formsets import formset_factory # Series-related admin class SeriesFeedURLInline(admin.TabularInline): model = SeriesFeedURL extra = 2 class SeriesAdmin(admin.ModelAdmin): inlines = [SeriesFeedURLInline] list_display = ("name", "number_of_resources") admin.site.register(Series, SeriesAdmin) # Project-related admin class DeduplicateProjectForm(forms.Form): name = forms.CharField(max_length=100) nice_url = forms.SlugField(max_length=100) class ProjectModelAdmin(admin.ModelAdmin): def get_urls(self): urls = super(ProjectModelAdmin, self).get_urls() my_urls = patterns('', (r'^deduplicate/(?P<project_id>\d+)/$', self.admin_site.admin_view(self.deduplicate_project)) ) return my_urls + urls def slugify(self, value): #TODO: copied from updateseries. This should be in a unique place # Returns a string that is safe to use as a nice url return urlquote(value[:99] # nice_url fields have max_length=100 .lower() .replace(" ", "-") .replace("/", "-") .replace("---", "-") .replace("--", "-")) def deduplicate_project(self, request, project_id): # Allows to split a project into multiple that are linked to the # same resources original_project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': # If the form has been submitted... # Get a formset bound to the POST data ProjectFormSet = formset_factory(DeduplicateProjectForm) formset = ProjectFormSet(request.POST) if formset.is_valid(): # All validation rules pass, retrieve the list of resources # that were linked to the original project resources = original_project.resource_set.all() success = False # Process the data in formset.cleaned_data for cleaned_data in formset.cleaned_data: if cleaned_data: project_name = cleaned_data["name"].strip() try: # Check if it's an already-known project p = Project.objects.get(name=project_name) if "VF" == p.status: # If the project was already verified, # bump it back to Pending p.status = "PD" p.save() except Project.DoesNotExist: # Create a new project p = Project(name=project_name, description=u"Empty description", status="NW") # Check if the nice url is not already in use nu = cleaned_data["nice_url"].strip() if 0 == Project.objects.filter(nice_url=nu).count() and \ 0 == Series.objects.filter(nice_url=nu).count(): p.nice_url = nu # Save the newly created project p.save() # Link the [new] project to all the resources of # the original project for r in resources: r.projects.add(p) success = True else: # An empty string, nothing to do pass if success: # Delete the original project if at least one new # project got created original_project.delete() # Redirect after POST return HttpResponseRedirect("/admin/flosstalks_app/project/deduplicate/%d/" % (int(project_id) + 1)) else: # This is a GET # Try to split the names of the projects new_projects_names = [original_project.name] if ", " in original_project.name: # Split the project names on ", " new_projects_names = original_project.name.split(", ") if " and " in new_projects_names[-1]: # Split the last 2 project names on " and " new_projects_names.extend(new_projects_names[-1].split(" and ")) # Remove the one containing " and " since it's now split new_projects_names.pop(-3) new_projects = [] for p in new_projects_names: new_projects.append({"name": p.strip(), "nice_url": self.slugify(p.strip())}) ProjectFormSet = formset_factory(DeduplicateProjectForm, extra=3) formset = ProjectFormSet(initial=new_projects) return render_to_response( "admin/projects/deduplicate.html", { "original_project" : original_project, "formset": formset, }, RequestContext(request, {}), ) class ProjectAdmin(ProjectModelAdmin): list_display = ("name", "status", "number_of_resources") list_filter = ["status", "skip_ohloh"] search_fields = ["name", "description"] admin.site.register(Project, ProjectAdmin) # Resource-related admin class ResourceDownloadURLInline(admin.TabularInline): model = ResourceDownloadURL extra = 1 class ResourceAdmin(admin.ModelAdmin): inlines = [ResourceDownloadURLInline] list_display = ("name", "list_of_projects", "series") list_filter = ["pub_date"] search_fields = ["name", "description"] date_hierarchy = "pub_date" admin.site.register(Resource, ResourceAdmin)
unknown
codeparrot/codeparrot-clean
// Copyright 2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package mime import ( "internal/asan" "slices" "strings" "sync" "testing" ) func setMimeInit(fn func()) (cleanup func()) { once = sync.Once{} testInitMime = fn return func() { testInitMime = nil once = sync.Once{} } } func clearMimeTypes() { setMimeTypes(map[string]string{}, map[string]string{}) } func setType(ext, typ string) { if !strings.HasPrefix(ext, ".") { panic("missing leading dot") } if err := setExtensionType(ext, typ); err != nil { panic("bad test data: " + err.Error()) } } func TestTypeByExtension(t *testing.T) { once = sync.Once{} // initMimeForTests returns the platform-specific extension => // type tests. On Unix and Plan 9, this also tests the parsing // of MIME text files (in testdata/*). On Windows, we test the // real registry on the machine and assume that ".png" exists // there, which empirically it always has, for all versions of // Windows. typeTests := initMimeForTests() for ext, want := range typeTests { val := TypeByExtension(ext) if val != want { t.Errorf("TypeByExtension(%q) = %q, want %q", ext, val, want) } } } func TestTypeByExtension_LocalData(t *testing.T) { cleanup := setMimeInit(func() { clearMimeTypes() setType(".foo", "x/foo") setType(".bar", "x/bar") setType(".Bar", "x/bar; capital=1") }) defer cleanup() tests := map[string]string{ ".foo": "x/foo", ".bar": "x/bar", ".Bar": "x/bar; capital=1", ".sdlkfjskdlfj": "", ".t1": "", // testdata shouldn't be used } for ext, want := range tests { val := TypeByExtension(ext) if val != want { t.Errorf("TypeByExtension(%q) = %q, want %q", ext, val, want) } } } func TestTypeByExtensionCase(t *testing.T) { const custom = "test/test; charset=iso-8859-1" const caps = "test/test; WAS=ALLCAPS" cleanup := setMimeInit(func() { clearMimeTypes() setType(".TEST", caps) setType(".tesT", custom) }) defer cleanup() // case-sensitive lookup if got := TypeByExtension(".tesT"); got != custom { t.Fatalf("for .tesT, got %q; want %q", got, custom) } if got := TypeByExtension(".TEST"); got != caps { t.Fatalf("for .TEST, got %q; want %s", got, caps) } // case-insensitive if got := TypeByExtension(".TesT"); got != custom { t.Fatalf("for .TesT, got %q; want %q", got, custom) } } func TestExtensionsByType(t *testing.T) { cleanup := setMimeInit(func() { clearMimeTypes() setType(".gif", "image/gif") setType(".a", "foo/letter") setType(".b", "foo/letter") setType(".B", "foo/letter") setType(".PNG", "image/png") }) defer cleanup() tests := []struct { typ string want []string wantErr string }{ {typ: "image/gif", want: []string{".gif"}}, {typ: "image/png", want: []string{".png"}}, // lowercase {typ: "foo/letter", want: []string{".a", ".b"}}, {typ: "x/unknown", want: nil}, } for _, tt := range tests { got, err := ExtensionsByType(tt.typ) if err != nil && tt.wantErr != "" && strings.Contains(err.Error(), tt.wantErr) { continue } if err != nil { t.Errorf("ExtensionsByType(%q) error: %v", tt.typ, err) continue } if tt.wantErr != "" { t.Errorf("ExtensionsByType(%q) = %q, %v; want error substring %q", tt.typ, got, err, tt.wantErr) continue } if !slices.Equal(got, tt.want) { t.Errorf("ExtensionsByType(%q) = %q; want %q", tt.typ, got, tt.want) } } } func TestLookupMallocs(t *testing.T) { if asan.Enabled { t.Skip("test allocates more with -asan; see #70079") } n := testing.AllocsPerRun(10000, func() { TypeByExtension(".html") TypeByExtension(".HtML") }) if n > 0 { t.Errorf("allocs = %v; want 0", n) } } func BenchmarkTypeByExtension(b *testing.B) { initMime() b.ResetTimer() for _, ext := range []string{ ".html", ".HTML", ".unused", } { b.Run(ext, func(b *testing.B) { b.RunParallel(func(pb *testing.PB) { for pb.Next() { TypeByExtension(ext) } }) }) } } func BenchmarkExtensionsByType(b *testing.B) { initMime() b.ResetTimer() for _, typ := range []string{ "text/html", "text/html; charset=utf-8", "application/octet-stream", } { b.Run(typ, func(b *testing.B) { b.RunParallel(func(pb *testing.PB) { for pb.Next() { if _, err := ExtensionsByType(typ); err != nil { b.Fatal(err) } } }) }) } } func TestExtensionsByType2(t *testing.T) { cleanup := setMimeInit(func() { clearMimeTypes() // Initialize built-in types like in type.go before osInitMime. setMimeTypes(builtinTypesLower, builtinTypesLower) }) defer cleanup() tests := []struct { typ string want []string }{ {typ: "application/postscript", want: []string{".ai", ".eps", ".ps"}}, {typ: "application/vnd.android.package-archive", want: []string{".apk"}}, {typ: "image/apng", want: []string{".apng"}}, {typ: "image/avif", want: []string{".avif"}}, {typ: "application/octet-stream", want: []string{".bin", ".com", ".exe"}}, {typ: "image/bmp", want: []string{".bmp"}}, {typ: "text/css; charset=utf-8", want: []string{".css"}}, {typ: "text/csv; charset=utf-8", want: []string{".csv"}}, {typ: "application/msword", want: []string{".doc"}}, {typ: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", want: []string{".docx"}}, {typ: "text/html; charset=utf-8", want: []string{".ehtml", ".htm", ".html", ".shtml"}}, {typ: "message/rfc822", want: []string{".eml"}}, {typ: "audio/flac", want: []string{".flac"}}, {typ: "image/gif", want: []string{".gif"}}, {typ: "application/gzip", want: []string{".gz"}}, {typ: "image/vnd.microsoft.icon", want: []string{".ico"}}, {typ: "text/calendar; charset=utf-8", want: []string{".ics"}}, {typ: "image/jpeg", want: []string{".jfif", ".jpeg", ".jpg", ".pjp", ".pjpeg"}}, {typ: "text/javascript; charset=utf-8", want: []string{".js", ".mjs"}}, {typ: "application/json", want: []string{".json"}}, {typ: "audio/mp4", want: []string{".m4a"}}, {typ: "audio/mpeg", want: []string{".mp3"}}, {typ: "video/mp4", want: []string{".mp4"}}, {typ: "audio/ogg", want: []string{".oga", ".ogg", ".opus"}}, {typ: "video/ogg", want: []string{".ogv"}}, {typ: "application/pdf", want: []string{".pdf"}}, {typ: "image/png", want: []string{".png"}}, {typ: "application/vnd.ms-powerpoint", want: []string{".ppt"}}, {typ: "application/vnd.openxmlformats-officedocument.presentationml.presentation", want: []string{".pptx"}}, {typ: "application/rdf+xml", want: []string{".rdf"}}, {typ: "application/rtf", want: []string{".rtf"}}, {typ: "image/svg+xml", want: []string{".svg"}}, {typ: "text/plain; charset=utf-8", want: []string{".text", ".txt"}}, {typ: "image/tiff", want: []string{".tif", ".tiff"}}, {typ: "text/vtt; charset=utf-8", want: []string{".vtt"}}, {typ: "application/wasm", want: []string{".wasm"}}, {typ: "audio/wav", want: []string{".wav"}}, {typ: "audio/webm", want: []string{".webm"}}, {typ: "image/webp", want: []string{".webp"}}, {typ: "text/xml; charset=utf-8", want: []string{".xbl", ".xml", ".xsl"}}, {typ: "image/x-xbitmap", want: []string{".xbm"}}, {typ: "application/xhtml+xml", want: []string{".xht", ".xhtml"}}, {typ: "application/vnd.ms-excel", want: []string{".xls"}}, {typ: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", want: []string{".xlsx"}}, {typ: "application/zip", want: []string{".zip"}}, } for _, tt := range tests { got, err := ExtensionsByType(tt.typ) if err != nil { t.Errorf("ExtensionsByType(%q): %v", tt.typ, err) continue } if !slices.Equal(got, tt.want) { t.Errorf("ExtensionsByType(%q) = %q; want %q", tt.typ, got, tt.want) } } }
go
github
https://github.com/golang/go
src/mime/type_test.go
// RUN: clang-include-cleaner --print=changes %s -- -I %S/Inputs | FileCheck --allow-empty %s #include "foo.h" #include "foo2.h" int n = foo(); // Make sure both providers are preserved. // CHECK-NOT: - "foo.h" // CHECK-NOT: - "foo2.h"
cpp
github
https://github.com/llvm/llvm-project
clang-tools-extra/include-cleaner/test/multiple-providers.cpp
import unittest from django.utils.termcolors import ( DARK_PALETTE, DEFAULT_PALETTE, LIGHT_PALETTE, NOCOLOR_PALETTE, PALETTES, colorize, parse_color_setting, ) class TermColorTests(unittest.TestCase): def test_empty_string(self): self.assertEqual(parse_color_setting(""), PALETTES[DEFAULT_PALETTE]) def test_simple_palette(self): self.assertEqual(parse_color_setting("light"), PALETTES[LIGHT_PALETTE]) self.assertEqual(parse_color_setting("dark"), PALETTES[DARK_PALETTE]) self.assertIsNone(parse_color_setting("nocolor")) def test_fg(self): self.assertEqual( parse_color_setting("error=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) def test_fg_bg(self): self.assertEqual( parse_color_setting("error=green/blue"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) def test_fg_opts(self): self.assertEqual( parse_color_setting("error=green,blink"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) self.assertEqual( parse_color_setting("error=green,bold,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink", "bold")}, ), ) def test_fg_bg_opts(self): self.assertEqual( parse_color_setting("error=green/blue,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue", "opts": ("blink",)}, ), ) self.assertEqual( parse_color_setting("error=green/blue,bold,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue", "opts": ("blink", "bold")}, ), ) def test_override_palette(self): self.assertEqual( parse_color_setting("light;error=green"), dict(PALETTES[LIGHT_PALETTE], ERROR={"fg": "green"}), ) def test_override_nocolor(self): self.assertEqual( parse_color_setting("nocolor;error=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) def test_reverse_override(self): self.assertEqual( parse_color_setting("error=green;light"), PALETTES[LIGHT_PALETTE] ) def test_multiple_roles(self): self.assertEqual( parse_color_setting("error=green;sql_field=blue"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}, SQL_FIELD={"fg": "blue"}, ), ) def test_override_with_multiple_roles(self): self.assertEqual( parse_color_setting("light;error=green;sql_field=blue"), dict( PALETTES[LIGHT_PALETTE], ERROR={"fg": "green"}, SQL_FIELD={"fg": "blue"} ), ) def test_empty_definition(self): self.assertIsNone(parse_color_setting(";")) self.assertEqual(parse_color_setting("light;"), PALETTES[LIGHT_PALETTE]) self.assertIsNone(parse_color_setting(";;;")) def test_empty_options(self): self.assertEqual( parse_color_setting("error=green,"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green,,,"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green,,blink,,"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) def test_bad_palette(self): self.assertIsNone(parse_color_setting("unknown")) def test_bad_role(self): self.assertIsNone(parse_color_setting("unknown=")) self.assertIsNone(parse_color_setting("unknown=green")) self.assertEqual( parse_color_setting("unknown=green;sql_field=blue"), dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={"fg": "blue"}), ) def test_bad_color(self): self.assertIsNone(parse_color_setting("error=")) self.assertEqual( parse_color_setting("error=;sql_field=blue"), dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={"fg": "blue"}), ) self.assertIsNone(parse_color_setting("error=unknown")) self.assertEqual( parse_color_setting("error=unknown;sql_field=blue"), dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={"fg": "blue"}), ) self.assertEqual( parse_color_setting("error=green/unknown"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green/blue/something"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) self.assertEqual( parse_color_setting("error=green/blue/something,blink"), dict( PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue", "opts": ("blink",)}, ), ) def test_bad_option(self): self.assertEqual( parse_color_setting("error=green,unknown"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=green,unknown,blink"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) def test_role_case(self): self.assertEqual( parse_color_setting("ERROR=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("eRrOr=green"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) def test_color_case(self): self.assertEqual( parse_color_setting("error=GREEN"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=GREEN/BLUE"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) self.assertEqual( parse_color_setting("error=gReEn"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green"}), ) self.assertEqual( parse_color_setting("error=gReEn/bLuE"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "bg": "blue"}), ) def test_opts_case(self): self.assertEqual( parse_color_setting("error=green,BLINK"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) self.assertEqual( parse_color_setting("error=green,bLiNk"), dict(PALETTES[NOCOLOR_PALETTE], ERROR={"fg": "green", "opts": ("blink",)}), ) def test_colorize_empty_text(self): self.assertEqual(colorize(text=None), "\x1b[m\x1b[0m") self.assertEqual(colorize(text=""), "\x1b[m\x1b[0m") self.assertEqual(colorize(text=None, opts=("noreset",)), "\x1b[m") self.assertEqual(colorize(text="", opts=("noreset",)), "\x1b[m") def test_colorize_reset(self): self.assertEqual(colorize(text="", opts=("reset",)), "\x1b[0m") def test_colorize_fg_bg(self): self.assertEqual(colorize(text="Test", fg="red"), "\x1b[31mTest\x1b[0m") self.assertEqual(colorize(text="Test", bg="red"), "\x1b[41mTest\x1b[0m") # Ignored kwarg. self.assertEqual(colorize(text="Test", other="red"), "\x1b[mTest\x1b[0m") def test_colorize_opts(self): self.assertEqual( colorize(text="Test", opts=("bold", "underscore")), "\x1b[1;4mTest\x1b[0m", ) self.assertEqual( colorize(text="Test", opts=("blink",)), "\x1b[5mTest\x1b[0m", ) # Ignored opts. self.assertEqual( colorize(text="Test", opts=("not_an_option",)), "\x1b[mTest\x1b[0m", )
python
github
https://github.com/django/django
tests/utils_tests/test_termcolors.py
""" Tests of errors that are common across a wide group of pywbemcli groups and commands. This includes: 1. Tests of connection timeout on bad server with all commands. Note that the command options in these tests are just sufficient to pass command parsing since all tests should fail with connection error. 2. Test of the --namespace option with namespace that is not in the target wbem server. """ from __future__ import absolute_import, print_function import os import pytest from .cli_test_extensions import CLITestsBase SCRIPT_DIR = os.path.dirname(__file__) SIMPLE_MOCK_FILE = 'simple_mock_model.mof' SIMPLE_MOCK_FILE_PATH = os.path.join(SCRIPT_DIR, SIMPLE_MOCK_FILE) OK = True RUN = True FAIL = False SKIP = False TEST_CASES_CONNECTION_FAIL = [ # desc - Description of test # group - String, defining test group to be executed. # cmd - string/required arguments defining the command string # condition - If True, the test is executed, Otherwise it is skipped. ['class', 'enumerate', OK], ['class', 'get CIM_BLAH', OK], ['class', 'delete CIM_BLAH', OK], ['class', 'associators CIM_BLAH', OK], ['class', 'references CIM_BLAH', OK], ['class', 'invokemethod CIM_BLAH methodx', OK], ['class', 'find CIM_*', OK], ['instance', 'enumerate CIM_Blah', OK], ['instance', 'get CIM_BLAH.x=3', OK], ['instance', 'create CIM_blah -p x=3', OK], ['instance', 'modify CIM_blah.x=3 -p x=4', OK], ['instance', 'delete CIM_BLAH.x=3', OK], ['instance', 'associators CIM_BLAH.x=3', OK], ['instance', 'references CIM_BLAH.x=4', OK], ['instance', 'invokemethod CIM_BLAH.x=4 methodx', OK], ['instance', 'query select', FAIL], ['instance', 'count CIM_*', OK], ['connection', 'test', OK], # The other connection commands do not connect to a server ['qualifier', 'get qualblah', OK], ['qualifier', 'enumerate', OK], ['server', 'namespaces', OK], ['server', 'interop', OK], ['server', 'brand', OK], ['server', 'info', OK], ['profile', 'list', OK], ['profile', 'centralinsts', OK], ] class TestConnectionFail(CLITestsBase): """ Test of the return for a connection error. """ @pytest.mark.parametrize( "grp, cmd, condition", TEST_CASES_CONNECTION_FAIL) def test_execute_pywbemcli(self, grp, cmd, condition): """ Execute pybemcli with the defined input and test output. This tests builds the inputs dictionary nad exp_response dictionary from the cmd line inputs. """ desc = "Verify {} args {} fails with connection error".format(grp, cmd) # Build inputs dictionary for the test with bad svr name and cmd/args inputs = {'general': ['--server', 'http://blahblah', '--timeout', '1'], 'args': cmd.split(' ')} # Build expected response dictionary that tests for ConnectionError exp_response = {'stderr': ['ConnectionError'], 'rc': 1, 'test': 'innows'} mock = None self.command_test(desc, grp, inputs, exp_response, mock, condition) TEST_CASES_NAMESPACE_ERR = [ # desc - Description of test # group - String, defining test group to be executed. # cmd - string/required arguments defining the command string # condition - If True, the test is executed, Otherwise it is skipped. ['class', 'enumerate --namespace blah', OK], ['class', 'get CIM_Foo --namespace blah', OK], ['class', 'delete CIM_Foo --namespace blah', OK], ['class', 'associators CIM_Foo --namespace blah', OK], ['class', 'references CIM_Foo --namespace blah', OK], ['class', 'invokemethod CIM_Foo methodx --namespace blah', OK], ['class', 'find CIM_* --namespace blah', OK], ['instance', 'enumerate CIM_Foo --namespace blah', OK], ['instance', 'get CIM_Foo.x=3 --namespace blah', OK], ['instance', 'create CIM_Foo -p x=3 --namespace blah', OK], ['instance', 'modify CIM_Foo.x=3 -p x=4 --namespace blah', OK], ['instance', 'delete CIM_Foo.x=3 --namespace blah', OK], ['instance', 'associators CIM_Foo.x=3 --namespace blah', OK], ['instance', 'references CIM_Foo.x=4 --namespace blah', OK], ['instance', 'invokemethod CIM_Foo.x=4 methodx --namespace blah', OK], # pywbem issue # 2313 - Fails with QueryLanguage, not namespace error # ['instance', 'query select --namespace blah', OK], ['instance', 'count CIM_* --namespace blah', OK], ['qualifier', 'get qualblah --namespace blah', OK], ['qualifier', 'enumerate --namespace blah', OK], ] class TestNamespaceError(CLITestsBase): """ Test of the return for a connection error. """ @pytest.mark.parametrize( "grp, cmd, condition", TEST_CASES_NAMESPACE_ERR) def test_execute_pywbemcli(self, grp, cmd, condition): """ Execute pybemcli with the defined input and test output. This tests builds the inputs dictionary nad exp_response dictionary from the cmd line inputs. """ desc = "Verify {} args {} fails with namespace error".format(grp, cmd) # Build inputs dictionary for the test with bad svr name and cmd/args inputs = {'args': cmd.split(' ')} # Build expected response dictionary that tests for ConnectionError exp_response = {'stderr': ['CIMError', 'CIM_ERR_INVALID_NAMESPACE'], 'rc': 1, 'test': 'innows'} mock = SIMPLE_MOCK_FILE_PATH self.command_test(desc, grp, inputs, exp_response, mock, condition)
unknown
codeparrot/codeparrot-clean
from __future__ import (absolute_import, division, print_function, unicode_literals) from .scale import scale from copy import deepcopy import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap, rgb2hex, ColorConverter def colors_at_breaks(cmap, breaks=[0, 0.25, 0.5, 0.75, 1.]): return [rgb2hex(cmap(bb)[:3]) for bb in breaks] class scale_colour_gradient(scale): VALID_SCALES = ['name', 'limits', 'low', 'mid', 'high'] def __radd__(self, gg): gg = deepcopy(gg) if self.name: gg.color_label = self.name if self.limits: gg.color_limits = self.limits color_spectrum = [] if self.low: color_spectrum.append(self.low) if self.mid: color_spectrum.append(self.mid) if self.high: color_spectrum.append(self.high) if self.low and self.high: gradient2n = LinearSegmentedColormap.from_list('gradient2n', color_spectrum) plt.cm.register_cmap(cmap=gradient2n) # add them back to ggplot gg.color_scale = colors_at_breaks(gradient2n) gg.colormap = gradient2n return gg
unknown
codeparrot/codeparrot-clean
#!/usr/bin/python # Copyright (c) 2009 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. """Compiler version checking tool for gcc Print gcc version as XY if you are running gcc X.Y.*. This is used to tweak build flags for gcc 4.4. """ import os import re import subprocess import sys def GetVersion(compiler): try: # Note that compiler could be something tricky like "distcc g++". compiler = compiler + " -dumpversion" pipe = subprocess.Popen(compiler, stdout=subprocess.PIPE, shell=True) gcc_output = pipe.communicate()[0] result = re.match(r"(\d+)\.(\d+)", gcc_output) return result.group(1) + result.group(2) except Exception, e: print >> sys.stderr, "compiler_version.py failed to execute:", compiler print >> sys.stderr, e return "" def main(): # Check if CXX environment variable exists and # if it does use that compiler. cxx = os.getenv("CXX", None) if cxx: cxxversion = GetVersion(cxx) if cxxversion != "": print cxxversion return 0 else: # Otherwise we check the g++ version. gccversion = GetVersion("g++") if gccversion != "": print gccversion return 0 return 1 if __name__ == "__main__": sys.exit(main())
unknown
codeparrot/codeparrot-clean
--- layout: step title: Setup menu_name: Step by Step Tutorial position: 1 redirect_from: - /docs/step-by-step/ --- Welcome to Jekyll's step-by-step tutorial. This tutorial takes you from having some front-end web development experience to building your first Jekyll site from scratch without relying on the default gem-based theme. ## Installation Jekyll is a Ruby gem. First, install Ruby on your machine. Go to [Installation]({{ '/docs/installation/' | relative_url }}) and follow the instructions for your operating system. With Ruby installed, install Jekyll from the terminal: ```sh gem install jekyll bundler ``` Create a new `Gemfile` to list your project's dependencies: ```sh bundle init ``` Edit the `Gemfile` in a text editor and add jekyll as a dependency: ```ruby gem "jekyll" ``` Run `bundle` to install jekyll for your project. You can now prefix all jekyll commands listed in this tutorial with `bundle exec` to make sure you use the jekyll version defined in your `Gemfile`. ## Create a site It's time to create a site! Create a new directory for your site and name it whatever you want. Through the rest of this tutorial we'll refer to this directory as **root**. You can also initialize a Git repository here. One of the great things about Jekyll is there's no database. All content and site structure are files that a Git repository can version. Using a repository is optional but is recommended. You can learn more about using Git by reading the [Git Handbook](https://guides.github.com/introduction/git-handbook/). Let's add your first file. Create `index.html` in **root** with the following content: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Home</title> </head> <body> <h1>Hello World!</h1> </body> </html> ``` ## Build Since Jekyll is a static site generator, it has to build the site before we can view it. Run either of the following commands to build your site: * `jekyll build` - Builds the site and outputs a static site to a directory called `_site`. * `jekyll serve` - Does `jekyll build` and runs it on a local web server at `http://localhost:4000`, rebuilding the site any time you make a change. {: .note .info} When you're developing a site, use `jekyll serve`. To force the browser to refresh with every change, use `jekyll serve --livereload`. If there's a conflict or you'd like Jekyll to serve your development site at a different URL, use the `--host` and `--port` arguments, as described in the [serve command options]({{ '/docs/configuration/options/#serve-command-options' | relative_url }}). {: .note .warning} The version of the site that `jekyll serve` builds in `_site` is not suited for deployment. Links and asset URLs in sites created with `jekyll serve` will use `https://localhost:4000` or the value set with command-line configuration, instead of the values set in [your site's configuration file]({{ '/docs/configuration/' | relative_url }}). To learn about how to build your site when it's ready for deployment, read the [Deployment]({{ '/docs/step-by-step/10-deployment/' | relative_url }}) section of this tutorial. Run `jekyll serve` and go to <a href="http://localhost:4000" target="_blank" data-proofer-ignore>http://localhost:4000</a> in your browser. You should see "Hello World!". At this point, you might be thinking, "So what?". The only thing that happened was that Jekyll copied an HTML file from one place to another. Patience, young grasshopper, there's still much to learn! Next. you'll learn about Liquid and templating.
unknown
github
https://github.com/jekyll/jekyll
docs/_docs/step-by-step/01-setup.md
/* * Copyright 2012-present the original author or authors. * * 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 * * https://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. */ package org.springframework.boot.configurationsample.generic; import java.util.HashMap; import java.util.Map; /** * A pojo with a complex generic signature. * * @param <T> the generic type * @author Stephane Nicoll */ public class UpperBoundGenericPojo<T extends Enum<T>> { private final Map<T, String> mappings = new HashMap<>(); public Map<T, String> getMappings() { return this.mappings; } }
java
github
https://github.com/spring-projects/spring-boot
configuration-metadata/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/generic/UpperBoundGenericPojo.java
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import time import FacebookService import thrift.reflection.limited from ttypes import fb_status class FacebookBase(FacebookService.Iface): def __init__(self, name): self.name = name self.alive = int(time.time()) self.counters = {} def getName(self, ): return self.name def getVersion(self, ): return '' def getStatus(self, ): return fb_status.ALIVE def getCounters(self): return self.counters def resetCounter(self, key): self.counters[key] = 0 def getCounter(self, key): if self.counters.has_key(key): return self.counters[key] return 0 def incrementCounter(self, key): self.counters[key] = self.getCounter(key) + 1 def setOption(self, key, value): pass def getOption(self, key): return "" def getOptions(self): return {} def getOptions(self): return {} def aliveSince(self): return self.alive def getCpuProfile(self, duration): return "" def getLimitedReflection(self): return thrift.reflection.limited.Service() def reinitialize(self): pass def shutdown(self): pass
unknown
codeparrot/codeparrot-clean
<?php namespace Illuminate\Database\Schema; use Illuminate\Support\Stringable; class ForeignIdColumnDefinition extends ColumnDefinition { /** * The schema builder blueprint instance. * * @var \Illuminate\Database\Schema\Blueprint */ protected $blueprint; /** * Create a new foreign ID column definition. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param array $attributes */ public function __construct(Blueprint $blueprint, $attributes = []) { parent::__construct($attributes); $this->blueprint = $blueprint; } /** * Create a foreign key constraint on this column referencing the "id" column of the conventionally related table. * * @param string|null $table * @param string|null $column * @param string|null $indexName * @return \Illuminate\Database\Schema\ForeignKeyDefinition */ public function constrained($table = null, $column = null, $indexName = null) { $table ??= $this->table; $column ??= $this->referencesModelColumn ?? 'id'; return $this->references($column, $indexName)->on($table ?? (new Stringable($this->name))->beforeLast('_'.$column)->plural()); } /** * Specify which column this foreign ID references on another table. * * @param string $column * @param string|null $indexName * @return \Illuminate\Database\Schema\ForeignKeyDefinition */ public function references($column, $indexName = null) { return $this->blueprint->foreign($this->name, $indexName)->references($column); } }
php
github
https://github.com/laravel/framework
src/Illuminate/Database/Schema/ForeignIdColumnDefinition.php
""" Goal: Store the rules by which we pick the elements of patient data before computing the hashed string. Authors: Andrei Sura <sura.andrei@gmail.com> """ # TODO: research the claim from # L. Sweeney. k-anonymity: a model for protecting privacy. # International Journal on Uncertainty, Fuzziness and Knowledge-based Systems # # "...87% (216 million of 248 million) of the population in the # United States had reported characteristics that likely made them # unique based only on {5-digit ZIP, sex, date of birth}." from onefl import utils # noqa from onefl.normalized_patient import NormalizedPatient # noqa # Last Name + First Name + DOB + Race RULE_CODE_F_L_D_R = 'F_L_D_R' # First Name + Last Name + DOB + Sex RULE_CODE_F_L_D_S = 'F_L_D_S' # For patients without hashes RULE_CODE_NO_HASH = 'NO_HASH' # In order to guarantee correctness we will allow the partners # to add to the configuration only values from the map below. # If we add new rules then we will ask the partners to download a new version # of the client software. AVAILABLE_RULES_MAP = { RULE_CODE_F_L_D_S: { 'required_attr': ['pat_first_name', 'pat_last_name', 'pat_birth_date', 'pat_sex'], # NOQA 'pattern': '{0.pat_first_name}{0.pat_last_name}{0.pat_birth_date}{0.pat_sex}', # NOQA }, RULE_CODE_F_L_D_R: { 'required_attr': ['pat_first_name', 'pat_last_name', 'pat_birth_date', 'pat_race'], # NOQA 'pattern': '{0.pat_last_name}{0.pat_first_name}{0.pat_birth_date}{0.pat_race}', # NOQA }, }
unknown
codeparrot/codeparrot-clean
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\FrameworkBundle\Controller; use Psr\Container\ContainerInterface; use Psr\Link\EvolvableLinkInterface; use Psr\Link\LinkInterface; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface; use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\Flow\FormFlowBuilderInterface; use Symfony\Component\Form\Flow\FormFlowInterface; use Symfony\Component\Form\Flow\FormFlowTypeInterface; use Symfony\Component\Form\Flow\Type\FormFlowType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\Form\FormInterface; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\HttpFoundation\Session\FlashBagAwareSessionInterface; use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authorization\AccessDecision; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Csrf\CsrfToken; use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\WebLink\EventListener\AddLinkHeaderListener; use Symfony\Component\WebLink\GenericLinkProvider; use Symfony\Component\WebLink\HttpHeaderSerializer; use Symfony\Contracts\Service\ServiceSubscriberInterface; use Twig\Environment; /** * Provides the helpers from AbstractControler as a standalone service. * * Best used together with #[AutowireMethodOf] to remove any coupling. */ class ControllerHelper implements ServiceSubscriberInterface { public function __construct( private ContainerInterface $container, ) { } public static function getSubscribedServices(): array { return [ 'router' => '?'.RouterInterface::class, 'request_stack' => '?'.RequestStack::class, 'http_kernel' => '?'.HttpKernelInterface::class, 'serializer' => '?'.SerializerInterface::class, 'security.authorization_checker' => '?'.AuthorizationCheckerInterface::class, 'twig' => '?'.Environment::class, 'form.factory' => '?'.FormFactoryInterface::class, 'security.token_storage' => '?'.TokenStorageInterface::class, 'security.csrf.token_manager' => '?'.CsrfTokenManagerInterface::class, 'parameter_bag' => '?'.ContainerBagInterface::class, 'web_link.http_header_serializer' => '?'.HttpHeaderSerializer::class, ]; } /** * Gets a container parameter by its name. */ public function getParameter(string $name): array|bool|string|int|float|\UnitEnum|null { if (!$this->container->has('parameter_bag')) { throw new ServiceNotFoundException('parameter_bag.', null, null, [], \sprintf('The "%s::getParameter()" method is missing a parameter bag to work properly. Did you forget to register your controller as a service subscriber? This can be fixed either by using autoconfiguration or by manually wiring a "parameter_bag" in the service locator passed to the controller.', static::class)); } return $this->container->get('parameter_bag')->get($name); } /** * Generates a URL from the given parameters. * * @see UrlGeneratorInterface */ public function generateUrl(string $route, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string { return $this->container->get('router')->generate($route, $parameters, $referenceType); } /** * Forwards the request to another controller. * * @param string $controller The controller name (a string like "App\Controller\PostController::index" or "App\Controller\PostController" if it is invokable) */ public function forward(string $controller, array $path = [], array $query = []): Response { $request = $this->container->get('request_stack')->getCurrentRequest(); $path['_controller'] = $controller; $subRequest = $request->duplicate($query, null, $path); return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST); } /** * Returns a RedirectResponse to the given URL. * * @param int $status The HTTP status code (302 "Found" by default) */ public function redirect(string $url, int $status = 302): RedirectResponse { return new RedirectResponse($url, $status); } /** * Returns a RedirectResponse to the given route with the given parameters. * * @param int $status The HTTP status code (302 "Found" by default) */ public function redirectToRoute(string $route, array $parameters = [], int $status = 302): RedirectResponse { return $this->redirect($this->generateUrl($route, $parameters), $status); } /** * Returns a JsonResponse that uses the serializer component if enabled, or json_encode. * * @param int $status The HTTP status code (200 "OK" by default) */ public function json(mixed $data, int $status = 200, array $headers = [], array $context = []): JsonResponse { if ($this->container->has('serializer')) { $json = $this->container->get('serializer')->serialize($data, 'json', array_merge([ 'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS, ], $context)); return new JsonResponse($json, $status, $headers, true); } if (null === $data) { return new JsonResponse('null', $status, $headers, true); } return new JsonResponse($data, $status, $headers); } /** * Returns a BinaryFileResponse object with original or customized file name and disposition header. */ public function file(\SplFileInfo|string $file, ?string $fileName = null, string $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse { $response = new BinaryFileResponse($file); $response->setContentDisposition($disposition, $fileName ?? $response->getFile()->getFilename()); return $response; } /** * Adds a flash message to the current session for type. * * @throws \LogicException */ public function addFlash(string $type, mixed $message): void { try { $session = $this->container->get('request_stack')->getSession(); } catch (SessionNotFoundException $e) { throw new \LogicException('You cannot use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".', 0, $e); } if (!$session instanceof FlashBagAwareSessionInterface) { throw new \LogicException(\sprintf('You cannot use the addFlash method because class "%s" doesn\'t implement "%s".', get_debug_type($session), FlashBagAwareSessionInterface::class)); } $session->getFlashBag()->add($type, $message); } /** * Checks if the attribute is granted against the current authentication token and optionally supplied subject. * * @throws \LogicException */ public function isGranted(mixed $attribute, mixed $subject = null): bool { if (!$this->container->has('security.authorization_checker')) { throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".'); } return $this->container->get('security.authorization_checker')->isGranted($attribute, $subject); } /** * Checks if the attribute is granted against the current authentication token and optionally supplied subject. */ public function getAccessDecision(mixed $attribute, mixed $subject = null): AccessDecision { if (!$this->container->has('security.authorization_checker')) { throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".'); } $accessDecision = new AccessDecision(); $accessDecision->isGranted = $this->container->get('security.authorization_checker')->isGranted($attribute, $subject, $accessDecision); return $accessDecision; } /** * Throws an exception unless the attribute is granted against the current authentication token and optionally * supplied subject. * * @throws AccessDeniedException */ public function denyAccessUnlessGranted(mixed $attribute, mixed $subject = null, string $message = 'Access Denied.'): void { $accessDecision = $this->getAccessDecision($attribute, $subject); $isGranted = $accessDecision->isGranted; if (!$isGranted) { $e = $this->createAccessDeniedException(3 > \func_num_args() && $accessDecision ? $accessDecision->getMessage() : $message); $e->setAttributes([$attribute]); $e->setSubject($subject); if ($accessDecision) { $e->setAccessDecision($accessDecision); } throw $e; } } /** * Returns a rendered view. * * Forms found in parameters are auto-cast to form views. */ public function renderView(string $view, array $parameters = []): string { return $this->doRenderView($view, null, $parameters, __FUNCTION__); } /** * Returns a rendered block from a view. * * Forms found in parameters are auto-cast to form views. */ public function renderBlockView(string $view, string $block, array $parameters = []): string { return $this->doRenderView($view, $block, $parameters, __FUNCTION__); } /** * Renders a view. * * If an invalid form is found in the list of parameters, a 422 status code is returned. * Forms found in parameters are auto-cast to form views. */ public function render(string $view, array $parameters = [], ?Response $response = null): Response { return $this->doRender($view, null, $parameters, $response, __FUNCTION__); } /** * Renders a block in a view. * * If an invalid form is found in the list of parameters, a 422 status code is returned. * Forms found in parameters are auto-cast to form views. */ public function renderBlock(string $view, string $block, array $parameters = [], ?Response $response = null): Response { return $this->doRender($view, $block, $parameters, $response, __FUNCTION__); } /** * Streams a view. */ public function stream(string $view, array $parameters = [], ?StreamedResponse $response = null): StreamedResponse { if (!$this->container->has('twig')) { throw new \LogicException('You cannot use the "stream" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".'); } $twig = $this->container->get('twig'); $callback = static function () use ($twig, $view, $parameters) { $twig->display($view, $parameters); }; if (null === $response) { return new StreamedResponse($callback); } $response->setCallback($callback); return $response; } /** * Returns a NotFoundHttpException. * * This will result in a 404 response code. Usage example: * * throw $this->createNotFoundException('Page not found!'); */ public function createNotFoundException(string $message = 'Not Found', ?\Throwable $previous = null): NotFoundHttpException { return new NotFoundHttpException($message, $previous); } /** * Returns an AccessDeniedException. * * This will result in a 403 response code. Usage example: * * throw $this->createAccessDeniedException('Unable to access this page!'); * * @throws \LogicException If the Security component is not available */ public function createAccessDeniedException(string $message = 'Access Denied.', ?\Throwable $previous = null): AccessDeniedException { if (!class_exists(AccessDeniedException::class)) { throw new \LogicException('You cannot use the "createAccessDeniedException" method if the Security component is not available. Try running "composer require symfony/security-bundle".'); } return new AccessDeniedException($message, $previous); } /** * Creates and returns a Form instance from the type of the form. * * @return ($type is class-string<FormFlowTypeInterface> ? FormFlowInterface : FormInterface) */ public function createForm(string $type, mixed $data = null, array $options = []): FormInterface { return $this->container->get('form.factory')->create($type, $data, $options); } /** * Creates and returns a form builder instance. */ public function createFormBuilder(mixed $data = null, array $options = []): FormBuilderInterface { return $this->container->get('form.factory')->createBuilder(FormType::class, $data, $options); } /** * Creates and returns a form flow builder instance. */ public function createFormFlowBuilder(mixed $data = null, array $options = []): FormFlowBuilderInterface { return $this->container->get('form.factory')->createBuilder(FormFlowType::class, $data, $options); } /** * Get a user from the Security Token Storage. * * @throws \LogicException If SecurityBundle is not available * * @see TokenInterface::getUser() */ public function getUser(): ?UserInterface { if (!$this->container->has('security.token_storage')) { throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".'); } if (null === $token = $this->container->get('security.token_storage')->getToken()) { return null; } return $token->getUser(); } /** * Checks the validity of a CSRF token. * * @param string $id The id used when generating the token * @param string|null $token The actual token sent with the request that should be validated */ public function isCsrfTokenValid(string $id, #[\SensitiveParameter] ?string $token): bool { if (!$this->container->has('security.csrf.token_manager')) { throw new \LogicException('CSRF protection is not enabled in your application. Enable it with the "csrf_protection" key in "config/packages/framework.yaml".'); } return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id, $token)); } /** * Adds a Link HTTP header to the current response. * * @see https://tools.ietf.org/html/rfc5988 */ public function addLink(Request $request, LinkInterface $link): void { if (!class_exists(AddLinkHeaderListener::class)) { throw new \LogicException('You cannot use the "addLink" method if the WebLink component is not available. Try running "composer require symfony/web-link".'); } if (null === $linkProvider = $request->attributes->get('_links')) { $request->attributes->set('_links', new GenericLinkProvider([$link])); return; } $request->attributes->set('_links', $linkProvider->withLink($link)); } /** * @param LinkInterface[] $links */ public function sendEarlyHints(iterable $links = [], ?Response $response = null): Response { if (!$this->container->has('web_link.http_header_serializer')) { throw new \LogicException('You cannot use the "sendEarlyHints" method if the WebLink component is not available. Try running "composer require symfony/web-link".'); } $response ??= new Response(); $populatedLinks = []; foreach ($links as $link) { if ($link instanceof EvolvableLinkInterface && !$link->getRels()) { $link = $link->withRel('preload'); } $populatedLinks[] = $link; } $response->headers->set('Link', $this->container->get('web_link.http_header_serializer')->serialize($populatedLinks), false); $response->sendHeaders(103); return $response; } private function doRenderView(string $view, ?string $block, array $parameters, string $method): string { if (!$this->container->has('twig')) { throw new \LogicException(\sprintf('You cannot use the "%s" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".', $method)); } foreach ($parameters as $k => $v) { if ($v instanceof FormInterface) { $parameters[$k] = $v->createView(); } } if (null !== $block) { return $this->container->get('twig')->load($view)->renderBlock($block, $parameters); } return $this->container->get('twig')->render($view, $parameters); } private function doRender(string $view, ?string $block, array $parameters, ?Response $response, string $method): Response { $content = $this->doRenderView($view, $block, $parameters, $method); $response ??= new Response(); if (200 === $response->getStatusCode()) { foreach ($parameters as $v) { if ($v instanceof FormInterface && $v->isSubmitted() && !$v->isValid()) { $response->setStatusCode(422); break; } } } $response->setContent($content); return $response; } }
php
github
https://github.com/symfony/symfony
src/Symfony/Bundle/FrameworkBundle/Controller/ControllerHelper.php
import itertools, warnings import cPickle from hashlib import sha1 import numpy as np import helpers class DataSet: """ A data set consists of samples with features and labels, and some additional descriptors. xs* Samples with features. Features can be multi-dimensional. For example, in the case of EEG, samples can be epochs, consisting of time samples for each channel. If xs is multi-dimensional, then the multi-dimensional version can be obtained through the property: nd_xs. ys* The true class labels (or values) for the samples. The ground truth. For each sample, for each class, an indication is given as to the truth or chance or value for this class. For example, if for a certain sample the labels are [0 1 0] this means this sample belongs to the second class. The names of the classes are stored in cl_lab. ids A unique identifier per sample. If not provided, it will generate a unique integer id from 0 to the number of samples. In the case of EEG, this can contain the time stamps of the samples cl_lab A list of string descriptors for each class. feat_lab A list of string descriptors for each feature. feat_shape If the features of xs are multi-dimensional, feat_shape contains the shape of these features. feat_dim_lab For each feature dimension, a string descriptor. In the case of EEG, this could be ['channels', 'time']. feat_nd_lab For each feature dimension, a list of string feature descriptors. In the case of EEG, this could be [['C3','C4'],['0.01','0.02','0.03','0.04']] extra A dictionary that can be used to store any additional information you may want to include. default A default dataset from which all the information will be obtained that is not defined in the initialization of a new dataset. Fields with an asterisk have to be provided when creating a new dataset. For security, it is not possible to write to an already created dataset (xs, ys, and ids are locked). This way, you can be certain that a dataset will not be modified from analysis chain to another. Handy class functions: nd_xs Return a multi-dimensional view of xs, depends on feat_shape. save(filename) Store the dataset to disk. load(filename) Load a dataset from disk. d3 = d1 + d2 Adding datasets together. if d1 == d2 Comparing datasets. len(d) Return the number of samples in the dataset. d[5] Return the sample with index 5. str(d) Return a string representation of the dataset. d.shuffled() Return a dataset copy with the samples shuffled. d.sorted() Return a dataset copy with the samples sorted according to ids. """ @property def xs(self): warnings.warn('DataSet.xs is deprecated, use DataSet.X.T instead.', DeprecationWarning) return self.X.T @property def ys(self): warnings.warn('DataSet.ys is deprecated, use DataSet.Y.T instead.', DeprecationWarning) return self.Y.T @property def ids(self): warnings.warn('DataSet.ids is deprecated, use DataSet.I.T instead', DeprecationWarning) return self.I.T @property def nd_xs(self): warnings.warn('DataSet.nd_xs is deprecated. ' + 'Use np.rollaxis(d.ndX, -1) instead.', DeprecationWarning) return np.rollaxis(self.ndX, -1) def __init__(self, xs=None, ys=None, ids=None, cl_lab=None, feat_lab=None, feat_shape=None, feat_dim_lab=None, feat_nd_lab=None, extra=None, default=None, X=None, Y=None, I=None): ''' Create a new dataset. ''' # backwards compatibility if xs != None: X = np.asarray(xs).T if ys != None: Y = np.asarray(ys).T if ids != None: I = np.asarray(ids).T # first, take care of X, Y, I if default != None: assert isinstance(default, DataSet), 'Default is not a DataSet' X = X if X != None else default.X Y = Y if Y != None else default.Y I = I if I != None else default.I if X == None: raise ValueError, 'No X given' if Y == None: raise ValueError, 'No Y given' # convert to np.ndarray self.X, self.Y = X, Y = np.atleast_2d(X, Y) if I == None: I = np.arange(self.ninstances) self.I = I = np.atleast_2d(I) # test essential properties if self.X.ndim != 2: raise ValueError('Only 2D arrays are supported for X. See feat_shape.') if self.Y.ndim != 2: raise ValueError('Only 2D arrays are supported for Y.') if self.I.ndim != 2: raise ValueError('Only 2D arrays are supported for I.') if not (self.X.shape[1] == self.Y.shape[1] == self.I.shape[1]): raise ValueError('Number of instances (cols) does not match') if np.unique(self.I[0]).size != self.ninstances: raise ValueError('The ids not unique.') if not np.all(np.isfinite(self.X)): raise ValueError('Only finite values are allowed for X') # Lock X, Y, I: for arr in [self.X, self.Y, self.I]: arr.flags.writeable = False # Ok, X, Y and I are ok. Now wel add required structural info: if default != None: # fill in from default arg if cl_lab == None: cl_lab = default.cl_lab if feat_lab == None: feat_lab = default.feat_lab if feat_lab != None and len(feat_lab) != self.nfeatures: feat_lab = None if feat_shape == None: feat_shape = default.feat_shape if np.prod(default.feat_shape) != self.nfeatures: feat_shape = (self.nfeatures,) self.cl_lab = cl_lab if cl_lab \ else ['class%d' % i for i in range(self.nclasses)] self.feat_lab = feat_lab self.feat_shape = feat_shape if feat_shape != None else (self.nfeatures,) # Now we are basically done, but let's add optional info if default != None: # fill in from default arg if feat_dim_lab == None: feat_dim_lab = default.feat_dim_lab if len(feat_dim_lab) != len(self.feat_shape): feat_dim_lab = None if feat_nd_lab == None: feat_nd_lab = default.feat_nd_lab if feat_nd_lab != None: if tuple(len(dim_lab) for dim_lab in feat_nd_lab) != self.feat_shape: feat_nd_lab = None extra = extra if extra != None else default.extra self.feat_dim_lab = feat_dim_lab if feat_dim_lab else \ ['feat_dim%d' % i for i in range(len(self.feat_shape))] self.feat_nd_lab = feat_nd_lab if feat_nd_lab else None self.extra = extra if extra else {} self.check_consistency() def check_consistency(self): assert isinstance(self.cl_lab, list), 'cl_lab not a list' assert self.feat_lab == None or isinstance(self.feat_lab, list), \ 'Feature labels not a list' assert isinstance(self.feat_shape, tuple), 'feat_shape not a tuple' assert isinstance(self.feat_dim_lab, list), 'feat_dim_lab not a list' assert isinstance(self.extra, dict), 'extra not a dict' if self.feat_lab != None and len(self.feat_lab) != self.nfeatures: raise ValueError('feat_lab %s does not match #features' % self.feat_lab) if len(self.cl_lab) != self.nclasses: raise ValueError('The number of class labels does not match #classes') if not np.prod(self.feat_shape) == self.nfeatures: raise ValueError('%d features does not match feat_shape %s' % \ (self.nfeatures, self.feat_shape)) if self.feat_dim_lab != None: if len(self.feat_shape) != len(self.feat_dim_lab): raise ValueError('feat_dim_lab %s does not match feat_shape %s' % (repr(self.feat_dim_lab), repr(self.feat_shape))) if self.feat_nd_lab != None: assert len(self.feat_nd_lab) == len(self.feat_shape) for i, dlab in enumerate(self.feat_nd_lab): assert isinstance(dlab, list) if len(dlab) != self.feat_shape[i]: raise ValueError( 'feat_nd_lab[%d] %s does not match feat_shape %s' % \ (i, dlab, self.feat_shape)) def get_class(self, i): return self[self.Y[i] == 1] def sorted(self): '''Return a DataSet sorted on the first row of .I''' return self[np.argsort(self.I[0])] def shuffled(self): '''Return a shuffled DataSet''' si = np.arange(self.ninstances) np.random.shuffle(si) return self[si] def __getitem__(self, i): if isinstance(i, slice) or isinstance(i, list) or isinstance(i, np.ndarray): if self.ninstances == 0: if not isinstance(i, slice) and len(i) == 0: # Because np.zeros((0, 10)[[]] raises error, we use a workaround # using slice to index in a empty dataset. # see http://projects.scipy.org/numpy/ticket/1171 i = slice(0) return DataSet(X=self.X[:,i], Y=self.Y[:,i], I=self.I[:,i], default=self) elif isinstance(i, int): return DataSet(X=np.atleast_2d(self.X[:,i]).T, Y=np.atleast_2d(self.Y[:,i]).T, I=np.atleast_2d(self.I[:,i]).T, default=self) else: raise ValueError, 'Unknown indexing type.' def __len__(self): return self.ninstances def __str__(self): return ('DataSet with %d instances, %d features [%s], %d classes: %s, ' 'extras: %s') % (self.ninstances, self.nfeatures, 'x'.join([str(di) for di in self.feat_shape]), self.nclasses, repr(self.ninstances_per_class), repr(self.extra.keys())) def __repr__(self): return str(self) def __add__(a, b): '''Create a new DataSet by adding the instances of b to a''' assert(isinstance(a, DataSet)) assert(isinstance(b, DataSet)) # Handle empty datasets if a.X.ndim == 0: return b if b.X.ndim == 0: return a # Check for compatibility if (a.nfeatures != b.nfeatures) or (a.nclasses != b.nclasses): raise ValueError, 'The #features or #classes do not match' for member in a.__dict__.keys(): if member not in ['X', 'Y', 'I']: if a.__dict__[member] != b.__dict__[member]: raise ValueError('Cannot add DataSets: %s is different' % member) return DataSet(X=np.hstack([a.X, b.X]), Y=np.hstack([a.Y, b.Y]), I=np.hstack([a.I, b.I]), default=a) def __eq__(a, b): if not isinstance(b, DataSet): return False for member in a.__dict__.keys(): am, bm = a.__dict__[member], b.__dict__[member] if isinstance(am, np.ndarray): if am.shape != bm.shape or not np.all(am == bm): return False else: if not am == bm: return False return True def __ne__(a, b): return not a == b @property def nclasses(self): if self.Y.ndim == 0: return 0 return self.Y.shape[0] @property def ninstances(self): if self.X.ndim == 0: return 0 return self.X.shape[1] @property def ninstances_per_class(self): return np.sum(helpers.hard_max(self.Y), axis=1).astype(int).tolist() @property def prior(self): return np.asarray(self.ninstances_per_class) / float(self.ninstances) @property def nfeatures(self): if self.X.ndim == 0: return 0 return self.X.shape[0] @property def ndX(self): '''Return multi-dimensional view of X''' return self.X.reshape(self.feat_shape + (self.ninstances,)) def save(self, file): f = open(file, 'wb') if isinstance(file, str) else file cPickle.dump(self, f, cPickle.HIGHEST_PROTOCOL) if isinstance(file, str): f.close() @classmethod def load(cls, file): f = open(file, 'rb') if isinstance(file, str) else file d = cPickle.load(f) assert isinstance(d, DataSet) d.check_consistency() if isinstance(file, str): f.close() return d
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0030_auto_20151203_1116'), ] operations = [ migrations.AlterField( model_name='userprofile', name='use_case', field=models.CharField(blank=True, max_length=3, null=True, choices=[(b'u01', b'Use Case 1: Comparison between stratospheric ozone model output and satellite observations'), (b'u02', b'Use Case 2: Model validation tool'), (b'u03', b'Use Case 3: Characterization of optical and microphysical properties of aerosol'), (b'u04', b'Use Case 4: ECARE lidar/ CALIPSO Simulation'), (b'u05', b'Use Case 5: Development of Scientific L2 products based on OMI instruments'), (b'u06', b'Use Case 6: Model Quality Assessment'), (b'u07', b'Use Case 7: Re-grid and time average satellite data'), (b'u08', b'Use Case 8: Model Validation against satellite data (Aerosol NO2, trace gases)'), (b'u09', b'Dummy use case 1'), (b'u10', b'Dummy use case 2'), (b'u11', b'Dummy use case 3)')]), ), ]
unknown
codeparrot/codeparrot-clean
import warnings from .base import Renderer from ..exporter import Exporter class VincentRenderer(Renderer): def open_figure(self, fig, props): self.chart = None self.figwidth = int(props['figwidth'] * props['dpi']) self.figheight = int(props['figheight'] * props['dpi']) def draw_line(self, data, coordinates, style, label, mplobj=None): import vincent # only import if VincentRenderer is used if coordinates != 'data': warnings.warn("Only data coordinates supported. Skipping this") linedata = {'x': data[:, 0], 'y': data[:, 1]} line = vincent.Line(linedata, iter_idx='x', width=self.figwidth, height=self.figheight) # TODO: respect the other style settings line.scales['color'].range = [style['color']] if self.chart is None: self.chart = line else: warnings.warn("Multiple plot elements not yet supported") def draw_markers(self, data, coordinates, style, label, mplobj=None): import vincent # only import if VincentRenderer is used if coordinates != 'data': warnings.warn("Only data coordinates supported. Skipping this") markerdata = {'x': data[:, 0], 'y': data[:, 1]} markers = vincent.Scatter(markerdata, iter_idx='x', width=self.figwidth, height=self.figheight) # TODO: respect the other style settings markers.scales['color'].range = [style['facecolor']] if self.chart is None: self.chart = markers else: warnings.warn("Multiple plot elements not yet supported") def fig_to_vincent(fig): """Convert a matplotlib figure to a vincent object""" renderer = VincentRenderer() exporter = Exporter(renderer) exporter.run(fig) return renderer.chart
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python # -*- coding: utf-8 -*- # # king_phisher/client/dialogs/__init__.py # # 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 project nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # from .about import * from .campaign_selection import * from .clone_page import * from .company_editor import * from .configuration import * from .entry import * from .exception import * from .login import * from .ssh_host_key import * from .tag_editor import *
unknown
codeparrot/codeparrot-clean
package daemon import ( "testing" containertypes "github.com/moby/moby/api/types/container" ) func TestMergeAndVerifyLogConfigNilConfig(t *testing.T) { d := &Daemon{defaultLogConfig: containertypes.LogConfig{Type: "json-file", Config: map[string]string{"max-file": "1"}}} cfg := containertypes.LogConfig{Type: d.defaultLogConfig.Type} if err := d.mergeAndVerifyLogConfig(&cfg); err != nil { t.Fatal(err) } }
go
github
https://github.com/moby/moby
daemon/logs_test.go
# Parsec Cloud (https://parsec.cloud) Copyright (c) AGPLv3 2016-2021 Scille SAS import pytest import trio from uuid import uuid4 from parsec.api.protocol import INVITED_CMDS, InvitationType from parsec.core.types import BackendInvitationAddr from parsec.core.backend_connection import ( BackendNotAvailable, BackendConnectionRefused, BackendInvitationNotFound, BackendInvitationAlreadyUsed, backend_invited_cmds_factory, ) from parsec.backend.backend_events import BackendEvent from tests.core.backend_connection.common import ALL_CMDS @pytest.fixture async def invitation_addr(backend, alice): invitation = await backend.invite.new_for_device( organization_id=alice.organization_id, greeter_user_id=alice.user_id ) return BackendInvitationAddr.build( backend_addr=alice.organization_addr, organization_id=alice.organization_id, invitation_type=InvitationType.DEVICE, token=invitation.token, ) @pytest.mark.trio async def test_backend_offline(invitation_addr): with pytest.raises(BackendNotAvailable): async with backend_invited_cmds_factory(invitation_addr) as cmds: await cmds.ping() @pytest.mark.trio async def test_backend_switch_offline(running_backend, invitation_addr): async with backend_invited_cmds_factory(invitation_addr) as cmds: await cmds.ping() with running_backend.offline(): with pytest.raises(BackendNotAvailable): await cmds.ping() @pytest.mark.trio async def test_backend_closed_cmds(running_backend, invitation_addr): async with backend_invited_cmds_factory(invitation_addr) as cmds: pass with pytest.raises(trio.ClosedResourceError): await cmds.ping() @pytest.mark.trio async def test_ping(running_backend, invitation_addr): async with backend_invited_cmds_factory(invitation_addr) as cmds: rep = await cmds.ping("Hello World !") assert rep == {"status": "ok", "pong": "Hello World !"} @pytest.mark.trio async def test_handshake_organization_expired(running_backend, expiredorg, expiredorgalice): invitation = await running_backend.backend.invite.new_for_device( organization_id=expiredorgalice.organization_id, greeter_user_id=expiredorgalice.user_id ) invitation_addr = BackendInvitationAddr.build( backend_addr=running_backend.addr, organization_id=expiredorgalice.organization_id, invitation_type=InvitationType.DEVICE, token=invitation.token, ) with running_backend.backend.event_bus.listen() as spy: with pytest.raises(BackendConnectionRefused) as exc: async with backend_invited_cmds_factory(invitation_addr) as cmds: await cmds.ping() await spy.wait_with_timeout(BackendEvent.ORGANIZATION_EXPIRED) assert str(exc.value) == "Trial organization has expired" @pytest.mark.trio async def test_handshake_unknown_organization(running_backend, coolorg): invitation_addr = BackendInvitationAddr.build( backend_addr=running_backend.addr, organization_id=coolorg.organization_id, invitation_type=InvitationType.DEVICE, token=uuid4(), ) with pytest.raises(BackendInvitationNotFound) as exc: async with backend_invited_cmds_factory(invitation_addr) as cmds: await cmds.ping() assert str(exc.value) == "Invalid handshake: Invitation not found" from parsec.api.protocol import InvitationDeletedReason from pendulum import now as pendulum_now @pytest.mark.trio async def test_handshake_already_used_invitation(running_backend, coolorg, invitation_addr, alice): await running_backend.backend.invite.delete( organization_id=alice.organization_id, greeter=alice.user_id, token=invitation_addr.token, on=pendulum_now(), reason=InvitationDeletedReason.CANCELLED, ) with pytest.raises(BackendInvitationAlreadyUsed) as exc: async with backend_invited_cmds_factory(invitation_addr) as cmds: await cmds.ping() assert str(exc.value) == "Invalid handshake: Invitation already deleted" @pytest.mark.trio async def test_invited_cmds_has_right_methods(running_backend, coolorg): async with backend_invited_cmds_factory(coolorg.addr) as cmds: for method_name in INVITED_CMDS: assert hasattr(cmds, method_name) for method_name in ALL_CMDS - INVITED_CMDS: assert not hasattr(cmds, method_name)
unknown
codeparrot/codeparrot-clean
from test.support import verbose, TestFailed import sys import test.support as support import unittest maxsize = support.MAX_Py_ssize_t # test string formatting operator (I am not sure if this is being tested # elsewhere but, surely, some of the given cases are *not* tested because # they crash python) # test on unicode strings as well def testformat(formatstr, args, output=None, limit=None, overflowok=False): if verbose: if output: print("%r %% %r =? %r ..." %\ (formatstr, args, output), end=' ') else: print("%r %% %r works? ..." % (formatstr, args), end=' ') try: result = formatstr % args except OverflowError: if not overflowok: raise if verbose: print('overflow (this is fine)') else: if output and limit is None and result != output: if verbose: print('no') raise AssertionError("%r %% %r == %r != %r" % (formatstr, args, result, output)) # when 'limit' is specified, it determines how many characters # must match exactly; lengths must always match. # ex: limit=5, '12345678' matches '12345___' # (mainly for floating point format tests for which an exact match # can't be guaranteed due to rounding and representation errors) elif output and limit is not None and ( len(result)!=len(output) or result[:limit]!=output[:limit]): if verbose: print('no') print("%s %% %s == %s != %s" % \ (repr(formatstr), repr(args), repr(result), repr(output))) else: if verbose: print('yes') class FormatTest(unittest.TestCase): def test_format(self): testformat("%.1d", (1,), "1") testformat("%.*d", (sys.maxsize,1), overflowok=True) # expect overflow testformat("%.100d", (1,), '00000000000000000000000000000000000000' '000000000000000000000000000000000000000000000000000000' '00000001', overflowok=True) testformat("%#.117x", (1,), '0x00000000000000000000000000000000000' '000000000000000000000000000000000000000000000000000000' '0000000000000000000000000001', overflowok=True) testformat("%#.118x", (1,), '0x00000000000000000000000000000000000' '000000000000000000000000000000000000000000000000000000' '00000000000000000000000000001', overflowok=True) testformat("%f", (1.0,), "1.000000") # these are trying to test the limits of the internal magic-number-length # formatting buffer, if that number changes then these tests are less # effective testformat("%#.*g", (109, -1.e+49/3.)) testformat("%#.*g", (110, -1.e+49/3.)) testformat("%#.*g", (110, -1.e+100/3.)) # test some ridiculously large precision, expect overflow testformat('%12.*f', (123456, 1.0)) # check for internal overflow validation on length of precision # these tests should no longer cause overflow in Python # 2.7/3.1 and later. testformat("%#.*g", (110, -1.e+100/3.)) testformat("%#.*G", (110, -1.e+100/3.)) testformat("%#.*f", (110, -1.e+100/3.)) testformat("%#.*F", (110, -1.e+100/3.)) # Formatting of integers. Overflow is not ok testformat("%x", 10, "a") testformat("%x", 100000000000, "174876e800") testformat("%o", 10, "12") testformat("%o", 100000000000, "1351035564000") testformat("%d", 10, "10") testformat("%d", 100000000000, "100000000000") big = 123456789012345678901234567890 testformat("%d", big, "123456789012345678901234567890") testformat("%d", -big, "-123456789012345678901234567890") testformat("%5d", -big, "-123456789012345678901234567890") testformat("%31d", -big, "-123456789012345678901234567890") testformat("%32d", -big, " -123456789012345678901234567890") testformat("%-32d", -big, "-123456789012345678901234567890 ") testformat("%032d", -big, "-0123456789012345678901234567890") testformat("%-032d", -big, "-123456789012345678901234567890 ") testformat("%034d", -big, "-000123456789012345678901234567890") testformat("%034d", big, "0000123456789012345678901234567890") testformat("%0+34d", big, "+000123456789012345678901234567890") testformat("%+34d", big, " +123456789012345678901234567890") testformat("%34d", big, " 123456789012345678901234567890") testformat("%.2d", big, "123456789012345678901234567890") testformat("%.30d", big, "123456789012345678901234567890") testformat("%.31d", big, "0123456789012345678901234567890") testformat("%32.31d", big, " 0123456789012345678901234567890") testformat("%d", float(big), "123456________________________", 6) big = 0x1234567890abcdef12345 # 21 hex digits testformat("%x", big, "1234567890abcdef12345") testformat("%x", -big, "-1234567890abcdef12345") testformat("%5x", -big, "-1234567890abcdef12345") testformat("%22x", -big, "-1234567890abcdef12345") testformat("%23x", -big, " -1234567890abcdef12345") testformat("%-23x", -big, "-1234567890abcdef12345 ") testformat("%023x", -big, "-01234567890abcdef12345") testformat("%-023x", -big, "-1234567890abcdef12345 ") testformat("%025x", -big, "-0001234567890abcdef12345") testformat("%025x", big, "00001234567890abcdef12345") testformat("%0+25x", big, "+0001234567890abcdef12345") testformat("%+25x", big, " +1234567890abcdef12345") testformat("%25x", big, " 1234567890abcdef12345") testformat("%.2x", big, "1234567890abcdef12345") testformat("%.21x", big, "1234567890abcdef12345") testformat("%.22x", big, "01234567890abcdef12345") testformat("%23.22x", big, " 01234567890abcdef12345") testformat("%-23.22x", big, "01234567890abcdef12345 ") testformat("%X", big, "1234567890ABCDEF12345") testformat("%#X", big, "0X1234567890ABCDEF12345") testformat("%#x", big, "0x1234567890abcdef12345") testformat("%#x", -big, "-0x1234567890abcdef12345") testformat("%#.23x", -big, "-0x001234567890abcdef12345") testformat("%#+.23x", big, "+0x001234567890abcdef12345") testformat("%# .23x", big, " 0x001234567890abcdef12345") testformat("%#+.23X", big, "+0X001234567890ABCDEF12345") testformat("%#-+.23X", big, "+0X001234567890ABCDEF12345") testformat("%#-+26.23X", big, "+0X001234567890ABCDEF12345") testformat("%#-+27.23X", big, "+0X001234567890ABCDEF12345 ") testformat("%#+27.23X", big, " +0X001234567890ABCDEF12345") # next one gets two leading zeroes from precision, and another from the # 0 flag and the width testformat("%#+027.23X", big, "+0X0001234567890ABCDEF12345") # same, except no 0 flag testformat("%#+27.23X", big, " +0X001234567890ABCDEF12345") testformat("%x", float(big), "123456_______________", 6) big = 0o12345670123456701234567012345670 # 32 octal digits testformat("%o", big, "12345670123456701234567012345670") testformat("%o", -big, "-12345670123456701234567012345670") testformat("%5o", -big, "-12345670123456701234567012345670") testformat("%33o", -big, "-12345670123456701234567012345670") testformat("%34o", -big, " -12345670123456701234567012345670") testformat("%-34o", -big, "-12345670123456701234567012345670 ") testformat("%034o", -big, "-012345670123456701234567012345670") testformat("%-034o", -big, "-12345670123456701234567012345670 ") testformat("%036o", -big, "-00012345670123456701234567012345670") testformat("%036o", big, "000012345670123456701234567012345670") testformat("%0+36o", big, "+00012345670123456701234567012345670") testformat("%+36o", big, " +12345670123456701234567012345670") testformat("%36o", big, " 12345670123456701234567012345670") testformat("%.2o", big, "12345670123456701234567012345670") testformat("%.32o", big, "12345670123456701234567012345670") testformat("%.33o", big, "012345670123456701234567012345670") testformat("%34.33o", big, " 012345670123456701234567012345670") testformat("%-34.33o", big, "012345670123456701234567012345670 ") testformat("%o", big, "12345670123456701234567012345670") testformat("%#o", big, "0o12345670123456701234567012345670") testformat("%#o", -big, "-0o12345670123456701234567012345670") testformat("%#.34o", -big, "-0o0012345670123456701234567012345670") testformat("%#+.34o", big, "+0o0012345670123456701234567012345670") testformat("%# .34o", big, " 0o0012345670123456701234567012345670") testformat("%#+.34o", big, "+0o0012345670123456701234567012345670") testformat("%#-+.34o", big, "+0o0012345670123456701234567012345670") testformat("%#-+37.34o", big, "+0o0012345670123456701234567012345670") testformat("%#+37.34o", big, "+0o0012345670123456701234567012345670") # next one gets one leading zero from precision testformat("%.33o", big, "012345670123456701234567012345670") # base marker shouldn't change that, since "0" is redundant testformat("%#.33o", big, "0o012345670123456701234567012345670") # but reduce precision, and base marker should add a zero testformat("%#.32o", big, "0o12345670123456701234567012345670") # one leading zero from precision, and another from "0" flag & width testformat("%034.33o", big, "0012345670123456701234567012345670") # base marker shouldn't change that testformat("%0#34.33o", big, "0o012345670123456701234567012345670") testformat("%o", float(big), "123456__________________________", 6) # Some small ints, in both Python int and flavors). testformat("%d", 42, "42") testformat("%d", -42, "-42") testformat("%d", 42, "42") testformat("%d", -42, "-42") testformat("%d", 42.0, "42") testformat("%#x", 1, "0x1") testformat("%#x", 1, "0x1") testformat("%#X", 1, "0X1") testformat("%#X", 1, "0X1") testformat("%#x", 1.0, "0x1") testformat("%#o", 1, "0o1") testformat("%#o", 1, "0o1") testformat("%#o", 0, "0o0") testformat("%#o", 0, "0o0") testformat("%o", 0, "0") testformat("%o", 0, "0") testformat("%d", 0, "0") testformat("%d", 0, "0") testformat("%#x", 0, "0x0") testformat("%#x", 0, "0x0") testformat("%#X", 0, "0X0") testformat("%#X", 0, "0X0") testformat("%x", 0x42, "42") testformat("%x", -0x42, "-42") testformat("%x", 0x42, "42") testformat("%x", -0x42, "-42") testformat("%x", float(0x42), "42") testformat("%o", 0o42, "42") testformat("%o", -0o42, "-42") testformat("%o", 0o42, "42") testformat("%o", -0o42, "-42") testformat("%o", float(0o42), "42") testformat("%r", "\u0378", "'\\u0378'") # non printable testformat("%a", "\u0378", "'\\u0378'") # non printable testformat("%r", "\u0374", "'\u0374'") # printable testformat("%a", "\u0374", "'\\u0374'") # printable # alternate float formatting testformat('%g', 1.1, '1.1') testformat('%#g', 1.1, '1.10000') # Test exception for unknown format characters if verbose: print('Testing exceptions') def test_exc(formatstr, args, exception, excmsg): try: testformat(formatstr, args) except exception as exc: if str(exc) == excmsg: if verbose: print("yes") else: if verbose: print('no') print('Unexpected ', exception, ':', repr(str(exc))) except: if verbose: print('no') print('Unexpected exception') raise else: raise TestFailed('did not get expected exception: %s' % excmsg) test_exc('abc %b', 1, ValueError, "unsupported format character 'b' (0x62) at index 5") #test_exc(unicode('abc %\u3000','raw-unicode-escape'), 1, ValueError, # "unsupported format character '?' (0x3000) at index 5") test_exc('%d', '1', TypeError, "%d format: a number is required, not str") test_exc('%g', '1', TypeError, "a float is required") test_exc('no format', '1', TypeError, "not all arguments converted during string formatting") test_exc('no format', '1', TypeError, "not all arguments converted during string formatting") if maxsize == 2**31-1: # crashes 2.2.1 and earlier: try: "%*d"%(maxsize, -127) except MemoryError: pass else: raise TestFailed('"%*d"%(maxsize, -127) should fail') def test_main(): support.run_unittest(FormatTest) if __name__ == "__main__": unittest.main()
unknown
codeparrot/codeparrot-clean
# 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. # ============================================================================== """Tests for tensorflow.ops.svd.""" import itertools from absl.testing import parameterized import numpy as np from tensorflow.compiler.tests import xla_test from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_linalg_ops from tensorflow.python.ops import linalg_ops from tensorflow.python.platform import test class SvdOpTest(xla_test.XLATestCase, parameterized.TestCase): def _compute_usvt(self, s, u, v): m = u.shape[-1] n = v.shape[-1] if m <= n: v = v[..., :m] else: u = u[..., :n] return np.matmul(u * s[..., None, :], np.swapaxes(v, -1, -2)) def _testSvdCorrectness(self, dtype, shape): np.random.seed(1) x_np = np.random.uniform(low=-1.0, high=1.0, size=shape).astype(dtype) m, n = shape[-2], shape[-1] _, s_np, _ = np.linalg.svd(x_np) with self.session() as sess: x_tf = array_ops.placeholder(dtype) with self.test_scope(): s, u, v = linalg_ops.svd(x_tf, full_matrices=True) s_val, u_val, v_val = sess.run([s, u, v], feed_dict={x_tf: x_np}) u_diff = np.matmul(u_val, np.swapaxes(u_val, -1, -2)) - np.eye(m) v_diff = np.matmul(v_val, np.swapaxes(v_val, -1, -2)) - np.eye(n) # Check u_val and v_val are orthogonal matrices. self.assertLess(np.linalg.norm(u_diff), 1e-2) self.assertLess(np.linalg.norm(v_diff), 1e-2) # Check that the singular values are correct, i.e., close to the ones from # numpy.lingal.svd. self.assertLess(np.linalg.norm(s_val - s_np), 1e-2) # The tolerance is set based on our tests on numpy's svd. As our tests # have batch dimensions and all our operations are on float32, we set the # tolerance a bit larger. Numpy's svd calls LAPACK's svd, which operates # on double precision. self.assertLess( np.linalg.norm(self._compute_usvt(s_val, u_val, v_val) - x_np), 2e-2) # Check behavior with compute_uv=False. We expect to still see 3 outputs, # with a sentinel scalar 0 in the last two outputs. with self.test_scope(): no_uv_s, no_uv_u, no_uv_v = gen_linalg_ops.svd( x_tf, full_matrices=True, compute_uv=False) no_uv_s_val, no_uv_u_val, no_uv_v_val = sess.run( [no_uv_s, no_uv_u, no_uv_v], feed_dict={x_tf: x_np}) self.assertAllClose(no_uv_s_val, s_val, atol=1e-4, rtol=1e-4) self.assertEqual(no_uv_u_val.shape, tensor_shape.TensorShape([0])) self.assertEqual(no_uv_v_val.shape, tensor_shape.TensorShape([0])) SIZES = [1, 2, 5, 10, 32, 64] DTYPES = [np.float32] PARAMS = itertools.product(SIZES, DTYPES) @parameterized.parameters(*PARAMS) def testSvd(self, n, dtype): for batch_dims in [(), (3,)] + [(3, 2)] * (n < 10): self._testSvdCorrectness(dtype, batch_dims + (n, n)) self._testSvdCorrectness(dtype, batch_dims + (2 * n, n)) self._testSvdCorrectness(dtype, batch_dims + (n, 2 * n)) if __name__ == "__main__": test.main()
python
github
https://github.com/tensorflow/tensorflow
tensorflow/compiler/tests/svd_op_test.py
// clinic/vectorcall.c.h uses internal pycore_modsupport.h API #define PYTESTCAPI_NEED_INTERNAL_API #include "parts.h" #include "clinic/vectorcall.c.h" #include <stddef.h> // offsetof /*[clinic input] module _testcapi [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=6361033e795369fc]*/ /* Test PEP 590 - Vectorcall */ static int fastcall_args(PyObject *args, PyObject ***stack, Py_ssize_t *nargs) { if (args == Py_None) { *stack = NULL; *nargs = 0; } else if (PyTuple_Check(args)) { *stack = ((PyTupleObject *)args)->ob_item; *nargs = PyTuple_GET_SIZE(args); } else { PyErr_SetString(PyExc_TypeError, "args must be None or a tuple"); return -1; } return 0; } /*[clinic input] _testcapi.pyobject_fastcalldict func: object func_args: object kwargs: object / [clinic start generated code]*/ static PyObject * _testcapi_pyobject_fastcalldict_impl(PyObject *module, PyObject *func, PyObject *func_args, PyObject *kwargs) /*[clinic end generated code: output=35902ece94de4418 input=b9c0196ca7d5f9e4]*/ { PyObject **stack; Py_ssize_t nargs; if (fastcall_args(func_args, &stack, &nargs) < 0) { return NULL; } if (kwargs == Py_None) { kwargs = NULL; } else if (!PyDict_Check(kwargs)) { PyErr_SetString(PyExc_TypeError, "kwnames must be None or a dict"); return NULL; } return PyObject_VectorcallDict(func, stack, nargs, kwargs); } /*[clinic input] _testcapi.pyobject_vectorcall func: object func_args: object kwnames: object / [clinic start generated code]*/ static PyObject * _testcapi_pyobject_vectorcall_impl(PyObject *module, PyObject *func, PyObject *func_args, PyObject *kwnames) /*[clinic end generated code: output=ff77245bc6afe0d8 input=a0668dfef625764c]*/ { PyObject **stack; Py_ssize_t nargs, nkw; if (fastcall_args(func_args, &stack, &nargs) < 0) { return NULL; } if (kwnames == Py_None) { kwnames = NULL; } else if (PyTuple_Check(kwnames)) { nkw = PyTuple_GET_SIZE(kwnames); if (nargs < nkw) { PyErr_SetString(PyExc_ValueError, "kwnames longer than args"); return NULL; } nargs -= nkw; } else { PyErr_SetString(PyExc_TypeError, "kwnames must be None or a tuple"); return NULL; } return PyObject_Vectorcall(func, stack, nargs, kwnames); } static PyObject * override_vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames) { return PyUnicode_FromString("overridden"); } static PyObject * function_setvectorcall(PyObject *self, PyObject *func) { if (!PyFunction_Check(func)) { PyErr_SetString(PyExc_TypeError, "'func' must be a function"); return NULL; } PyFunction_SetVectorcall((PyFunctionObject *)func, (vectorcallfunc)override_vectorcall); Py_RETURN_NONE; } /*[clinic input] _testcapi.pyvectorcall_call func: object argstuple: object kwargs: object = NULL / [clinic start generated code]*/ static PyObject * _testcapi_pyvectorcall_call_impl(PyObject *module, PyObject *func, PyObject *argstuple, PyObject *kwargs) /*[clinic end generated code: output=809046fe78511306 input=4376ee7cabd698ce]*/ { if (!PyTuple_Check(argstuple)) { PyErr_SetString(PyExc_TypeError, "args must be a tuple"); return NULL; } if (kwargs != NULL && !PyDict_Check(kwargs)) { PyErr_SetString(PyExc_TypeError, "kwargs must be a dict"); return NULL; } return PyVectorcall_Call(func, argstuple, kwargs); } PyObject * VectorCallClass_tpcall(PyObject *self, PyObject *args, PyObject *kwargs) { return PyUnicode_FromString("tp_call"); } PyObject * VectorCallClass_vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames) { return PyUnicode_FromString("vectorcall"); } /*[clinic input] class _testcapi.VectorCallClass "PyObject *" "&PyType_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=95c63c1a47f9a995]*/ /*[clinic input] @permit_long_summary _testcapi.VectorCallClass.set_vectorcall type: object(subclass_of="&PyType_Type", type="PyTypeObject *") / Set self's vectorcall function for `type` to one that returns "vectorcall" [clinic start generated code]*/ static PyObject * _testcapi_VectorCallClass_set_vectorcall_impl(PyObject *self, PyTypeObject *type) /*[clinic end generated code: output=b37f0466f15da903 input=170fefc7ee77fd36]*/ { if (!PyObject_TypeCheck(self, type)) { return PyErr_Format( PyExc_TypeError, "expected %N instance", type); } if (!type->tp_vectorcall_offset) { return PyErr_Format( PyExc_TypeError, "type %N has no vectorcall offset", type); } *(vectorcallfunc*)((char*)self + type->tp_vectorcall_offset) = ( VectorCallClass_vectorcall); Py_RETURN_NONE; } PyMethodDef VectorCallClass_methods[] = { _TESTCAPI_VECTORCALLCLASS_SET_VECTORCALL_METHODDEF {NULL, NULL} }; PyMemberDef VectorCallClass_members[] = { {"__vectorcalloffset__", Py_T_PYSSIZET, 0/* set later */, Py_READONLY}, {NULL} }; PyType_Slot VectorCallClass_slots[] = { {Py_tp_call, VectorCallClass_tpcall}, {Py_tp_members, VectorCallClass_members}, {Py_tp_methods, VectorCallClass_methods}, {0}, }; /*[clinic input] _testcapi.make_vectorcall_class base: object(subclass_of="&PyType_Type", type="PyTypeObject *") = NULL / Create a class whose instances return "tpcall" when called. When the "set_vectorcall" method is called on an instance, a vectorcall function that returns "vectorcall" will be installed. [clinic start generated code]*/ static PyObject * _testcapi_make_vectorcall_class_impl(PyObject *module, PyTypeObject *base) /*[clinic end generated code: output=16dcfc3062ddf968 input=f72e01ccf52de2b4]*/ { if (!base) { base = (PyTypeObject *)&PyBaseObject_Type; } VectorCallClass_members[0].offset = base->tp_basicsize; PyType_Spec spec = { .name = "_testcapi.VectorcallClass", .basicsize = (int)(base->tp_basicsize + sizeof(vectorcallfunc)), .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_VECTORCALL | Py_TPFLAGS_BASETYPE, .slots = VectorCallClass_slots, }; return PyType_FromSpecWithBases(&spec, (PyObject *)base); } /*[clinic input] _testcapi.has_vectorcall_flag -> bool type: object(subclass_of="&PyType_Type", type="PyTypeObject *") / Return true iff Py_TPFLAGS_HAVE_VECTORCALL is set on the class. [clinic start generated code]*/ static int _testcapi_has_vectorcall_flag_impl(PyObject *module, PyTypeObject *type) /*[clinic end generated code: output=3ae8d1374388c671 input=8eee492ac548749e]*/ { return PyType_HasFeature(type, Py_TPFLAGS_HAVE_VECTORCALL); } static PyMethodDef TestMethods[] = { _TESTCAPI_PYOBJECT_FASTCALLDICT_METHODDEF _TESTCAPI_PYOBJECT_VECTORCALL_METHODDEF {"function_setvectorcall", function_setvectorcall, METH_O}, _TESTCAPI_PYVECTORCALL_CALL_METHODDEF _TESTCAPI_MAKE_VECTORCALL_CLASS_METHODDEF _TESTCAPI_HAS_VECTORCALL_FLAG_METHODDEF {NULL}, }; typedef struct { PyObject_HEAD vectorcallfunc vectorcall; } MethodDescriptorObject; static PyObject * MethodDescriptor_vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames) { /* True if using the vectorcall function in MethodDescriptorObject * but False for MethodDescriptor2Object */ MethodDescriptorObject *md = (MethodDescriptorObject *)callable; return PyBool_FromLong(md->vectorcall != NULL); } static PyObject * MethodDescriptor_new(PyTypeObject* type, PyObject* args, PyObject *kw) { MethodDescriptorObject *op = (MethodDescriptorObject *)type->tp_alloc(type, 0); op->vectorcall = MethodDescriptor_vectorcall; return (PyObject *)op; } static PyObject * func_descr_get(PyObject *func, PyObject *obj, PyObject *type) { if (obj == Py_None || obj == NULL) { return Py_NewRef(func); } return PyMethod_New(func, obj); } static PyObject * nop_descr_get(PyObject *func, PyObject *obj, PyObject *type) { return Py_NewRef(func); } static PyObject * call_return_args(PyObject *self, PyObject *args, PyObject *kwargs) { return Py_NewRef(args); } static PyTypeObject MethodDescriptorBase_Type = { PyVarObject_HEAD_INIT(NULL, 0) "MethodDescriptorBase", sizeof(MethodDescriptorObject), .tp_new = MethodDescriptor_new, .tp_call = PyVectorcall_Call, .tp_vectorcall_offset = offsetof(MethodDescriptorObject, vectorcall), .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_METHOD_DESCRIPTOR | Py_TPFLAGS_HAVE_VECTORCALL, .tp_descr_get = func_descr_get, }; static PyTypeObject MethodDescriptorDerived_Type = { PyVarObject_HEAD_INIT(NULL, 0) "MethodDescriptorDerived", .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, }; static PyTypeObject MethodDescriptorNopGet_Type = { PyVarObject_HEAD_INIT(NULL, 0) "MethodDescriptorNopGet", .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, .tp_call = call_return_args, .tp_descr_get = nop_descr_get, }; typedef struct { MethodDescriptorObject base; vectorcallfunc vectorcall; } MethodDescriptor2Object; static PyObject * MethodDescriptor2_new(PyTypeObject* type, PyObject* args, PyObject *kw) { MethodDescriptor2Object *op = PyObject_New(MethodDescriptor2Object, type); if (op == NULL) { return NULL; } op->base.vectorcall = NULL; op->vectorcall = MethodDescriptor_vectorcall; return (PyObject *)op; } static PyTypeObject MethodDescriptor2_Type = { PyVarObject_HEAD_INIT(NULL, 0) "MethodDescriptor2", sizeof(MethodDescriptor2Object), .tp_new = MethodDescriptor2_new, .tp_call = PyVectorcall_Call, .tp_vectorcall_offset = offsetof(MethodDescriptor2Object, vectorcall), .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_VECTORCALL, }; int _PyTestCapi_Init_Vectorcall(PyObject *m) { if (PyModule_AddFunctions(m, TestMethods) < 0) { return -1; } if (PyType_Ready(&MethodDescriptorBase_Type) < 0) { return -1; } if (PyModule_AddType(m, &MethodDescriptorBase_Type) < 0) { return -1; } MethodDescriptorDerived_Type.tp_base = &MethodDescriptorBase_Type; if (PyType_Ready(&MethodDescriptorDerived_Type) < 0) { return -1; } if (PyModule_AddType(m, &MethodDescriptorDerived_Type) < 0) { return -1; } MethodDescriptorNopGet_Type.tp_base = &MethodDescriptorBase_Type; if (PyType_Ready(&MethodDescriptorNopGet_Type) < 0) { return -1; } if (PyModule_AddType(m, &MethodDescriptorNopGet_Type) < 0) { return -1; } MethodDescriptor2_Type.tp_base = &MethodDescriptorBase_Type; if (PyType_Ready(&MethodDescriptor2_Type) < 0) { return -1; } if (PyModule_AddType(m, &MethodDescriptor2_Type) < 0) { return -1; } return 0; }
c
github
https://github.com/python/cpython
Modules/_testcapi/vectorcall.c
import yaml import pytest import os from os import path import subprocess import tempfile import shutil import re import conda_skeletor from conda_skeletor import git def test_meta_generation(): data_path = path.join(path.dirname(__file__), 'data') projects_to_test = [path.join(data_path, folder) for folder in os.listdir(data_path)] for project_path in projects_to_test: yield meta_generator_helper, project_path def meta_generator_helper(data_path): # set up target_as_dict = safe_yaml_read(path.join(data_path, 'target.meta.yaml')) with open(path.join(data_path, 'target.meta.yaml'), 'r') as f: target_as_string = f.read() skeletor_config_path = path.join(data_path, 'conda-skeletor.yml') print('skeletor_config_path: %s' % skeletor_config_path) git_url = target_as_dict['source']['git_url'] git_rev = target_as_dict['source']['git_rev'] # clone the repo to a temporary directory source_dir = git.clone(git_url, git_rev) git.checkout(git_rev, source_dir) # run tests programmatic_path = generate_programmatically(source_dir, skeletor_config_path) programmatic_yaml_path = os.path.join(programmatic_path, 'meta.yaml') assert safe_yaml_read(programmatic_yaml_path) == target_as_dict with open(programmatic_yaml_path, 'r') as f: programmatic_text = f.read() assert programmatic_text == target_as_string cli_path = generate_cli_local_source(source_dir, skeletor_config_path) cli_yaml_path = os.path.join(cli_path, 'meta.yaml') assert safe_yaml_read(cli_yaml_path) == target_as_dict with open(cli_yaml_path, 'r') as f: cli_text = f.read() assert cli_text == target_as_string # tear down shutil.rmtree(cli_path) shutil.rmtree(programmatic_path) shutil.rmtree(source_dir) def generate_programmatically(source_dir, skeletor_config_path): output_dir = tempfile.mkdtemp() conda_skeletor.execute_programmatically( skeletor_config_path, source_dir, output_dir) return output_dir def generate_cli_local_source(source_dir, skeletor_config_path): output_dir = tempfile.mkdtemp() subprocess.call(['conda-skeletor', '--skeletor-config', skeletor_config_path, '--output-dir', output_dir, '-p', source_dir]) return output_dir def safe_yaml_read(fpath, replace_str=''): """ Reads a yaml file stripping all of the jinja templating markup Parameters ---------- fpath : str Path to yaml file to sanitize replace_str : str String to replace the template markup with, defaults to ''. Returns ------- yaml_dict : dict The dictionary with all of the jinja2 templating fields replaced with ``replace_str``. """ with open(fpath, 'r') as f: lns = [] for ln in f: lns.append(re.sub(r'{[{%].*?[%}]}', '', ln)) meta_dict = yaml.load(''.join(lns)) return meta_dict
unknown
codeparrot/codeparrot-clean
//// [tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression3_es2017.ts] //// //// [awaitCallExpression3_es2017.ts] declare var a: boolean; declare var p: Promise<boolean>; declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; declare function before(): void; declare function after(): void; async function func(): Promise<void> { before(); var b = fn(a, await p, a); after(); } //// [awaitCallExpression3_es2017.js] "use strict"; async function func() { before(); var b = fn(a, await p, a); after(); }
javascript
github
https://github.com/microsoft/TypeScript
tests/baselines/reference/awaitCallExpression3_es2017.js
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # 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. """Contains functions to define flags and params. Calling a DEFINE_* function will add a ParamSpec namedtuple to the param_spec dict. The DEFINE_* arguments match those in absl. Calling define_flags() creates a command-line flag for every ParamSpec defined by a DEFINE_* functions. The reason we don't use absl flags directly is that we want to be able to use tf_cnn_benchmarks as a library. When using it as a library, we don't want to define any flags, but instead pass parameters to the BenchmarkCNN constructor. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import namedtuple from absl import flags as absl_flags import six FLAGS = absl_flags.FLAGS # ParamSpec describes one of benchmark_cnn.BenchmarkCNN's parameters. ParamSpec = namedtuple('_ParamSpec', ['flag_type', 'default_value', 'description', 'kwargs']) # Maps from parameter name to its ParamSpec. param_specs = {} def DEFINE_string(name, default, help): # pylint: disable=invalid-name,redefined-builtin param_specs[name] = ParamSpec('string', default, help, {}) def DEFINE_boolean(name, default, help): # pylint: disable=invalid-name,redefined-builtin param_specs[name] = ParamSpec('boolean', default, help, {}) def DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None): # pylint: disable=invalid-name,redefined-builtin kwargs = {'lower_bound': lower_bound, 'upper_bound': upper_bound} param_specs[name] = ParamSpec('integer', default, help, kwargs) def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None): # pylint: disable=invalid-name,redefined-builtin kwargs = {'lower_bound': lower_bound, 'upper_bound': upper_bound} param_specs[name] = ParamSpec('float', default, help, kwargs) def DEFINE_enum(name, default, enum_values, help): # pylint: disable=invalid-name,redefined-builtin kwargs = {'enum_values': enum_values} param_specs[name] = ParamSpec('enum', default, help, kwargs) def DEFINE_list(name, default, help): # pylint: disable=invalid-name,redefined-builtin param_specs[name] = ParamSpec('list', default, help, {}) def define_flags(specs=None): """Define a command line flag for each ParamSpec in flags.param_specs.""" specs = specs or param_specs define_flag = { 'boolean': absl_flags.DEFINE_boolean, 'float': absl_flags.DEFINE_float, 'integer': absl_flags.DEFINE_integer, 'string': absl_flags.DEFINE_string, 'enum': absl_flags.DEFINE_enum, 'list': absl_flags.DEFINE_list } for name, param_spec in six.iteritems(specs): if param_spec.flag_type not in define_flag: raise ValueError('Unknown flag_type %s' % param_spec.flag_type) else: define_flag[param_spec.flag_type](name, param_spec.default_value, help=param_spec.description, **param_spec.kwargs)
unknown
codeparrot/codeparrot-clean
//// [tests/cases/conformance/async/es6/asyncSetter_es6.ts] //// //// [asyncSetter_es6.ts] class C { async set foo(value) { } } //// [asyncSetter_es6.js] "use strict"; class C { set foo(value) { } }
javascript
github
https://github.com/microsoft/TypeScript
tests/baselines/reference/asyncSetter_es6.js
import datetime from collections import defaultdict from django.contrib.auth.models import User from django.shortcuts import render from django.utils import timezone from django.db.models import Sum from django.template.defaultfilters import filesizeformat from jsonview.decorators import json_view from airmozilla.main.models import ( Event, SuggestedEvent, Picture, EventRevision, Chapter, ) from airmozilla.starred.models import StarredEvent from airmozilla.comments.models import Comment from airmozilla.uploads.models import Upload from .decorators import staff_required @staff_required def dashboard(request): """Management home / explanation page.""" return render(request, 'manage/dashboard.html') @staff_required @json_view def dashboard_data(request): context = {} now = timezone.now() today = now.replace(hour=0, minute=0, second=0, microsecond=0) tomorrow = today + datetime.timedelta(days=1) yesterday = today - datetime.timedelta(days=1) this_week = today - datetime.timedelta(days=today.weekday()) next_week = this_week + datetime.timedelta(days=7) last_week = this_week - datetime.timedelta(days=7) this_month = today.replace(day=1) next_month = this_month while next_month.month == this_month.month: next_month += datetime.timedelta(days=1) last_month = (this_month - datetime.timedelta(days=1)).replace(day=1) this_year = this_month.replace(month=1) next_year = this_year.replace(year=this_year.year + 1) last_year = this_year.replace(year=this_year.year - 1) context['groups'] = [] def make_filter(key, gte=None, lt=None): filter = {} if gte is not None: filter['%s__gte' % key] = gte if lt is not None: filter['%s__lt' % key] = lt return filter def get_counts(qs, key): counts = {} counts['today'] = qs.filter( **make_filter(key, gte=today, lt=tomorrow) ).count() counts['yesterday'] = qs.filter( **make_filter(key, gte=yesterday, lt=today)).count() counts['this_week'] = qs.filter( **make_filter(key, gte=this_week, lt=next_week)).count() counts['last_week'] = qs.filter( **make_filter(key, gte=last_week, lt=this_week)).count() counts['this_month'] = qs.filter( **make_filter(key, gte=this_month, lt=next_month)).count() counts['last_month'] = qs.filter( **make_filter(key, gte=last_month, lt=this_month)).count() counts['this_year'] = qs.filter( **make_filter(key, gte=this_year, lt=next_year)).count() counts['last_year'] = qs.filter( **make_filter(key, gte=last_year, lt=this_year)).count() counts['ever'] = qs.count() return counts # Events events = Event.objects.exclude(status=Event.STATUS_REMOVED) counts = get_counts(events, 'start_time') context['groups'].append({ 'name': 'New Events', 'counts': counts }) # Suggested Events counts = get_counts(SuggestedEvent.objects.all(), 'created') context['groups'].append({ 'name': 'Requested Events', 'counts': counts }) # Users counts = get_counts(User.objects.all(), 'date_joined') context['groups'].append({ 'name': 'New Users', 'counts': counts }) # Comments counts = get_counts(Comment.objects.all(), 'created') context['groups'].append({ 'name': 'Comments', 'counts': counts }) # Event revisions counts = get_counts(EventRevision.objects.all(), 'created') context['groups'].append({ 'name': 'Event Revisions', 'counts': counts }) # Pictures counts = get_counts(Picture.objects.all(), 'created') context['groups'].append({ 'name': 'Pictures', 'counts': counts }) # Chapters counts = get_counts(Chapter.objects.all(), 'created') context['groups'].append({ 'name': 'Chapters', 'counts': counts }) # Starred events counts = get_counts(StarredEvent.objects.all(), 'created') context['groups'].append({ 'name': 'Starred events', 'counts': counts }) def get_duration_totals(qs, key='start_time'): # def make_filter(gte=None, lt=None): # filter = {} # if gte is not None: # filter['%s__gte' % key] = gte # if lt is not None: # filter['%s__lt' % key] = lt # return filter counts = {} def sum(elements): seconds = elements.aggregate(Sum('duration'))['duration__sum'] seconds = seconds or 0 # in case it's None minutes = seconds / 60 hours = minutes / 60 if hours > 1: return "%dh" % hours elif minutes > 1: return "%dm" % minutes return "%ds" % seconds counts['today'] = sum(qs.filter( **make_filter(key, gte=today))) counts['yesterday'] = sum(qs.filter( **make_filter(key, gte=yesterday, lt=today))) counts['this_week'] = sum(qs.filter( **make_filter(key, gte=this_week))) counts['last_week'] = sum(qs.filter( **make_filter(key, gte=last_week, lt=this_week))) counts['this_month'] = sum(qs.filter( **make_filter(key, gte=this_month))) counts['last_month'] = sum(qs.filter( **make_filter(key, gte=last_month, lt=this_month))) counts['this_year'] = sum(qs.filter( **make_filter(key, gte=this_year))) counts['last_year'] = sum(qs.filter( **make_filter(key, gte=last_year, lt=this_year))) counts['ever'] = sum(qs) return counts def get_size_totals(qs, key='created'): counts = {} def sum(elements): bytes = elements.aggregate(Sum('size'))['size__sum'] return filesizeformat(bytes) counts['today'] = sum(qs.filter( **make_filter(key, gte=today))) counts['yesterday'] = sum(qs.filter( **make_filter(key, gte=yesterday, lt=today))) counts['this_week'] = sum(qs.filter( **make_filter(key, gte=this_week))) counts['last_week'] = sum(qs.filter( **make_filter(key, gte=last_week, lt=this_week))) counts['this_month'] = sum(qs.filter( **make_filter(key, gte=this_month))) counts['last_month'] = sum(qs.filter( **make_filter(key, gte=last_month, lt=this_month))) counts['this_year'] = sum(qs.filter( **make_filter(key, gte=this_year))) counts['last_year'] = sum(qs.filter( **make_filter(key, gte=last_year, lt=this_year))) counts['ever'] = sum(qs) return counts # Exceptional counts = get_duration_totals(Event.objects.exclude(duration__isnull=True)) context['groups'].append({ 'name': 'Total Event Durations', 'counts': counts }) counts = get_size_totals(Upload.objects.all()) context['groups'].append({ 'name': 'Uploads', 'counts': counts, 'small': True }) return context @staff_required def dashboard_graphs(request): # pragma: no cover """experimental""" return render(request, 'manage/dashboard_graphs.html') @staff_required @json_view def dashboard_data_graphs(request): # pragma: no cover """experimental""" YEARS = 3 now = timezone.now() def get_events(years_back): first_date = datetime.datetime(now.year - years_back + 1, 1, 1) objects = ( Event.objects .filter(archive_time__lt=now) .filter(created__gt=first_date.replace(tzinfo=timezone.utc)) .order_by('created') ) buckets = {} for each in objects.values_list('created'): created, = each year = created.year if year not in buckets: buckets[year] = defaultdict(int) next_monday = created + datetime.timedelta( days=7 - created.weekday() ) key = next_monday.strftime('%Y-%m-%d') buckets[year][key] += 1 legends = sorted(buckets.keys()) last_year = legends[-1] def fake_year(date_str, year): return date_str.replace(str(year), str(last_year)) data = [] for year in legends: group = sorted( {'date': fake_year(k, year), 'value': v} for k, v in buckets[year].items() ) data.append(group) return { 'type': 'events', 'title': 'New Events', 'data': data, 'description': 'Number of added events per year', 'legends': legends, } def get_revisions(years_back): first_date = datetime.datetime(now.year - years_back + 1, 1, 1) objects = ( EventRevision.objects .filter(created__gt=first_date.replace(tzinfo=timezone.utc)) .order_by('created') ) buckets = {} for each in objects.values_list('created'): created, = each year = created.year if year not in buckets: buckets[year] = defaultdict(int) next_monday = created + datetime.timedelta( days=7 - created.weekday() ) key = next_monday.strftime('%Y-%m-%d') buckets[year][key] += 1 legends = sorted(buckets.keys()) last_year = legends[-1] def fake_year(date_str, year): return date_str.replace(str(year), str(last_year)) data = [] for year in legends: group = sorted( {'date': fake_year(k, year), 'value': v} for k, v in buckets[year].items() ) data.append(group) return { 'type': 'revisions', 'title': 'Event Revisions', 'data': data, 'description': 'Number of event edits per year', 'legends': legends, } def get_users(years_back): first_date = datetime.datetime(now.year - years_back + 1, 1, 1) objects = ( User.objects .filter(date_joined__gt=first_date.replace(tzinfo=timezone.utc)) .order_by('date_joined') ) buckets = {} for each in objects.values_list('date_joined'): created, = each year = created.year if year not in buckets: buckets[year] = defaultdict(int) next_monday = created + datetime.timedelta( days=7 - created.weekday() ) key = next_monday.strftime('%Y-%m-%d') buckets[year][key] += 1 legends = sorted(buckets.keys()) last_year = legends[-1] def fake_year(date_str, year): return date_str.replace(str(year), str(last_year)) data = [] for year in legends: group = sorted( {'date': fake_year(k, year), 'value': v} for k, v in buckets[year].items() ) data.append(group) return { 'type': 'users', 'title': 'New Users', 'data': data, 'description': 'Number of first joining users per year', 'legends': legends, } groups = [] groups.append(get_events(YEARS)) groups.append(get_users(YEARS)) groups.append(get_revisions(2)) return {'groups': groups}
unknown
codeparrot/codeparrot-clean