repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
rynomster/django
refs/heads/master
tests/invalid_models_tests/test_deprecated_fields.py
51
from django.core import checks from django.db import models from django.test import SimpleTestCase from django.test.utils import isolate_apps @isolate_apps('invalid_models_tests') class DeprecatedFieldsTests(SimpleTestCase): def test_IPAddressField_deprecated(self): class IPAddressModel(models.Model): ip = models.IPAddressField() model = IPAddressModel() self.assertEqual( model.check(), [checks.Error( 'IPAddressField has been removed except for support in ' 'historical migrations.', hint='Use GenericIPAddressField instead.', obj=IPAddressModel._meta.get_field('ip'), id='fields.E900', )], ) def test_CommaSeparatedIntegerField_deprecated(self): class CommaSeparatedIntegerModel(models.Model): csi = models.CommaSeparatedIntegerField(max_length=64) model = CommaSeparatedIntegerModel() self.assertEqual( model.check(), [checks.Warning( 'CommaSeparatedIntegerField has been deprecated. Support ' 'for it (except in historical migrations) will be removed ' 'in Django 2.0.', hint='Use CharField(validators=[validate_comma_separated_integer_list]) instead.', obj=CommaSeparatedIntegerModel._meta.get_field('csi'), id='fields.W901', )], )
renner/spacewalk
refs/heads/master
backend/server/action_extra_data/__init__.py
14
# # Copyright (c) 2008--2015 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 # along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. # # Red Hat trademarks are not licensed under GPLv2. No permission is # granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation.
sdcooke/django
refs/heads/master
django/db/migrations/executor.py
170
from __future__ import unicode_literals from django.apps.registry import apps as global_apps from django.db import migrations from .loader import MigrationLoader from .recorder import MigrationRecorder from .state import ProjectState class MigrationExecutor(object): """ End-to-end migration execution - loads migrations, and runs them up or down to a specified set of targets. """ def __init__(self, connection, progress_callback=None): self.connection = connection self.loader = MigrationLoader(self.connection) self.recorder = MigrationRecorder(self.connection) self.progress_callback = progress_callback def migration_plan(self, targets, clean_start=False): """ Given a set of targets, returns a list of (Migration instance, backwards?). """ plan = [] if clean_start: applied = set() else: applied = set(self.loader.applied_migrations) for target in targets: # If the target is (app_label, None), that means unmigrate everything if target[1] is None: for root in self.loader.graph.root_nodes(): if root[0] == target[0]: for migration in self.loader.graph.backwards_plan(root): if migration in applied: plan.append((self.loader.graph.nodes[migration], True)) applied.remove(migration) # If the migration is already applied, do backwards mode, # otherwise do forwards mode. elif target in applied: # Don't migrate backwards all the way to the target node (that # may roll back dependencies in other apps that don't need to # be rolled back); instead roll back through target's immediate # child(ren) in the same app, and no further. next_in_app = sorted( n for n in self.loader.graph.node_map[target].children if n[0] == target[0] ) for node in next_in_app: for migration in self.loader.graph.backwards_plan(node): if migration in applied: plan.append((self.loader.graph.nodes[migration], True)) applied.remove(migration) else: for migration in self.loader.graph.forwards_plan(target): if migration not in applied: plan.append((self.loader.graph.nodes[migration], False)) applied.add(migration) return plan def migrate(self, targets, plan=None, fake=False, fake_initial=False): """ Migrates the database up to the given targets. Django first needs to create all project states before a migration is (un)applied and in a second step run all the database operations. """ if plan is None: plan = self.migration_plan(targets) migrations_to_run = {m[0] for m in plan} # Create the forwards plan Django would follow on an empty database full_plan = self.migration_plan(self.loader.graph.leaf_nodes(), clean_start=True) # Holds all states right before a migration is applied # if the migration is being run. states = {} state = ProjectState(real_apps=list(self.loader.unmigrated_apps)) if self.progress_callback: self.progress_callback("render_start") # Phase 1 -- Store all project states of migrations right before they # are applied. The first migration that will be applied in phase 2 will # trigger the rendering of the initial project state. From this time on # models will be recursively reloaded as explained in # `django.db.migrations.state.get_related_models_recursive()`. for migration, _ in full_plan: if not migrations_to_run: # We remove every migration whose state was already computed # from the set below (`migrations_to_run.remove(migration)`). # If no states for migrations must be computed, we can exit # this loop. Migrations that occur after the latest migration # that is about to be applied would only trigger unneeded # mutate_state() calls. break do_run = migration in migrations_to_run if do_run: if 'apps' not in state.__dict__: state.apps # Render all real_apps -- performance critical states[migration] = state.clone() migrations_to_run.remove(migration) # Only preserve the state if the migration is being run later state = migration.mutate_state(state, preserve=do_run) if self.progress_callback: self.progress_callback("render_success") # Phase 2 -- Run the migrations for migration, backwards in plan: if not backwards: self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) else: self.unapply_migration(states[migration], migration, fake=fake) self.check_replacements() def collect_sql(self, plan): """ Takes a migration plan and returns a list of collected SQL statements that represent the best-efforts version of that plan. """ statements = [] state = None for migration, backwards in plan: with self.connection.schema_editor(collect_sql=True) as schema_editor: if state is None: state = self.loader.project_state((migration.app_label, migration.name), at_end=False) if not backwards: state = migration.apply(state, schema_editor, collect_sql=True) else: state = migration.unapply(state, schema_editor, collect_sql=True) statements.extend(schema_editor.collected_sql) return statements def apply_migration(self, state, migration, fake=False, fake_initial=False): """ Runs a migration forwards. """ if self.progress_callback: self.progress_callback("apply_start", migration, fake) if not fake: if fake_initial: # Test to see if this is an already-applied initial migration applied, state = self.detect_soft_applied(state, migration) if applied: fake = True if not fake: # Alright, do it normally with self.connection.schema_editor() as schema_editor: state = migration.apply(state, schema_editor) # For replacement migrations, record individual statuses if migration.replaces: for app_label, name in migration.replaces: self.recorder.record_applied(app_label, name) else: self.recorder.record_applied(migration.app_label, migration.name) # Report progress if self.progress_callback: self.progress_callback("apply_success", migration, fake) return state def unapply_migration(self, state, migration, fake=False): """ Runs a migration backwards. """ if self.progress_callback: self.progress_callback("unapply_start", migration, fake) if not fake: with self.connection.schema_editor() as schema_editor: state = migration.unapply(state, schema_editor) # For replacement migrations, record individual statuses if migration.replaces: for app_label, name in migration.replaces: self.recorder.record_unapplied(app_label, name) else: self.recorder.record_unapplied(migration.app_label, migration.name) # Report progress if self.progress_callback: self.progress_callback("unapply_success", migration, fake) return state def check_replacements(self): """ Mark replacement migrations applied if their replaced set all are. We do this unconditionally on every migrate, rather than just when migrations are applied or unapplied, so as to correctly handle the case when a new squash migration is pushed to a deployment that already had all its replaced migrations applied. In this case no new migration will be applied, but we still want to correctly maintain the applied state of the squash migration. """ applied = self.recorder.applied_migrations() for key, migration in self.loader.replacements.items(): all_applied = all(m in applied for m in migration.replaces) if all_applied and key not in applied: self.recorder.record_applied(*key) def detect_soft_applied(self, project_state, migration): """ Tests whether a migration has been implicitly applied - that the tables or columns it would create exist. This is intended only for use on initial migrations (as it only looks for CreateModel and AddField). """ if migration.initial is None: # Bail if the migration isn't the first one in its app if any(app == migration.app_label for app, name in migration.dependencies): return False, project_state elif migration.initial is False: # Bail if it's NOT an initial migration return False, project_state if project_state is None: after_state = self.loader.project_state((migration.app_label, migration.name), at_end=True) else: after_state = migration.mutate_state(project_state) apps = after_state.apps found_create_model_migration = False found_add_field_migration = False # Make sure all create model and add field operations are done for operation in migration.operations: if isinstance(operation, migrations.CreateModel): model = apps.get_model(migration.app_label, operation.name) if model._meta.swapped: # We have to fetch the model to test with from the # main app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if model._meta.proxy or not model._meta.managed: continue if model._meta.db_table not in self.connection.introspection.table_names(self.connection.cursor()): return False, project_state found_create_model_migration = True elif isinstance(operation, migrations.AddField): model = apps.get_model(migration.app_label, operation.model_name) if model._meta.swapped: # We have to fetch the model to test with from the # main app cache, as it's not a direct dependency. model = global_apps.get_model(model._meta.swapped) if model._meta.proxy or not model._meta.managed: continue table = model._meta.db_table db_field = model._meta.get_field(operation.name).column fields = self.connection.introspection.get_table_description(self.connection.cursor(), table) if db_field not in (f.name for f in fields): return False, project_state found_add_field_migration = True # If we get this far and we found at least one CreateModel or AddField migration, # the migration is considered implicitly applied. return (found_create_model_migration or found_add_field_migration), after_state
sebastian-code/system_overview
refs/heads/master
net_stat.py
1
#!/usr/bin/env python # # Copyright (c) 2010-2013 Corey Goldberg (http://goldb.org) # # This file is part of linux-metrics # # License :: OSI Approved :: MIT License: # http://www.opensource.org/licenses/mit-license # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # """ net_stat - Python Module for Network Stats on Linux requires: - Python 2.6+ - Linux 2.6+ """ import re import subprocess def rx_tx_bytes(interface): # by reading /proc for line in open('/proc/net/dev'): if interface in line: data = line.split('%s:' % interface)[1].split() rx_bytes, tx_bytes = (int(data[0]), int(data[8])) return (rx_bytes, tx_bytes) raise NetError('interface not found: %r' % interface) def rx_tx_bits(interface): # by reading /proc rx_bytes, tx_bytes = rx_tx_bytes(interface) rx_bits = rx_bytes * 8 tx_bits = tx_bytes * 8 return (rx_bits, tx_bits) def rx_tx_dump(interface): # get all info for line in open('/proc/net/dev'): if interface in line: data = line.split('%s:' % interface)[1].split() rx, tx = [int(x) for x in data[0:8]], [int(x) for x in data[8:]] return (rx, tx) def net_stats_ifconfig(interface): # by parsing ifconfig output output = subprocess.Popen(['ifconfig', interface], stdout=subprocess.PIPE).communicate()[0] rx_bytes = int(re.findall('RX bytes:([0-9]*) ', output)[0]) tx_bytes = int(re.findall('TX bytes:([0-9]*) ', output)[0]) return (rx_bytes, tx_bytes) class NetError(Exception): pass
rahul67/hue
refs/heads/master
desktop/core/ext-py/python-ldap-2.3.13/Lib/ldif.py
44
""" ldif - generate and parse LDIF data (see RFC 2849) See http://www.python-ldap.org/ for details. $Id: ldif.py,v 1.56 2010/07/19 08:23:22 stroeder Exp $ Python compability note: Tested with Python 2.0+, but should work with Python 1.5.2+. """ __version__ = '2.3.12' __all__ = [ # constants 'ldif_pattern', # functions 'AttrTypeandValueLDIF','CreateLDIF','ParseLDIF', # classes 'LDIFWriter', 'LDIFParser', 'LDIFRecordList', 'LDIFCopy', ] import urlparse,urllib,base64,re,types try: from cStringIO import StringIO except ImportError: from StringIO import StringIO attrtype_pattern = r'[\w;.-]+(;[\w_-]+)*' attrvalue_pattern = r'(([^,]|\\,)+|".*?")' attrtypeandvalue_pattern = attrtype_pattern + r'[ ]*=[ ]*' + attrvalue_pattern rdn_pattern = attrtypeandvalue_pattern + r'([ ]*\+[ ]*' + attrtypeandvalue_pattern + r')*[ ]*' dn_pattern = rdn_pattern + r'([ ]*,[ ]*' + rdn_pattern + r')*[ ]*' dn_regex = re.compile('^%s$' % dn_pattern) ldif_pattern = '^((dn(:|::) %(dn_pattern)s)|(%(attrtype_pattern)s(:|::) .*)$)+' % vars() MOD_OP_INTEGER = { 'add':0,'delete':1,'replace':2 } MOD_OP_STR = { 0:'add',1:'delete',2:'replace' } CHANGE_TYPES = ['add','delete','modify','modrdn'] valid_changetype_dict = {} for c in CHANGE_TYPES: valid_changetype_dict[c]=None def is_dn(s): """ returns 1 if s is a LDAP DN """ if s=='': return 1 rm = dn_regex.match(s) return rm!=None and rm.group(0)==s SAFE_STRING_PATTERN = '(^(\000|\n|\r| |:|<)|[\000\n\r\200-\377]+|[ ]+$)' safe_string_re = re.compile(SAFE_STRING_PATTERN) def list_dict(l): """ return a dictionary with all items of l being the keys of the dictionary """ return dict([(i,None) for i in l]) class LDIFWriter: """ Write LDIF entry or change records to file object Copy LDIF input to a file output object containing all data retrieved via URLs """ def __init__(self,output_file,base64_attrs=None,cols=76,line_sep='\n'): """ output_file file object for output base64_attrs list of attribute types to be base64-encoded in any case cols Specifies how many columns a line may have before it's folded into many lines. line_sep String used as line separator """ self._output_file = output_file self._base64_attrs = list_dict([a.lower() for a in (base64_attrs or [])]) self._cols = cols self._line_sep = line_sep self.records_written = 0 def _unfoldLDIFLine(self,line): """ Write string line as one or more folded lines """ # Check maximum line length line_len = len(line) if line_len<=self._cols: self._output_file.write(line) self._output_file.write(self._line_sep) else: # Fold line pos = self._cols self._output_file.write(line[0:min(line_len,self._cols)]) self._output_file.write(self._line_sep) while pos<line_len: self._output_file.write(' ') self._output_file.write(line[pos:min(line_len,pos+self._cols-1)]) self._output_file.write(self._line_sep) pos = pos+self._cols-1 return # _unfoldLDIFLine() def _needs_base64_encoding(self,attr_type,attr_value): """ returns 1 if attr_value has to be base-64 encoded because of special chars or because attr_type is in self._base64_attrs """ return self._base64_attrs.has_key(attr_type.lower()) or \ not safe_string_re.search(attr_value) is None def _unparseAttrTypeandValue(self,attr_type,attr_value): """ Write a single attribute type/value pair attr_type attribute type attr_value attribute value """ if self._needs_base64_encoding(attr_type,attr_value): # Encode with base64 self._unfoldLDIFLine(':: '.join([attr_type,base64.encodestring(attr_value).replace('\n','')])) else: self._unfoldLDIFLine(': '.join([attr_type,attr_value])) return # _unparseAttrTypeandValue() def _unparseEntryRecord(self,entry): """ entry dictionary holding an entry """ attr_types = entry.keys()[:] attr_types.sort() for attr_type in attr_types: for attr_value in entry[attr_type]: self._unparseAttrTypeandValue(attr_type,attr_value) def _unparseChangeRecord(self,modlist): """ modlist list of additions (2-tuple) or modifications (3-tuple) """ mod_len = len(modlist[0]) if mod_len==2: changetype = 'add' elif mod_len==3: changetype = 'modify' else: raise ValueError,"modlist item of wrong length" self._unparseAttrTypeandValue('changetype',changetype) for mod in modlist: if mod_len==2: mod_type,mod_vals = mod elif mod_len==3: mod_op,mod_type,mod_vals = mod self._unparseAttrTypeandValue(MOD_OP_STR[mod_op],mod_type) else: raise ValueError,"Subsequent modlist item of wrong length" if mod_vals: for mod_val in mod_vals: self._unparseAttrTypeandValue(mod_type,mod_val) if mod_len==3: self._output_file.write('-'+self._line_sep) def unparse(self,dn,record): """ dn string-representation of distinguished name record Either a dictionary holding the LDAP entry {attrtype:record} or a list with a modify list like for LDAPObject.modify(). """ if not record: # Simply ignore empty records return # Start with line containing the distinguished name self._unparseAttrTypeandValue('dn',dn) # Dispatch to record type specific writers if isinstance(record,types.DictType): self._unparseEntryRecord(record) elif isinstance(record,types.ListType): self._unparseChangeRecord(record) else: raise ValueError, "Argument record must be dictionary or list" # Write empty line separating the records self._output_file.write(self._line_sep) # Count records written self.records_written = self.records_written+1 return # unparse() def CreateLDIF(dn,record,base64_attrs=None,cols=76): """ Create LDIF single formatted record including trailing empty line. This is a compability function. Use is deprecated! dn string-representation of distinguished name record Either a dictionary holding the LDAP entry {attrtype:record} or a list with a modify list like for LDAPObject.modify(). base64_attrs list of attribute types to be base64-encoded in any case cols Specifies how many columns a line may have before it's folded into many lines. """ f = StringIO() ldif_writer = LDIFWriter(f,base64_attrs,cols,'\n') ldif_writer.unparse(dn,record) s = f.getvalue() f.close() return s class LDIFParser: """ Base class for a LDIF parser. Applications should sub-class this class and override method handle() to implement something meaningful. Public class attributes: records_read Counter for records processed so far """ def _stripLineSep(self,s): """ Strip trailing line separators from s, but no other whitespaces """ if s[-2:]=='\r\n': return s[:-2] elif s[-1:]=='\n': return s[:-1] else: return s def __init__( self, input_file, ignored_attr_types=None, max_entries=0, process_url_schemes=None, line_sep='\n' ): """ Parameters: input_file File-object to read the LDIF input from ignored_attr_types Attributes with these attribute type names will be ignored. max_entries If non-zero specifies the maximum number of entries to be read from f. process_url_schemes List containing strings with URLs schemes to process with urllib. An empty list turns off all URL processing and the attribute is ignored completely. line_sep String used as line separator """ self._input_file = input_file self._max_entries = max_entries self._process_url_schemes = list_dict([s.lower() for s in (process_url_schemes or [])]) self._ignored_attr_types = list_dict([a.lower() for a in (ignored_attr_types or [])]) self._line_sep = line_sep self.records_read = 0 def handle(self,dn,entry): """ Process a single content LDIF record. This method should be implemented by applications using LDIFParser. """ def _unfoldLDIFLine(self): """ Unfold several folded lines with trailing space into one line """ unfolded_lines = [ self._stripLineSep(self._line) ] self._line = self._input_file.readline() while self._line and self._line[0]==' ': unfolded_lines.append(self._stripLineSep(self._line[1:])) self._line = self._input_file.readline() return ''.join(unfolded_lines) def _parseAttrTypeandValue(self): """ Parse a single attribute type and value pair from one or more lines of LDIF data """ # Reading new attribute line unfolded_line = self._unfoldLDIFLine() # Ignore comments which can also be folded while unfolded_line and unfolded_line[0]=='#': unfolded_line = self._unfoldLDIFLine() if not unfolded_line or unfolded_line=='\n' or unfolded_line=='\r\n': return None,None try: colon_pos = unfolded_line.index(':') except ValueError: # Treat malformed lines without colon as non-existent return None,None attr_type = unfolded_line[0:colon_pos] # if needed attribute value is BASE64 decoded value_spec = unfolded_line[colon_pos:colon_pos+2] if value_spec=='::': # attribute value needs base64-decoding attr_value = base64.decodestring(unfolded_line[colon_pos+2:]) elif value_spec==':<': # fetch attribute value from URL url = unfolded_line[colon_pos+2:].strip() attr_value = None if self._process_url_schemes: u = urlparse.urlparse(url) if self._process_url_schemes.has_key(u[0]): attr_value = urllib.urlopen(url).read() elif value_spec==':\r\n' or value_spec=='\n': attr_value = '' else: attr_value = unfolded_line[colon_pos+2:].lstrip() return attr_type,attr_value def parse(self): """ Continously read and parse LDIF records """ self._line = self._input_file.readline() while self._line and \ (not self._max_entries or self.records_read<self._max_entries): # Reset record version = None; dn = None; changetype = None; modop = None; entry = {} attr_type,attr_value = self._parseAttrTypeandValue() while attr_type!=None and attr_value!=None: if attr_type=='dn': # attr type and value pair was DN of LDIF record if dn!=None: raise ValueError, 'Two lines starting with dn: in one record.' if not is_dn(attr_value): raise ValueError, 'No valid string-representation of distinguished name %s.' % (repr(attr_value)) dn = attr_value elif attr_type=='version' and dn is None: version = 1 elif attr_type=='changetype': # attr type and value pair was DN of LDIF record if dn is None: raise ValueError, 'Read changetype: before getting valid dn: line.' if changetype!=None: raise ValueError, 'Two lines starting with changetype: in one record.' if not valid_changetype_dict.has_key(attr_value): raise ValueError, 'changetype value %s is invalid.' % (repr(attr_value)) changetype = attr_value elif attr_value!=None and \ not self._ignored_attr_types.has_key(attr_type.lower()): # Add the attribute to the entry if not ignored attribute if entry.has_key(attr_type): entry[attr_type].append(attr_value) else: entry[attr_type]=[attr_value] # Read the next line within an entry attr_type,attr_value = self._parseAttrTypeandValue() if entry: # append entry to result list self.handle(dn,entry) self.records_read = self.records_read+1 return # parse() class LDIFRecordList(LDIFParser): """ Collect all records of LDIF input into a single list. of 2-tuples (dn,entry). It can be a memory hog! """ def __init__( self, input_file, ignored_attr_types=None,max_entries=0,process_url_schemes=None ): """ See LDIFParser.__init__() Additional Parameters: all_records List instance for storing parsed records """ LDIFParser.__init__(self,input_file,ignored_attr_types,max_entries,process_url_schemes) self.all_records = [] def handle(self,dn,entry): """ Append single record to dictionary of all records. """ self.all_records.append((dn,entry)) class LDIFCopy(LDIFParser): """ Copy LDIF input to LDIF output containing all data retrieved via URLs """ def __init__( self, input_file,output_file, ignored_attr_types=None,max_entries=0,process_url_schemes=None, base64_attrs=None,cols=76,line_sep='\n' ): """ See LDIFParser.__init__() and LDIFWriter.__init__() """ LDIFParser.__init__(self,input_file,ignored_attr_types,max_entries,process_url_schemes) self._output_ldif = LDIFWriter(output_file,base64_attrs,cols,line_sep) def handle(self,dn,entry): """ Write single LDIF record to output file. """ self._output_ldif.unparse(dn,entry) def ParseLDIF(f,ignore_attrs=None,maxentries=0): """ Parse LDIF records read from file. This is a compability function. Use is deprecated! """ ldif_parser = LDIFRecordList( f,ignored_attr_types=ignore_attrs,max_entries=maxentries,process_url_schemes=0 ) ldif_parser.parse() return ldif_parser.all_records
xuqingkuang/tsCloud
refs/heads/master
tsCloud/ad/tests.py
1
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase from django.test.client import Client from django.core.urlresolvers import reverse from django.utils import simplejson from tsCloud.ctauth.middleware import username_field, token_field import models client = Client() class UpdateTest(TestCase): username = '18910975586' token = 'abcdefghijklmnopqrst' def test_update_user_category(self): """ Tests that 1 + 1 always equals 2. """ # ================================================= # Preparation # ================================================= # Create user for testing response = client.post( reverse('tsCloud.ad.api.set_category'), { username_field: self.username, token_field: self.token, 'category_id': 2, } ) # Test response messages. json = simplejson.loads(response.content) # Test user category exist category = models.Category.objects.filter( user__username = self.username ) # ================================================= # Checking # ================================================= self.assertEqual(response.status_code, 200) self.assertEqual(json['res'], 0) self.assertEqual(category[0].pk, 2)
jonathonwalz/ansible
refs/heads/devel
test/integration/targets/module_utils/module_utils/sub/bam/bam.py
298
#!/usr/bin/env python bam = "BAM FROM sub/bam/bam.py"
turi-code/SFrame
refs/heads/master
oss_src/unity/python/doc/source/sphinx_graphlab_ext/__init__.py
15
import sframe
smmribeiro/intellij-community
refs/heads/master
python/testData/completion/privateMemberOwnerResolvedToStub/a.py
21
class Test: @classmethod def foo(cls): return cls._bar(), cls.__eg<caret> @staticmethod def _bar(): pass @staticmethod def __egg(): pass
dadisigursveinn/VEF-Lokaverkefni
refs/heads/master
photo/tests.py
24123
from django.test import TestCase # Create your tests here.
dan1/horizon-proto
refs/heads/master
openstack_dashboard/dashboards/admin/networks/tables.py
47
# Copyright 2012 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging from django.core.urlresolvers import reverse from django.template import defaultfilters as filters from django.utils.translation import pgettext_lazy from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ungettext_lazy from horizon import exceptions from horizon import tables from openstack_dashboard import api from openstack_dashboard.dashboards.project.networks \ import tables as project_tables from openstack_dashboard import policy LOG = logging.getLogger(__name__) class DeleteNetwork(policy.PolicyTargetMixin, tables.DeleteAction): @staticmethod def action_present(count): return ungettext_lazy( u"Delete Network", u"Delete Networks", count ) @staticmethod def action_past(count): return ungettext_lazy( u"Deleted Network", u"Deleted Networks", count ) policy_rules = (("network", "delete_network"),) def delete(self, request, obj_id): try: api.neutron.network_delete(request, obj_id) except Exception: msg = _('Failed to delete network %s') % obj_id LOG.info(msg) redirect = reverse('horizon:admin:networks:index') exceptions.handle(request, msg, redirect=redirect) class CreateNetwork(tables.LinkAction): name = "create" verbose_name = _("Create Network") url = "horizon:admin:networks:create" classes = ("ajax-modal",) icon = "plus" policy_rules = (("network", "create_network"),) class EditNetwork(policy.PolicyTargetMixin, tables.LinkAction): name = "update" verbose_name = _("Edit Network") url = "horizon:admin:networks:update" classes = ("ajax-modal",) icon = "pencil" policy_rules = (("network", "update_network"),) # def _get_subnets(network): # cidrs = [subnet.get('cidr') for subnet in network.subnets] # return ','.join(cidrs) DISPLAY_CHOICES = ( ("UP", pgettext_lazy("Admin state of a Network", u"UP")), ("DOWN", pgettext_lazy("Admin state of a Network", u"DOWN")), ) class NetworksTable(tables.DataTable): tenant = tables.Column("tenant_name", verbose_name=_("Project")) name = tables.Column("name_or_id", verbose_name=_("Network Name"), link='horizon:admin:networks:detail') subnets = tables.Column(project_tables.get_subnets, verbose_name=_("Subnets Associated"),) num_agents = tables.Column("num_agents", verbose_name=_("DHCP Agents")) shared = tables.Column("shared", verbose_name=_("Shared"), filters=(filters.yesno, filters.capfirst)) status = tables.Column( "status", verbose_name=_("Status"), display_choices=project_tables.STATUS_DISPLAY_CHOICES) admin_state = tables.Column("admin_state", verbose_name=_("Admin State"), display_choices=DISPLAY_CHOICES) class Meta(object): name = "networks" verbose_name = _("Networks") table_actions = (CreateNetwork, DeleteNetwork, project_tables.NetworksFilterAction) row_actions = (EditNetwork, DeleteNetwork) def __init__(self, request, data=None, needs_form_wrapper=None, **kwargs): super(NetworksTable, self).__init__( request, data=data, needs_form_wrapper=needs_form_wrapper, **kwargs) if not api.neutron.is_extension_supported(request, 'dhcp_agent_scheduler'): del self.columns['num_agents']
lencioni/ultisnips
refs/heads/master
plugin/UltiSnips/tests/test_geometry.py
4
#!/usr/bin/env python # encoding: utf-8 import unittest import os.path as p, sys; sys.path.append(p.join(p.dirname(__file__), "..")) from geometry import Position class _MPBase(object): def runTest(self): obj = Position(*self.obj) for pivot, diff, wanted in self.steps: obj.move(Position(*pivot), Position(*diff)) self.assertEqual(Position(*wanted), obj) class MovePosition_DelSameLine(_MPBase, unittest.TestCase): # hello wor*ld -> h*ld -> hl*ld obj = (0, 9) steps = ( ((0, 1), (0, -8), (0, 1)), ((0, 1), (0, 1), (0, 2)), ) class MovePosition_DelSameLine1(_MPBase, unittest.TestCase): # hel*lo world -> hel*world -> hel*worl obj = (0,3) steps = ( ((0, 4), (0, -3), (0,3)), ((0, 8), (0, -1), (0,3)), ) class MovePosition_InsSameLine1(_MPBase, unittest.TestCase): # hel*lo world -> hel*woresld obj = (0, 3) steps = ( ((0, 4), (0, -3), (0, 3)), ((0, 6), (0, 2), (0, 3)), ((0, 8), (0, -1), (0, 3)) ) class MovePosition_InsSameLine2(_MPBase, unittest.TestCase): # hello wor*ld -> helesdlo wor*ld obj = (0, 9) steps = ( ((0, 3), (0, 3), (0, 12)), ) class MovePosition_DelSecondLine(_MPBase, unittest.TestCase): # hello world. sup hello world.*a, was # *a, was ach nix # ach nix obj = (1, 0) steps = ( ((0, 12), (0, -4), (1, 0)), ((0, 12), (-1, 0), (0, 12)), ) class MovePosition_DelSecondLine1(_MPBase, unittest.TestCase): # hello world. sup # a, *was # ach nix # hello world.a*was # ach nix obj = (1, 3) steps = ( ((0, 12), (0, -4), (1, 3)), ((0, 12), (-1, 0), (0, 15)), ((0, 12), (0, -3), (0, 12)), ((0, 12), (0, 1), (0, 13)), ) if __name__ == '__main__': unittest.main()
vulcansteel/autorest
refs/heads/master
AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/auto_rest_url_test_service/operations/__init__.py
9
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .paths import Paths from .queries import Queries from .path_items import PathItems __all__ = [ 'Paths', 'Queries', 'PathItems', ]
AlessandroCorsi/fibermodes
refs/heads/master
fibermodesgui/modesolver/fiberselector.py
2
from PyQt4 import QtGui, QtCore import os from datetime import datetime from string import Template from fibermodesgui.fibereditor.mainwindow import FiberEditor class FiberSelector(QtGui.QFrame): fileLoaded = QtCore.pyqtSignal() fiberEdited = QtCore.pyqtSignal() def __init__(self, doc, parent, *args, **kwargs): super().__init__(parent, *args, **kwargs) self._doc = doc self._editWin = None self.fiberName = QtGui.QLabel(self.tr("<i>Select fiber...</i>")) self.fiberName.setTextFormat(QtCore.Qt.RichText) self.chooseButton = QtGui.QPushButton( parent.getIcon('document-open'), self.tr("Choose")) self.chooseButton.clicked.connect(self.chooseFiber) self.editButton = QtGui.QPushButton(parent.getIcon('document-new'), self.tr("New")) self.editButton.clicked.connect(self.editFiber) self.propButton = QtGui.QPushButton( parent.getIcon('info'), "") self.propButton.setEnabled(False) self.propButton.clicked.connect(self.fiberProperties) layout = QtGui.QHBoxLayout() layout.addWidget(self.fiberName) layout.addWidget(self.chooseButton) layout.addWidget(self.editButton) layout.addWidget(self.propButton) self.setLayout(layout) self.editIcon = parent.getIcon('pen') def updateFiberName(self): name = self._doc.factory.name if not name: name = os.path.basename(self._doc.filename) self.fiberName.setText(name) self.editButton.setText(self.tr("Edit")) self.editButton.setIcon(self.editIcon) self.propButton.setEnabled(True) def chooseFiber(self): dirname = (os.path.dirname(self._doc.filename) if self._doc.filename else os.getcwd()) openDialog = QtGui.QFileDialog() openDialog.setWindowTitle(self.tr("Open fiber...")) openDialog.setDirectory(dirname) openDialog.setAcceptMode(QtGui.QFileDialog.AcceptOpen) openDialog.setNameFilter(self.tr("Fibers (*.fiber)")) if openDialog.exec_() == QtGui.QFileDialog.Accepted: self._doc.filename = openDialog.selectedFiles()[0] self.fileLoaded.emit() def editFiber(self): if self._editWin is None: self._editWin = FiberEditor(self) self._editWin.closed.connect(self.editorClosed) if self._doc.filename: self._editWin.actionOpen(self._doc.filename) # self._editWin.setWindowModality(QtCore.Qt.WindowModal) self._editWin.saved.connect(self.updateFiber) self._editWin.show() self._editWin.raise_() def updateFiber(self, filename): self._doc.filename = filename self.fiberEdited.emit() def fiberProperties(self): propTemplate = Template(self.tr("""<table> <tr><th align="right">Filename: </th><td>$filename</td></tr> <tr><th align="right">Name: </th><td>$name</td></tr> <tr><th align="right">Author: </th><td>$author</td></tr> <tr><th align="right">Creation date: </th><td>$crdate</td></tr> <tr><th align="right">Modification date: </th><td>$tstamp</td></tr> <tr><th align="right">Description: </th><td>$description</td></tr> </table> """)).substitute(filename=os.path.relpath(self._doc.filename), name=self._doc.factory.name, author=self._doc.factory.author, crdate=datetime.fromtimestamp( self._doc.factory.crdate).strftime('%Y-%m-%d %H:%M:%S'), tstamp=datetime.fromtimestamp( self._doc.factory.tstamp).strftime('%Y-%m-%d %H:%M:%S'), description=self._doc.factory.description) msgBox = QtGui.QMessageBox() msgBox.setWindowTitle(self.tr("Fiber Properties")) msgBox.setText(propTemplate) msgBox.exec_() def editorClosed(self): self._editWin = None
aviciimaxwell/odoo
refs/heads/8.0
addons/stock/report/report_stock.py
376
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.sql import drop_view_if_exists class report_stock_lines_date(osv.osv): _name = "report.stock.lines.date" _description = "Dates of Inventories and latest Moves" _auto = False _order = "date" _columns = { 'id': fields.integer('Product Id', readonly=True), 'product_id': fields.many2one('product.product', 'Product', readonly=True, select=True), 'date': fields.datetime('Date of latest Inventory', readonly=True), 'move_date': fields.datetime('Date of latest Stock Move', readonly=True), "active": fields.boolean("Active", readonly=True), } def init(self, cr): drop_view_if_exists(cr, 'report_stock_lines_date') cr.execute(""" create or replace view report_stock_lines_date as ( select p.id as id, p.id as product_id, max(s.date) as date, max(m.date) as move_date, p.active as active from product_product p left join ( stock_inventory_line l inner join stock_inventory s on (l.inventory_id=s.id and s.state = 'done') ) on (p.id=l.product_id) left join stock_move m on (m.product_id=p.id and m.state = 'done') group by p.id )""") # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
mozilla/addons-server
refs/heads/master
src/olympia/scanners/migrations/0045_auto_20210604_1340.py
2
# Generated by Django 2.2.23 on 2021-06-04 13:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('scanners', '0044_auto_20210511_1256'), ] operations = [ migrations.AlterField( model_name='scannerqueryrule', name='action', field=models.PositiveSmallIntegerField( choices=[ (1, 'No action'), (20, 'Flag for human review'), (100, 'Delay auto-approval'), (200, 'Delay auto-approval indefinitely'), (300, 'Delay auto-approval indefinitely and add restrictions'), ( 400, 'Delay auto-approval indefinitely and add restrictions to future approvals', ), ], default=1, ), ), migrations.AlterField( model_name='scannerrule', name='action', field=models.PositiveSmallIntegerField( choices=[ (1, 'No action'), (20, 'Flag for human review'), (100, 'Delay auto-approval'), (200, 'Delay auto-approval indefinitely'), (300, 'Delay auto-approval indefinitely and add restrictions'), ( 400, 'Delay auto-approval indefinitely and add restrictions to future approvals', ), ], default=1, ), ), ]
li-xiao-nan/gyp_tools
refs/heads/master
test/compiler-override/gyptest-compiler-global-settings.py
137
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that make_global_settings can be used to override the compiler settings. """ import TestGyp import os import copy import sys from string import Template if sys.platform == 'win32': # cross compiling not support by ninja on windows # and make not supported on windows at all. sys.exit(0) test = TestGyp.TestGyp(formats=['ninja', 'make']) gypfile = 'compiler-global-settings.gyp' replacements = { 'PYTHON': '/usr/bin/python', 'PWD': os.getcwd()} # Process the .in gyp file to produce the final gyp file # since we need to include absolute paths in the make_global_settings # section. replacements['TOOLSET'] = 'target' s = Template(open(gypfile + '.in').read()) output = open(gypfile, 'w') output.write(s.substitute(replacements)) output.close() old_env = dict(os.environ) os.environ['GYP_CROSSCOMPILE'] = '1' test.run_gyp(gypfile) os.environ.clear() os.environ.update(old_env) test.build(gypfile) test.must_contain_all_lines(test.stdout(), ['my_cc.py', 'my_cxx.py', 'FOO']) # Same again but with the host toolset. replacements['TOOLSET'] = 'host' s = Template(open(gypfile + '.in').read()) output = open(gypfile, 'w') output.write(s.substitute(replacements)) output.close() old_env = dict(os.environ) os.environ['GYP_CROSSCOMPILE'] = '1' test.run_gyp(gypfile) os.environ.clear() os.environ.update(old_env) test.build(gypfile) test.must_contain_all_lines(test.stdout(), ['my_cc.py', 'my_cxx.py', 'BAR']) # Check that CC_host overrides make_global_settings old_env = dict(os.environ) os.environ['CC_host'] = '%s %s/my_cc.py SECRET' % (replacements['PYTHON'], replacements['PWD']) test.run_gyp(gypfile) os.environ.clear() os.environ.update(old_env) test.build(gypfile) test.must_contain_all_lines(test.stdout(), ['SECRET', 'my_cxx.py', 'BAR']) test.pass_test()
DedMemez/ODS-August-2017
refs/heads/master
minigame/DistributedRaceGame.py
1
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.minigame.DistributedRaceGame from panda3d.core import Camera, Quat, VBase4, Vec3, lookAt from toontown.toonbase.ToonBaseGlobal import * from direct.distributed.ClockDelta import * from DistributedMinigame import * from direct.gui.DirectGui import * from direct.interval.IntervalGlobal import * from direct.fsm import ClassicFSM, State from direct.fsm import State from direct.task.Task import Task from toontown.toonbase import ToontownTimer import RaceGameGlobals from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer class DistributedRaceGame(DistributedMinigame): def __init__(self, cr): DistributedMinigame.__init__(self, cr) self.gameFSM = ClassicFSM.ClassicFSM('DistributedRaceGame', [State.State('off', self.enterOff, self.exitOff, ['inputChoice']), State.State('inputChoice', self.enterInputChoice, self.exitInputChoice, ['waitServerChoices', 'moveAvatars', 'cleanup']), State.State('waitServerChoices', self.enterWaitServerChoices, self.exitWaitServerChoices, ['moveAvatars', 'cleanup']), State.State('moveAvatars', self.enterMoveAvatars, self.exitMoveAvatars, ['inputChoice', 'winMovie', 'cleanup']), State.State('winMovie', self.enterWinMovie, self.exitWinMovie, ['cleanup']), State.State('cleanup', self.enterCleanup, self.exitCleanup, [])], 'off', 'cleanup') self.addChildGameFSM(self.gameFSM) self.posHprArray = (((-9.03, 0.06, 0.025, -152.9), (-7.43, -2.76, 0.025, -152.68), (-6.02, -5.48, 0.025, -157.54), (-5.01, -8.32, 0.025, -160.66), (-4.05, -11.36, 0.025, -170.22), (-3.49, -14.18, 0.025, -175.76), (-3.12, -17.15, 0.025, -177.73), (-3.0, -20.32, 0.025, 178.49), (-3.09, -23.44, 0.025, 176.59), (-3.43, -26.54, 0.025, 171.44), (-4.07, -29.44, 0.025, 163.75), (-5.09, -32.27, 0.025, 158.2), (-6.11, -35.16, 0.025, 154.98), (-7.57, -37.78, 0.025, 154.98), (-9.28, -40.65, 0.025, 150.41)), ((-6.12, 1.62, 0.025, -152.9), (-4.38, -1.35, 0.025, -150.92), (-3.08, -4.3, 0.025, -157.9), (-1.85, -7.26, 0.025, -162.54), (-0.93, -10.49, 0.025, -167.71), (-0.21, -13.71, 0.025, -171.79), (0.21, -17.08, 0.025, -174.92), (0.31, -20.2, 0.025, 177.1), (0.17, -23.66, 0.025, 174.82), (-0.23, -26.91, 0.025, 170.51), (-0.99, -30.2, 0.025, 162.54), (-2.02, -33.28, 0.025, 160.48), (-3.28, -36.38, 0.025, 157.96), (-4.67, -39.17, 0.025, 154.13), (-6.31, -42.15, 0.025, 154.13)), ((-2.99, 3.09, 0.025, -154.37), (-1.38, -0.05, 0.025, -154.75), (-0.19, -3.29, 0.025, -159.22), (1.17, -6.51, 0.025, -162.74), (2.28, -9.8, 0.025, -168.73), (3.09, -13.28, 0.025, -173.49), (3.46, -16.63, 0.025, -176.81), (3.69, -20.38, 0.025, 179.14), (3.61, -24.12, 0.025, 175.78), (3.0, -27.55, 0.025, 170.87), (2.15, -30.72, 0.025, 167.41), (1.04, -34.26, 0.025, 162.11), (-0.15, -37.44, 0.025, 158.59), (-1.64, -40.52, 0.025, 153.89), (-3.42, -43.63, 0.025, 153.89)), ((0.0, 4.35, 0.025, -154.37), (1.52, 1.3, 0.025, -155.67), (3.17, -2.07, 0.025, -155.67), (4.47, -5.41, 0.025, -163.0), (5.56, -9.19, 0.025, -168.89), (6.22, -12.66, 0.025, -171.67), (6.67, -16.56, 0.025, -176.53), (6.93, -20.33, 0.025, 179.87), (6.81, -24.32, 0.025, 175.19), (6.22, -27.97, 0.025, 170.81), (5.59, -31.73, 0.025, 167.54), (4.48, -35.42, 0.025, 161.92), (3.06, -38.82, 0.025, 158.56), (1.4, -42.0, 0.025, 154.32), (-0.71, -45.17, 0.025, 153.27))) self.avatarPositions = {} self.cameraTopView = (-22.78, -41.65, 31.53, -51.55, -42.68, -2.96) self.timer = None self.timerStartTime = None return def getTitle(self): return TTLocalizer.RaceGameTitle def getInstructions(self): return TTLocalizer.RaceGameInstructions def getMaxDuration(self): return 60 def load(self): self.notify.debug('load') DistributedMinigame.load(self) self.raceBoard = loader.loadModel('phase_4/models/minigames/race') self.raceBoard.setPosHpr(0, 0, 0, 0, 0, 0) self.raceBoard.setScale(0.8) self.dice = loader.loadModel('phase_4/models/minigames/dice') self.dice1 = self.dice.find('**/dice_button1') self.dice2 = self.dice.find('**/dice_button2') self.dice3 = self.dice.find('**/dice_button3') self.dice4 = self.dice.find('**/dice_button4') self.diceList = [self.dice1, self.dice2, self.dice3, self.dice4] self.music = loader.loadMusic('phase_4/audio/bgm/minigame_race.ogg') self.posBuzzer = loader.loadSfx('phase_4/audio/sfx/MG_pos_buzzer.ogg') self.negBuzzer = loader.loadSfx('phase_4/audio/sfx/MG_neg_buzzer.ogg') self.winSting = loader.loadSfx('phase_4/audio/sfx/MG_win.ogg') self.loseSting = loader.loadSfx('phase_4/audio/sfx/MG_lose.ogg') self.diceButtonList = [] for i in xrange(1, 5): button = self.dice.find('**/dice_button' + str(i)) button_down = self.dice.find('**/dice_button' + str(i) + '_down') button_ro = self.dice.find('**/dice_button' + str(i) + '_ro') diceButton = DirectButton(image=(button, button_down, button_ro, None), relief=None, pos=(0.433 + (i - 1) * 0.2, 0.0, 0.15), parent=base.a2dBottomLeft, scale=0.25, command=self.handleInputChoice, extraArgs=[i]) diceButton.hide() self.diceButtonList.append(diceButton) self.waitingChoicesLabel = DirectLabel(text=TTLocalizer.RaceGameWaitingChoices, text_fg=VBase4(1, 1, 1, 1), relief=None, pos=(-0.6, 0, -0.75), scale=0.075) self.waitingChoicesLabel.hide() self.chanceMarker = loader.loadModel('phase_4/models/minigames/question_mark') self.chanceCard = loader.loadModel('phase_4/models/minigames/chance_card') self.chanceCardText = OnscreenText('', fg=(1.0, 0, 0, 1), scale=0.14, font=ToontownGlobals.getSignFont(), wordwrap=14, pos=(0.0, 0.2), mayChange=1) self.chanceCardText.hide() self.cardSound = loader.loadSfx('phase_3.5/audio/sfx/GUI_stickerbook_turn.ogg') self.chanceMarkers = [] return def unload(self): self.notify.debug('unload') DistributedMinigame.unload(self) self.raceBoard.removeNode() del self.raceBoard self.dice.removeNode() del self.dice self.chanceMarker.removeNode() del self.chanceMarker self.chanceCardText.removeNode() del self.chanceCardText self.chanceCard.removeNode() del self.chanceCard self.waitingChoicesLabel.destroy() del self.waitingChoicesLabel del self.music del self.posBuzzer del self.negBuzzer del self.winSting del self.loseSting del self.cardSound for button in self.diceButtonList: button.destroy() del self.diceButtonList for marker in self.chanceMarkers: marker.removeNode() del marker del self.chanceMarkers self.removeChildGameFSM(self.gameFSM) del self.gameFSM def onstage(self): self.notify.debug('onstage') DistributedMinigame.onstage(self) base.playMusic(self.music, looping=1, volume=0.8) self.raceBoard.reparentTo(render) camera.reparentTo(render) p = self.cameraTopView camera.setPosHpr(p[0], p[1], p[2], p[3], p[4], p[5]) base.transitions.irisIn(0.4) base.setBackgroundColor(0.1875, 0.7929, 0) def offstage(self): self.notify.debug('offstage') DistributedMinigame.offstage(self) self.music.stop() base.setBackgroundColor(ToontownGlobals.DefaultBackgroundColor) self.raceBoard.reparentTo(hidden) self.chanceCard.reparentTo(hidden) self.chanceCardText.hide() if hasattr(self, 'chanceMarkers'): for marker in self.chanceMarkers: marker.reparentTo(hidden) def setGameReady(self): if not self.hasLocalToon: return self.notify.debug('setGameReady') if DistributedMinigame.setGameReady(self): return self.resetPositions() for i in xrange(self.numPlayers): avId = self.avIdList[i] if self.localAvId == avId: self.localAvLane = i avatar = self.getAvatar(avId) if avatar: avatar.reparentTo(render) avatar.setAnimState('neutral', 1) self.positionInPlace(avatar, i, 0) def setGameStart(self, timestamp): if not self.hasLocalToon: return self.notify.debug('setGameStart') DistributedMinigame.setGameStart(self, timestamp) self.gameFSM.request('inputChoice') def enterOff(self): self.notify.debug('enterOff') def exitOff(self): pass def enterInputChoice(self): self.notify.debug('enterInputChoice') for button in self.diceButtonList: button.show() self.timer = ToontownTimer.ToontownTimer() self.timer.hide() if self.timerStartTime != None: self.startTimer() return def startTimer(self): now = globalClock.getFrameTime() elapsed = now - self.timerStartTime self.timer.posInTopRightCorner() self.timer.setTime(RaceGameGlobals.InputTimeout) self.timer.countdown(RaceGameGlobals.InputTimeout - elapsed, self.handleChoiceTimeout) self.timer.show() def setTimerStartTime(self, timestamp): if not self.hasLocalToon: return else: self.timerStartTime = globalClockDelta.networkToLocalTime(timestamp) if self.timer != None: self.startTimer() return def exitInputChoice(self): for button in self.diceButtonList: button.hide() if self.timer != None: self.timer.destroy() self.timer = None self.timerStartTime = None self.ignore('diceButton') return def handleChoiceTimeout(self): self.sendUpdate('setAvatarChoice', [0]) self.gameFSM.request('waitServerChoices') def handleInputChoice(self, choice): self.sendUpdate('setAvatarChoice', [choice]) self.gameFSM.request('waitServerChoices') def enterWaitServerChoices(self): self.notify.debug('enterWaitServerChoices') self.waitingChoicesLabel.show() def exitWaitServerChoices(self): self.waitingChoicesLabel.hide() def localToonWon(self): localToonPosition = self.avatarPositions[self.localAvId] if localToonPosition >= RaceGameGlobals.NumberToWin: self.notify.debug('localToon won') return 1 else: return 0 def anyAvatarWon(self): for position in self.avatarPositions.values(): if position >= RaceGameGlobals.NumberToWin: self.notify.debug('anyAvatarWon: Somebody won') return 1 self.notify.debug('anyAvatarWon: Nobody won') return 0 def showNumbers(self, task): self.notify.debug('showing numbers...') self.diceInstanceList = [] for i in xrange(len(task.choiceList)): avId = self.avIdList[i] choice = task.choiceList[i] if choice == 0: self.diceInstanceList.append(None) else: diceInstance = self.diceList[choice - 1].copyTo(self.raceBoard) self.diceInstanceList.append(diceInstance) dicePosition = self.avatarPositions[avId] + 1 diceInstance.setScale(4.0) self.positionInPlace(diceInstance, i, dicePosition) diceInstance.setP(-90) diceInstance.setZ(0.05) return Task.done def showMatches(self, task): self.notify.debug('showing matches...') for i in xrange(len(task.choiceList)): avId = self.avIdList[i] choice = task.choiceList[i] if choice != 0: diceInstance = self.diceInstanceList[i] freq = task.choiceList.count(choice) if freq == 1: diceInstance.setColor(0.2, 1, 0.2, 1) if avId == self.localAvId: base.playSfx(self.posBuzzer) else: diceInstance.setColor(1, 0.2, 0.2, 1) if avId == self.localAvId: base.playSfx(self.negBuzzer) return Task.done def hideNumbers(self, task): self.notify.debug('hiding numbers...') for dice in self.diceInstanceList: if dice: dice.removeNode() self.diceInstanceList = [] return Task.done def enterMoveAvatars(self, choiceList, positionList, rewardList): self.notify.debug('in enterMoveAvatars:') tasks = [] self.avatarPositionsCopy = self.avatarPositions.copy() for i in xrange(0, len(choiceList) / self.numPlayers): startIndex = i * self.numPlayers endIndex = startIndex + self.numPlayers self.choiceList = choiceList[startIndex:endIndex] self.positionList = positionList[startIndex:endIndex] self.rewardList = rewardList[startIndex:endIndex] self.notify.debug(' turn: ' + str(i + 1)) self.notify.debug(' choiceList: ' + str(self.choiceList)) self.notify.debug(' positionList: ' + str(self.positionList)) self.notify.debug(' rewardList: ' + str(self.rewardList)) longestLerpTime = self.getLongestLerpTime(i > 0) self.notify.debug('longestLerpTime: ' + str(longestLerpTime)) if i == 0: snt = Task(self.showNumbers) snt.choiceList = self.choiceList smt = Task(self.showMatches) smt.choiceList = self.choiceList tasks += [snt, Task.pause(0.5), smt] if longestLerpTime > 0.0: self.notify.debug('someone moved...') mat = Task(self.moveAvatars) mat.choiceList = self.choiceList mat.positionList = self.positionList mat.rewardList = self.rewardList mat.name = 'moveAvatars' if i == 0: tasks += [Task.pause(0.75), mat, Task.pause(0.75), Task(self.hideNumbers), Task.pause(longestLerpTime - 0.5)] else: mat.chance = 1 tasks += [mat, Task.pause(longestLerpTime)] tasks += self.showChanceRewards() else: self.notify.debug('no one moved...') tasks += [Task.pause(1.0), Task(self.hideNumbers)] self.notify.debug('task list : ' + str(tasks)) wdt = Task(self.walkDone) wdt.name = 'walk done' tasks.append(wdt) moveTask = Task.sequence(*tasks) taskMgr.add(moveTask, 'moveAvatars') def walkDone(self, task): self.choiceList = [] self.positionList = [] if self.anyAvatarWon(): self.gameFSM.request('winMovie') else: self.gameFSM.request('inputChoice') return Task.done def getLongestLerpTime(self, afterFirst): self.notify.debug('afterFirst: ' + str(afterFirst)) longestTime = 0.0 for i in xrange(len(self.choiceList)): freq = self.choiceList.count(self.choiceList[i]) if afterFirst or freq == 1: oldPosition = self.avatarPositionsCopy[self.avIdList[i]] newPosition = self.positionList[i] self.avatarPositionsCopy[self.avIdList[i]] = newPosition squares_walked = abs(newPosition - oldPosition) longestTime = max(longestTime, self.getWalkDuration(squares_walked)) return longestTime def showChanceRewards(self): tasks = [] for reward in self.rewardList: self.notify.debug('showChanceRewards: reward = ' + str(reward)) index = self.rewardList.index(reward) if reward != -1: self.notify.debug('adding tasks!') hcc = Task(self.hideChanceMarker) hcc.chanceMarkers = self.chanceMarkers hcc.index = index sct = Task(self.showChanceCard) sct.chanceCard = self.chanceCard sct.cardSound = self.cardSound stt = Task(self.showChanceCardText) rewardEntry = RaceGameGlobals.ChanceRewards[reward] stt.rewardIdx = reward if rewardEntry[0][0] < 0 or rewardEntry[0][1] > 0: stt.sound = self.negBuzzer else: stt.sound = self.posBuzzer stt.picker = self.avIdList[index] rct = Task(self.resetChanceCard) task = Task.sequence(hcc, sct, Task.pause(1.0), stt, Task.pause(3.0), rct, Task.pause(0.25)) tasks.append(task) return tasks def showChanceCard(self, task): base.playSfx(task.cardSound) self.chanceCard.reparentTo(render) quat = Quat() quat.setHpr((270, 0, -85.24)) self.chanceCard.posQuatInterval(1.0, (19.62, 13.41, 13.14), quat, other=camera).start() return Task.done def hideChanceMarker(self, task): task.chanceMarkers[task.index].reparentTo(hidden) return Task.done def showChanceCardText(self, task): self.notify.debug('showing chance reward: ' + str(task.rewardIdx)) name = self.getAvatar(task.picker).getName() rewardEntry = RaceGameGlobals.ChanceRewards[task.rewardIdx] cardText = '' if rewardEntry[1] != -1: rewardstr_fmt = TTLocalizer.RaceGameCardText if rewardEntry[2] > 0: rewardstr_fmt = TTLocalizer.RaceGameCardTextBeans cardText = rewardstr_fmt % {'name': name, 'reward': rewardEntry[1]} else: rewardstr_fmt = TTLocalizer.RaceGameCardTextHi1 cardText = rewardstr_fmt % {'name': name} base.playSfx(task.sound) self.chanceCardText.setText(cardText) self.chanceCardText.show() return Task.done def resetChanceCard(self, task): self.chanceCardText.hide() self.chanceCard.reparentTo(hidden) self.chanceCard.setPosHpr(0, 0, 0, 0, 0, 0) return Task.done def moveCamera(self): bestPosIdx = self.avatarPositions.values()[0] best_lane = 0 cur_lane = 0 for pos in self.avatarPositions.values(): if pos > bestPosIdx: bestPosIdx = pos best_lane = cur_lane cur_lane = cur_lane + 1 bestPosIdx = min(RaceGameGlobals.NumberToWin, bestPosIdx) localToonPosition = self.avatarPositions[self.localAvId] savedCamPos = camera.getPos() savedCamHpr = camera.getHpr() pos1_idx = min(RaceGameGlobals.NumberToWin - 4, localToonPosition) pos1 = self.posHprArray[self.localAvLane][pos1_idx] bestPosLookAtIdx = bestPosIdx + 1 localToonLookAtIdx = localToonPosition + 4 if localToonLookAtIdx >= bestPosLookAtIdx: pos2_idx = localToonLookAtIdx pos2_idx = min(RaceGameGlobals.NumberToWin, pos2_idx) pos2 = self.posHprArray[self.localAvLane][pos2_idx] else: pos2_idx = bestPosLookAtIdx pos2_idx = min(RaceGameGlobals.NumberToWin, pos2_idx) pos2 = self.posHprArray[best_lane][pos2_idx] posDeltaVecX = pos2[0] - pos1[0] posDeltaVecY = pos2[1] - pos1[1] DistanceMultiplier = 0.8 camposX = pos2[0] + DistanceMultiplier * posDeltaVecX camposY = pos2[1] + DistanceMultiplier * posDeltaVecY race_fraction = bestPosIdx / float(RaceGameGlobals.NumberToWin) CamHeight = 10.0 * race_fraction + (1.0 - race_fraction) * 22.0 CamPos = Vec3(camposX, camposY, pos2[2] + CamHeight) camera.setPos(CamPos) camera_lookat_idx = min(RaceGameGlobals.NumberToWin - 6, localToonPosition) posLookAt = self.posHprArray[self.localAvLane][camera_lookat_idx] camera.lookAt(posLookAt[0], posLookAt[1], posLookAt[2]) CamQuat = Quat() CamQuat.setHpr(camera.getHpr()) camera.setPos(savedCamPos) camera.setHpr(savedCamHpr) camera.posQuatInterval(0.75, CamPos, CamQuat).start() def getWalkDuration(self, squares_walked): walkDuration = abs(squares_walked / 1.2) if squares_walked > 4: walkDuration = walkDuration * 0.3 return walkDuration def moveAvatars(self, task): self.notify.debug('In moveAvatars: ') self.notify.debug(' choiceList: ' + str(task.choiceList)) self.notify.debug(' positionList: ' + str(task.positionList)) self.notify.debug(' rewardList: ' + str(task.rewardList)) for i in xrange(len(self.choiceList)): avId = self.avIdList[i] choice = task.choiceList[i] position = task.positionList[i] chance = max(0, hasattr(task, 'chance')) if choice != 0: oldPosition = self.avatarPositions[avId] self.avatarPositions[avId] = position self.moveCamera() if not chance and task.choiceList.count(choice) != 1: self.notify.debug('duplicate choice!') else: avatar = self.getAvatar(avId) if avatar: squares_walked = abs(position - oldPosition) if squares_walked > 4: self.notify.debug('running') avatar.setPlayRate(1.0, 'run') self.runInPlace(avatar, i, oldPosition, position, self.getWalkDuration(squares_walked)) else: if choice > 0: self.notify.debug('walking forwards') avatar.setPlayRate(1.0, 'walk') else: self.notify.debug('walking backwards') avatar.setPlayRate(-1.0, 'walk') self.walkInPlace(avatar, i, position, self.getWalkDuration(squares_walked)) return Task.done def exitMoveAvatars(self): self.notify.debug('In exitMoveAvatars: removing hooks') taskMgr.remove('moveAvatars') return None def gameOverCallback(self, task): self.gameOver() return Task.done def enterWinMovie(self): self.notify.debug('enterWinMovie') if self.localToonWon(): base.playSfx(self.winSting) else: base.playSfx(self.loseSting) for avId in self.avIdList: avPosition = self.avatarPositions[avId] if avPosition >= RaceGameGlobals.NumberToWin: avatar = self.getAvatar(avId) if avatar: lane = str(self.avIdList.index(avId)) taskMgr.remove('runAvatar-' + lane) taskMgr.remove('walkAvatar-' + lane) avatar.setAnimState('jump', 1.0) taskMgr.doMethodLater(4.0, self.gameOverCallback, 'playMovie') def exitWinMovie(self): taskMgr.remove('playMovie') self.winSting.stop() self.loseSting.stop() def enterCleanup(self): self.notify.debug('enterCleanup') def exitCleanup(self): pass def positionInPlace(self, avatar, lane, place): place = min(place, len(self.posHprArray[lane]) - 1) posH = self.posHprArray[lane][place] avatar.setPosHpr(self.raceBoard, posH[0], posH[1], posH[2], posH[3], 0, 0) def walkInPlace(self, avatar, lane, place, time): place = min(place, len(self.posHprArray[lane]) - 1) posH = self.posHprArray[lane][place] def stopWalk(raceBoard = self.raceBoard, posH = posH): avatar.setAnimState('neutral', 1) if raceBoard.isEmpty(): avatar.setPosHpr(0, 0, 0, 0, 0, 0) else: avatar.setPosHpr(raceBoard, posH[0], posH[1], posH[2], posH[3], 0, 0) posQuat = Quat() posQuat.setHpr((posH[3], 0, 0)) walkSeq = Sequence(Func(avatar.setAnimState, 'walk', 1), avatar.posQuatInterval(time, posH[:3], posQuat, other=self.raceBoard), Func(stopWalk)) walkSeq.start() def runInPlace(self, avatar, lane, currentPlace, newPlace, time): place = min(newPlace, len(self.posHprArray[lane]) - 1) step = (place - currentPlace) / 3 pos1 = self.posHprArray[lane][currentPlace + step] pos2 = self.posHprArray[lane][currentPlace + 2 * step] pos3 = self.posHprArray[lane][place] def stopRun(raceBoard = self.raceBoard, pos3 = pos3): avatar.setAnimState('neutral', 1) avatar.setPosHpr(raceBoard, pos3[0], pos3[1], pos3[2], pos3[3], 0, 0) pos1Quat = Quat() pos1Quat.setHpr((pos1[3], 0, 0)) pos2Quat = Quat() pos2Quat.setHpr((pos1[3], 0, 0)) pos3Quat = Quat() pos3Quat.setHpr((pos1[3], 0, 0)) runSeq = Sequence(Func(avatar.setAnimState, 'run', 1), avatar.posQuatInterval(time / 3.0, pos1[:3], pos1Quat, other=self.raceBoard), avatar.posQuatInterval(time / 3.0, pos2[:3], pos2Quat, other=self.raceBoard), avatar.posQuatInterval(time / 3.0, pos3[:3], pos3Quat, other=self.raceBoard), Func(stopRun)) runSeq.start() def setAvatarChoice(self, choice): self.notify.error('setAvatarChoice should not be called on the client') def setAvatarChose(self, avId): if not self.hasLocalToon: return self.notify.debug('setAvatarChose: avatar: ' + str(avId) + ' choose a number') def setChancePositions(self, positions): if not self.hasLocalToon: return row = 0 for pos in positions: marker = self.chanceMarker.copyTo(render) posHpr = self.posHprArray[row][pos] marker.setPosHpr(self.raceBoard, posHpr[0], posHpr[1], posHpr[2], posHpr[3] + 180, 0, 0.025) marker.setScale(0.7) self.chanceMarkers.append(marker) row += 1 def setServerChoices(self, choices, positions, rewards): if not self.hasLocalToon: return for i in xrange(len(positions)): if positions[i] > RaceGameGlobals.NumberToWin: positions[i] = RaceGameGlobals.NumberToWin if positions[i] < 0: positions[i] = 0 self.notify.debug('setServerChoices: %s positions: %s rewards: %s ' % (choices, positions, rewards)) self.gameFSM.request('moveAvatars', [choices, positions, rewards]) def resetPositions(self): for avId in self.avIdList: self.avatarPositions[avId] = 0
oldmantaiter/disco
refs/heads/develop
lib/disco/worker/classic/modutil.py
11
# for backward compatibility with old location from disco.worker.modutil import *
LuyaoHuang/depend-test-framework
refs/heads/master
depend_test_framework/case_generator.py
1
""" Helper classes to help generate case """ import itertools import random import copy from progressbar import ProgressBar, SimpleProgress, Counter, Timer from .log import get_logger from .env import Env from .utils import pretty from .case import Case from .algorithms import route_permutations LOGGER = get_logger(__name__) class DependGraphCaseGenerator(object): """ Case generator which use a directed graph to describe the dependency of the work items """ def __init__(self, suit_env_limit=20, allow_dep=8, use_map=True): self.dep_graph = None self._allow_dep = allow_dep self._suit_env_limit = suit_env_limit # graph objs mapping self._use_map = use_map self._nodes_map = [] self._edge_map = [] self._v_graph = None def find_suit_envs(self, env): env_list = env if type(env) is list else [env] if not self.dep_graph: raise Exception('Need gen depend graph first') env_record = [] for tmp_env in env_list: tmp_list = [] for key_env in self.dep_graph.keys(): if tmp_env <= key_env: tmp_list.append(key_env) for i, tgt_env in enumerate(sorted(tmp_list, key=len)): if i <= self._suit_env_limit and tgt_env not in env_record: env_record.append(tgt_env) yield tgt_env def compute_route_permutations(self, src_env, target_env, cleanup=False): if not self.dep_graph: raise Exception('Need gen depend graph first') LOGGER.info("Compute route from %s to %s", src_env, target_env) # TODO encapsulation the ProgressBar in utils widgets = ['Processed: ', Counter(), ' of %d (' % len(self.dep_graph), Timer(), ')'] pbar = ProgressBar(widgets=widgets, maxval=len(self.dep_graph)).start() graph = self._v_graph if self._use_map else self.dep_graph src_node = self._nodes_map.index(src_env) if self._use_map else src_env tgt_node = self._nodes_map.index(target_env) if self._use_map else target_env if cleanup: routes = route_permutations(graph, tgt_node, src_node, pb=pbar, allow_dep=self._allow_dep) else: routes = route_permutations(graph, src_node, tgt_node, pb=pbar, allow_dep=self._allow_dep) pbar.finish() ret_routes = [] for route in routes: ret_routes.extend(itertools.product(*route)) return ret_routes def gen_cases(self, test_func, random_cleanup=False, need_cleanup=False, src_env=None): if not src_env: src_env = Env() target_env = list(Env.gen_require_env(test_func)) for tgt_env in self.find_suit_envs(target_env): cases = self.compute_route_permutations(src_env, tgt_env) if not tgt_env.gen_transfer_env(test_func): LOGGER.info('Cannot use env %s for testing', tgt_env) continue if need_cleanup: new_tgt_env = tgt_env.gen_transfer_env(test_func) cleanup_steps = self.gen_cleanups(new_tgt_env, src_env, random_cleanup) else: cleanup_steps = None LOGGER.debug("env: %s case num: %d" % (tgt_env, len(cases))) for case in cases: tmp_case = self.restore_onigin_data(case) case_obj = Case(tmp_case, tgt_env=tgt_env, cleanups=cleanup_steps) yield case_obj def gen_cleanups(self, src_env, tgt_env, random_cleanup=False): cleanups = self.compute_route_permutations(tgt_env, src_env, True) if cleanups: if random_cleanup: cleanup_steps = random.choice(cleanups) else: cleanup_steps = min(cleanups, key=len) return self.restore_onigin_data(cleanup_steps) def gen_cases_special(self, src_env, start_env, end_env): """ Support find cases reach mutli target env """ # TODO: this is tied to mist to close for tgt_start_env in self.find_suit_envs(start_env): if tgt_start_env == src_env: cases = None else: cases = self.compute_route_permutations(src_env, tgt_start_env) if not cases: continue for tgt_end_env in self.dep_graph[tgt_start_env].keys(): if end_env <= tgt_end_env: funcs = self.dep_graph[tgt_start_env][tgt_end_env] if cases: for data in itertools.product(cases, funcs): case = list(data[0]) case = self.restore_onigin_data(case) case.append(data[1]) case_obj = Case(case, tgt_env=tgt_end_env) yield case_obj else: for func in funcs: case_obj = Case([func], tgt_env=tgt_end_env) yield case_obj def gen_multi_test_objects_cases(self, test_funcs, random_cleanup=False, need_cleanup=False, src_env=None, no_extra=True): # TODO: merge this method with gen_cases if src_env is None: src_env = Env() rets = list() def _find_next_steps(int_test_funcs, cur_env, exist_steps, old_env): if int_test_funcs: test_func = int_test_funcs[0] rest_func = int_test_funcs[1:] new_env = cur_env.gen_transfer_env(test_func) if no_extra and new_env is not None: # this means current env is okay # python3: new_exist_steps = exist_steps.copy() new_exist_steps = copy.deepcopy(exist_steps) new_exist_steps.append(test_func) _find_next_steps(rest_func, new_env, new_exist_steps, cur_env) else: # sigh, need find a route target_env = list(Env.gen_require_env(test_func)) for tgt_env in self.find_suit_envs(target_env): steps_list = self.compute_route_permutations(cur_env, tgt_env) new_env = tgt_env.gen_transfer_env(test_func) if not new_env: # BUG: this should not happen LOGGER.info('Cannot use env %s for testing', tgt_env) continue for steps in steps_list: # python3: new_exist_steps = exist_steps.copy() new_exist_steps = copy.deepcopy(exist_steps) new_exist_steps.extend(steps) new_exist_steps.append(test_func) _find_next_steps(rest_func, new_env, new_exist_steps, tgt_env) else: # this is the end of the test_funcs # drop last test func final_steps = exist_steps[:-1] if need_cleanup: cleanup_steps = self.gen_cleanups(cur_env, src_env, random_cleanup) else: cleanup_steps = None # pass old_env since we drop last test func rets.append((final_steps, old_env, cleanup_steps)) _find_next_steps(test_funcs, src_env, [], None) for steps, tgt_env, cleanup_steps in rets: tmp_case = self.restore_onigin_data(steps) case_obj = Case(tmp_case, tgt_env=tgt_env, cleanups=cleanup_steps) yield case_obj def gen_depend_map(self, test_funcs, drop_env=None, start_node=None): dep_graph = {} if not start_node: start_node = Env() dep_graph.setdefault(start_node, {}) nodes = [start_node] widgets = ['Processed: ', Counter(), ' nodes (', Timer(), ')'] LOGGER.info("Start gen depend map...") try: pbar = ProgressBar(widgets=widgets, max_value=100000) except TypeError: # python3 ProgressBar pbar = ProgressBar(widgets=widgets, maxval=100000) pbar.start() while nodes: node = nodes.pop() LOGGER.debug('Start check node %s', node) for func in test_funcs: new_node = node.gen_transfer_env(func) LOGGER.debug('posible New Node: %s func: %s', new_node, func) if new_node is None: continue if drop_env and len(new_node) > drop_env: continue if new_node not in dep_graph.keys(): LOGGER.debug('New Node: %s func: %s', new_node, func) dep_graph.setdefault(new_node, {}) nodes.append(new_node) data = dep_graph[node] data.setdefault(new_node, set()) data[new_node].add(func) pbar.update(len(dep_graph)) LOGGER.debug(pretty(dep_graph)) LOGGER.info('Depend map is %d x %d size', len(dep_graph), len(dep_graph)) self.dep_graph = dep_graph if self._use_map: self.build_graph_map() def build_graph_map(self): if not self.dep_graph: return self._nodes_map = list(self.dep_graph.keys()) v_graph = {} for node in self._nodes_map: sub_map = {} for tgt_node, datas in self.dep_graph[node].items(): tmp_datas = set() for data in datas: if data not in self._edge_map: self._edge_map.append(data) tmp_datas.add(self._edge_map.index(data)) sub_map[self._nodes_map.index(tgt_node)] = tmp_datas v_graph[self._nodes_map.index(node)] = sub_map self._v_graph = v_graph def restore_onigin_data(self, datas): if self._use_map: return [self._edge_map[data] if type(data) is int else data for data in datas] else: return datas def save_dep_graph(self, path=None): raise NotImplementedError def load_dep_graph(self, path=None): raise NotImplementedError
zhanglingkang/three.js
refs/heads/master
utils/exporters/blender/addons/io_three/exporter/texture.py
125
from .. import constants, logger from . import base_classes, image, api class Texture(base_classes.BaseNode): """Class that wraps a texture node""" def __init__(self, node, parent): logger.debug("Texture().__init__(%s)", node) base_classes.BaseNode.__init__(self, node, parent, constants.TEXTURE) img_inst = self.scene.image(api.texture.file_name(self.node)) if not img_inst: image_node = api.texture.image_node(self.node) img_inst = image.Image(image_node.name, self.scene) self.scene[constants.IMAGES].append(img_inst) self[constants.IMAGE] = img_inst[constants.UUID] self[constants.WRAP] = api.texture.wrap(self.node) if constants.WRAPPING.REPEAT in self[constants.WRAP]: self[constants.REPEAT] = api.texture.repeat(self.node) self[constants.ANISOTROPY] = api.texture.anisotropy(self.node) self[constants.MAG_FILTER] = api.texture.mag_filter(self.node) self[constants.MIN_FILTER] = api.texture.min_filter(self.node) self[constants.MAPPING] = api.texture.mapping(self.node) @property def image(self): """ :return: the image object of the current texture :rtype: image.Image """ return self.scene.image(self[constants.IMAGE])
angelapper/edx-platform
refs/heads/master
common/lib/xmodule/xmodule/mako_module.py
7
""" Code to handle mako templating for XModules and XBlocks. """ from xblock.fragment import Fragment from .x_module import DescriptorSystem, XModuleDescriptor, shim_xmodule_js class MakoDescriptorSystem(DescriptorSystem): def __init__(self, render_template, **kwargs): super(MakoDescriptorSystem, self).__init__(**kwargs) self.render_template = render_template class MakoTemplateBlockBase(object): """ XBlock intended as a mixin that uses a mako template to specify the module html. Expects the descriptor to have the `mako_template` attribute set with the name of the template to render, and it will pass the descriptor as the `module` parameter to that template """ # pylint: disable=no-member def __init__(self, *args, **kwargs): super(MakoTemplateBlockBase, self).__init__(*args, **kwargs) if getattr(self.runtime, 'render_template', None) is None: raise TypeError( '{runtime} must have a render_template function' ' in order to use a MakoDescriptor'.format( runtime=self.runtime, ) ) def get_context(self): """ Return the context to render the mako template with """ return { 'module': self, 'editable_metadata_fields': self.editable_metadata_fields } def studio_view(self, context): # pylint: disable=unused-argument """ View used in Studio. """ # pylint: disable=no-member fragment = Fragment( self.system.render_template(self.mako_template, self.get_context()) ) shim_xmodule_js(self, fragment) return fragment class MakoModuleDescriptor(MakoTemplateBlockBase, XModuleDescriptor): # pylint: disable=abstract-method """ Mixin to use for XModule descriptors. """ resources_dir = None def get_html(self): return self.studio_view(None).content
eneldoserrata/marcos_openerp
refs/heads/master
addons/survey/wizard/survey_print_statistics.py
54
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-TODAY OpenERP S.A. <http://www.openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ class survey_print_statistics(osv.osv_memory): _name = 'survey.print.statistics' _columns = { 'survey_ids': fields.many2many('survey', string="Survey", required="1"), } def action_next(self, cr, uid, ids, context=None): """ Print Survey Statistics in pdf format. """ if context is None: context = {} datas = {'ids': context.get('active_ids', [])} res = self.read(cr, uid, ids, ['survey_ids'], context=context) res = res and res[0] or {} datas['form'] = res datas['model'] = 'survey.print.statistics' return { 'type': 'ir.actions.report.xml', 'report_name': 'survey.analysis', 'datas': datas, } survey_print_statistics() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
lsqtongxin/django
refs/heads/master
tests/generic_relations_regress/models.py
269
from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models.deletion import ProtectedError from django.utils.encoding import python_2_unicode_compatible __all__ = ('Link', 'Place', 'Restaurant', 'Person', 'Address', 'CharLink', 'TextLink', 'OddRelation1', 'OddRelation2', 'Contact', 'Organization', 'Note', 'Company') @python_2_unicode_compatible class Link(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() def __str__(self): return "Link to %s id=%s" % (self.content_type, self.object_id) @python_2_unicode_compatible class Place(models.Model): name = models.CharField(max_length=100) links = GenericRelation(Link) def __str__(self): return "Place: %s" % self.name @python_2_unicode_compatible class Restaurant(Place): def __str__(self): return "Restaurant: %s" % self.name @python_2_unicode_compatible class Address(models.Model): street = models.CharField(max_length=80) city = models.CharField(max_length=50) state = models.CharField(max_length=2) zipcode = models.CharField(max_length=5) content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() def __str__(self): return '%s %s, %s %s' % (self.street, self.city, self.state, self.zipcode) @python_2_unicode_compatible class Person(models.Model): account = models.IntegerField(primary_key=True) name = models.CharField(max_length=128) addresses = GenericRelation(Address) def __str__(self): return self.name class CharLink(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.CharField(max_length=100) content_object = GenericForeignKey() class TextLink(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.TextField() content_object = GenericForeignKey() class OddRelation1(models.Model): name = models.CharField(max_length=100) clinks = GenericRelation(CharLink) class OddRelation2(models.Model): name = models.CharField(max_length=100) tlinks = GenericRelation(TextLink) # models for test_q_object_or: class Note(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() note = models.TextField() class Contact(models.Model): notes = GenericRelation(Note) class Organization(models.Model): name = models.CharField(max_length=255) contacts = models.ManyToManyField(Contact, related_name='organizations') @python_2_unicode_compatible class Company(models.Model): name = models.CharField(max_length=100) links = GenericRelation(Link) def __str__(self): return "Company: %s" % self.name # For testing #13085 fix, we also use Note model defined above class Developer(models.Model): name = models.CharField(max_length=15) @python_2_unicode_compatible class Team(models.Model): name = models.CharField(max_length=15) members = models.ManyToManyField(Developer) def __str__(self): return "%s team" % self.name def __len__(self): return self.members.count() class Guild(models.Model): name = models.CharField(max_length=15) members = models.ManyToManyField(Developer) def __nonzero__(self): return self.members.count() class Tag(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE, related_name='g_r_r_tags') object_id = models.CharField(max_length=15) content_object = GenericForeignKey() label = models.CharField(max_length=15) class Board(models.Model): name = models.CharField(primary_key=True, max_length=15) class SpecialGenericRelation(GenericRelation): def __init__(self, *args, **kwargs): super(SpecialGenericRelation, self).__init__(*args, **kwargs) self.editable = True self.save_form_data_calls = 0 def save_form_data(self, *args, **kwargs): self.save_form_data_calls += 1 class HasLinks(models.Model): links = SpecialGenericRelation(Link) class Meta: abstract = True class HasLinkThing(HasLinks): pass class A(models.Model): flag = models.NullBooleanField() content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class B(models.Model): a = GenericRelation(A) class Meta: ordering = ('id',) class C(models.Model): b = models.ForeignKey(B, models.CASCADE) class Meta: ordering = ('id',) class D(models.Model): b = models.ForeignKey(B, models.SET_NULL, null=True) class Meta: ordering = ('id',) # Ticket #22998 class Node(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content = GenericForeignKey('content_type', 'object_id') class Content(models.Model): nodes = GenericRelation(Node) related_obj = models.ForeignKey('Related', models.CASCADE) class Related(models.Model): pass def prevent_deletes(sender, instance, **kwargs): raise ProtectedError("Not allowed to delete.", [instance]) models.signals.pre_delete.connect(prevent_deletes, sender=Node)
hsr-ba-fs15-dat/opendatahub
refs/heads/master
src/main/python/hub/odhql/functions/misc.py
1
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ Misc. functions/utils """ import pandas as pd import numpy as np from hub.structures.frame import OdhType, OdhSeries from hub.odhql.functions.core import VectorizedFunction class NVL(VectorizedFunction): """ Gibt das zweite Argument zurück, falls das erste NULL ist. Parameter - `a`: Spalte oder Wert der auf NULL geprüft werden soll - `b`: Spalte oder Wert der als Ersatz verwendet werden soll Beispiel .. code:: sql NVL(ODH12.title, '') as title """ name = 'NVL' def apply(self, a, b): return a.where(~pd.isnull(a), b) class Round(VectorizedFunction): """ Rundet auf die angegebene Anzahl Nachkommastellen. Parameter - `col`: Spalte oder Wert der gerundet werden soll. Muss vom Datentyp FLOAT sein. - `decimals`: Anzahl Nachkommastellen, auf die gerundet werden soll. Beispiel .. code:: sql ROUND(ODH20.fraction, 4) AS fraction """ name = 'ROUND' def apply(self, col, decimals): self.assert_float('column', col) self.assert_int('decimals', decimals) self.assert_value() return self.expand(col).round(decimals) class Cast(VectorizedFunction): """ Konvertiert den Datentyp einer Spalte oder eines einzelnen Wertes. Parameter - `values`: Spalte oder Wert der konvertiert werden soll. - `datatype`: Gültiger ODHQL Datentyp Beispiel .. code:: sql CAST(ODH42.age, 'INTEGER') AS age """ name = 'CAST' def apply(self, values, datatype): datatype = datatype.upper() self.assert_in('type', datatype.upper(), OdhType.by_name.keys()) odh_type = OdhType.by_name[datatype] with self.errorhandler('Unable to cast ({exception})'): return odh_type.convert(self.expand(values)) class ToDate(VectorizedFunction): """ Konvertiert ein Datum in TEXT-Form zu DATETIME. Parameter - `values`: Spalte oder Wert der konvertiert werden soll. - `format`: Format-Angabe. Siehe `Dokumentation <https://docs.python.org/2/library/time.html#time.strftime>`_. Beispiel .. code:: sql TO_DATE(ODH5.baubeginn, '%d%m%Y') AS baubeginn """ name = 'TO_DATE' def apply(self, values, format=None): values = self.expand(values) self.assert_str(0, values) with self.errorhandler('Unable to parse datetimes ({exception})'): return pd.to_datetime(values, format=format, infer_datetime_format=True, coerce=True) class Range(VectorizedFunction): """ Liefert eine Sequenz von Ganzzahlen. Geeignet um beispielsweise künstliche IDs zu erstellen. Parameter - `start`: Erster Wert der Sequenz. - `step`: Abstand zwischen den Ganzzahlen. Beispiel .. code:: sql RANGE() AS id """ name = 'RANGE' def apply(self, start=1, step=1): self.assert_value('start', start) self.assert_value('step', step) self.assert_int('start', start) self.assert_int('step', step) stop = (start + self.num_rows) * step return OdhSeries(np.arange(start, stop, step))
daineseh/kodi-plugin.video.ted-talks-chinese
refs/heads/master
youtube_dl/extractor/dumpert.py
44
# coding: utf-8 from __future__ import unicode_literals import base64 import re from .common import InfoExtractor from ..utils import ( qualities, sanitized_Request, ) class DumpertIE(InfoExtractor): _VALID_URL = r'(?P<protocol>https?)://(?:www\.)?dumpert\.nl/(?:mediabase|embed)/(?P<id>[0-9]+/[0-9a-zA-Z]+)' _TESTS = [{ 'url': 'http://www.dumpert.nl/mediabase/6646981/951bc60f/', 'md5': '1b9318d7d5054e7dcb9dc7654f21d643', 'info_dict': { 'id': '6646981/951bc60f', 'ext': 'mp4', 'title': 'Ik heb nieuws voor je', 'description': 'Niet schrikken hoor', 'thumbnail': 're:^https?://.*\.jpg$', } }, { 'url': 'http://www.dumpert.nl/embed/6675421/dc440fe7/', 'only_matching': True, }] def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') protocol = mobj.group('protocol') url = '%s://www.dumpert.nl/mediabase/%s' % (protocol, video_id) req = sanitized_Request(url) req.add_header('Cookie', 'nsfw=1; cpc=10') webpage = self._download_webpage(req, video_id) files_base64 = self._search_regex( r'data-files="([^"]+)"', webpage, 'data files') files = self._parse_json( base64.b64decode(files_base64.encode('utf-8')).decode('utf-8'), video_id) quality = qualities(['flv', 'mobile', 'tablet', '720p']) formats = [{ 'url': video_url, 'format_id': format_id, 'quality': quality(format_id), } for format_id, video_url in files.items() if format_id != 'still'] self._sort_formats(formats) title = self._html_search_meta( 'title', webpage) or self._og_search_title(webpage) description = self._html_search_meta( 'description', webpage) or self._og_search_description(webpage) thumbnail = files.get('still') or self._og_search_thumbnail(webpage) return { 'id': video_id, 'title': title, 'description': description, 'thumbnail': thumbnail, 'formats': formats }
andrius-preimantas/odoo
refs/heads/master
addons/l10n_fr_hr_payroll/report/__init__.py
424
#-*- coding:utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # d$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import fiche_paye # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
abseil/abseil-py
refs/heads/master
absl/testing/tests/__init__.py
44
# Copyright 2017 The Abseil 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.
shhui/nova
refs/heads/master
nova/api/openstack/compute/schemas/v3/agents.py
19
# Copyright 2013 NEC Corporation. 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. create = { 'type': 'object', 'properties': { 'agent': { 'type': 'object', 'properties': { 'hypervisor': { 'type': 'string', 'minLength': 0, 'maxLength': 255, 'pattern': '^[a-zA-Z0-9-._ ]*$' }, 'os': { 'type': 'string', 'minLength': 0, 'maxLength': 255, 'pattern': '^[a-zA-Z0-9-._ ]*$' }, 'architecture': { 'type': 'string', 'minLength': 0, 'maxLength': 255, 'pattern': '^[a-zA-Z0-9-._ ]*$' }, 'version': { 'type': 'string', 'minLength': 0, 'maxLength': 255, 'pattern': '^[a-zA-Z0-9-._ ]*$' }, 'url': { 'type': 'string', 'minLength': 0, 'maxLength': 255, 'format': 'uri' }, 'md5hash': { 'type': 'string', 'minLength': 0, 'maxLength': 255, 'pattern': '^[a-fA-F0-9]*$' }, }, 'required': ['hypervisor', 'os', 'architecture', 'version', 'url', 'md5hash'], 'additionalProperties': False, }, }, 'required': ['agent'], 'additionalProperties': False, } update = { 'type': 'object', 'properties': { 'agent': { 'type': 'object', 'properties': { 'version': { 'type': 'string', 'minLength': 0, 'maxLength': 255, 'pattern': '^[a-zA-Z0-9-._ ]*$' }, 'url': { 'type': 'string', 'minLength': 0, 'maxLength': 255, 'format': 'uri' }, 'md5hash': { 'type': 'string', 'minLength': 0, 'maxLength': 255, 'pattern': '^[a-fA-F0-9]*$' }, }, 'required': ['version', 'url', 'md5hash'], 'additionalProperties': False, }, }, 'required': ['agent'], 'additionalProperties': False, }
DavidRamage/imagestream
refs/heads/master
udp_broadcast.py
1
#!/usr/bin/python """A simple program which captures a jpeg from a webcam. The image is then chopped up and sent in UDP broadcast packets.""" from SimpleCV import Camera from io import BytesIO import struct import binascii from socket import socket, AF_INET, SOCK_DGRAM, SOL_SOCKET, SO_BROADCAST import time import syslog CAMERA = Camera() def get_image(): """Get an image from CAMERA and return a BytesIO object comtaining the image as a jpeg.""" img_buffer = BytesIO() try: image = CAMERA.getImage() except Exception as ex: syslog.syslog(syslog.LOG_ERR, "Unable to grab image from camera due to %s" % str(ex)) image.save(img_buffer) return img_buffer.getvalue() def get_image_chunks(byte_str): """Get an array of correct-sized chunks of bytes for packetization""" byte_strings = [] count = 0 mystr = str() for img_byte in byte_str: mystr += img_byte count += 1 if count == 457: byte_strings.append((mystr, count)) mystr = str() count = 0 byte_strings.append((mystr.ljust(457, '0'), count)) return byte_strings def get_packet(last_pkt, seq_num, bytes_sent, payload): """build a packet""" pkt_struct = struct.Struct("> B l I H 457s") try: return pkt_struct.pack(last_pkt, binascii.crc32(payload), seq_num, bytes_sent, payload) except Exception as ex: syslog.syslog(syslog.LOG_ERR, "Unable to send packet due to %s" %\ str(ex)) if __name__ == "__main__": SOCK = socket(AF_INET, SOCK_DGRAM, 0) SOCK.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) SOCK.connect(('255.255.255.255', 31337)) while True: FILE_BUF = get_image() BYTE_ARRAYS = get_image_chunks(FILE_BUF) COUNT = 0 for (byte_array, size) in BYTE_ARRAYS: last_pkt = 0 if COUNT == len(BYTE_ARRAYS) - 1: last_pkt = 1 SOCK.send(get_packet(last_pkt, COUNT, size, byte_array)) COUNT += 1 time.sleep(1)
WDavidX/init
refs/heads/master
eplugins/python-mode/completion/test_pycomplete.py
22
#!/usr/bin/env python import os import linecache import tempfile from pycomplete import * def test_signature(): assert pysignature('') == '' assert pysignature('os.path.join') == 'join: (a, *p)' assert pysignature('json.dump').startswith( 'dump: (obj, fp, skipkeys=False, ensure_ascii=True, ') assert pysignature('json.JSONEncoder.encode') == 'encode: (self, o)' assert pysignature('json.JSONEncoder').startswith( '__init__: (self, skipkeys=False, ensure_ascii=True, ') assert pysignature('xml.dom.minidom.parse') == \ 'parse: (file, parser=None, bufsize=None)' assert pysignature('csv.reader') == \ 'csv_reader = reader(iterable [, dialect=\'excel\']' assert pysignature('super') in ( 'super(type) -> unbound super object', 'super() -> same as super(__class__, <first argument>)') def test_help(): assert pyhelp('os.path.join').startswith('Help on function join') assert pyhelp('logging', imports=('import logging',)).startswith( 'Help on package logging:\n\nNAME\n logging\n') assert pyhelp('csv', imports=('import csv',)).startswith( 'Help on module csv:\n\nNAME\n csv - CSV parsing and writing.\n') assert pyhelp('import').startswith( 'The ``import`` statement\n************************\n') assert pyhelp('pydoc.help').startswith( 'Help on class Helper in module pydoc') assert pyhelp('') == '' def test_complete(): assert pycomplete('') == '' assert pycomplete('sys.getd') == ['getdefaultencoding', 'getdlopenflags'] assert pycomplete('set') == ['set', 'setattr'] assert pycomplete('settr') is None assert pycomplete('settr', imports=['from sys import settrace']) == [ 'ace'] # Test with cached imports assert pycomplete('settr') == ['ace'] # Not cached for other files fpath = os.path.abspath(__file__) assert pycomplete('settr', fname=fpath) is None assert pycomplete('settr', fname=fpath, imports=['from sys import settrace']) == ['ace'] assert pycomplete('foo.') is None assert pycomplete('JSONEnc') is None assert pycomplete('JSONEnc', imports=['from json import *']) == ['oder'] assert pycomplete('A') == [ 'ArithmeticError', 'AssertionError', 'AttributeError'] def test_completions(): all_completions = pycompletions('') assert all_completions[0] == 'ArithmeticError' assert all_completions[-1] == 'zip' assert pycompletions('os.path.jo') == ['join'] assert pycompletions('settr', imports=['']) == [] assert pycompletions('settr', imports=['from sys import settrace']) == ['settrace'] # Check if imports are still cached. assert pycompletions('settr', imports=None) == ['settrace'] # Change list of imports, so that cache is invalidated. assert pycompletions('settr', imports=['']) == [] def test_location(): fn, line = pylocation('os.path.join') assert os.path.exists(fn) assert linecache.getline(fn, line).startswith('def join') assert pylocation('io.StringIO') is None fn, line = pylocation('json') assert os.path.exists(fn) assert pylocation('for') is None def test_docstring(): assert pydocstring('os.path.abspath') == 'Return an absolute path.' assert pydocstring('os.path').startswith( 'Common operations on Posix pathnames.\n') assert pydocstring('json.JSONEncoder.encode').startswith( 'Return a JSON string representation of a Python data structure.\n') assert pydocstring('yield') == '' assert pydocstring('numbers.Real.real') == \ 'Real numbers are their real component.' assert pydocstring('notexisting') == '' assert pydocstring('re.IGNORECASE') == '' def test_parse_source(): tmp_file = tempfile.NamedTemporaryFile(suffix='.py', mode='w') name = tmp_file.name with tmp_file.file as fh: assert pyparse('not_existing', only_reload=True) == None assert pyparse('not_existing') == \ "[Errno 2] No such file or directory: 'not_existing'" assert pyparse(name) is None # Nothing imported so far assert pycompletions('dat' , name) == [] src = """ "Doc for module." from __future__ import print_function import sys, os, io, re from datetime import date, \ time import argparse if os.getenv('LC'): import linecache modvar = 1 mod_re = re.compile(r'^test') def testfunc(): "Doc for testfunc." import urllib def emptyfunc(): "Function with only docstring." class TestClass(date): "Doc for TestClass." CONST1 = 7 CONST2 = 'abc' CONST3 = ['a', ] def __init__(self): self._member1 = 'string member' self._member2 = None self.__member3 = [ None, open('not_existing') ] self.member4 = argparse.ArgumentParser() self.member4 = None self.member5 = open('not_existing') self.member6 = self.member7 = { 'multiple': 'targets' } self.member8, self.member9 = 'tuple', 'assignment' self.member10 = [ n for n in range(3) ] self.member11 = SyntaxError() self.member12 = testfunc() def testmeth(self, arg1=modvar): "Doc for testmeth." sys.stdout.write('From testmeth %d' % arg1) if arg1 == 2: self._member1 = None @staticmethod def teststaticmeth(arg1=2): "Doc for teststaticmeth." sys.stdout.write('From teststaticmeth %d' % arg1) @classmethod def testclassmeth(cls, arg1=3): "Doc for testclassmeth." open('not_existing') @property def testprop(self): "Doc for testprop." return 4 * 8 if __name__ == '__main__': testfunc() """ num_src_lines = len(src.splitlines()) fh.write(src) fh.flush() assert pyparse(name) == None # Check if only global imports are visible assert pycompletions('dat' , name) == ['date'] assert pycompletions('tim' , name) == ['time'] assert pycompletions('url' , name) == [] assert pycompletions('line' , name) == ['linecache'] assert pycompletions('os' , name) == ['os'] # Check for definitions in local file assert pycompletions('test' , name) == ['testfunc'] assert pycompletions('TestClass.CO' , name) == \ ['CONST1', 'CONST2', 'CONST3'] assert pycompletions('TestClass.test' , name) == \ ['testclassmeth', 'testmeth', 'testprop', 'teststaticmeth'] # Check for instance members assert pycompletions('TestClass._mem', name) == \ ['_member1', '_member2'] assert pycompletions('TestClass.__mem', name) == ['__member3'] assert pycompletions('TestClass._member1.start', name) == \ ['startswith'] assert pycompletions('TestClass._member2.', name) == [] assert pycompletions('TestClass.__member3.ext', name) == \ ['extend'] assert pycompletions('TestClass.member4.prin', name) == \ ['print_help', 'print_usage', 'print_version'] assert pycompletions('TestClass.member5.writel', name) == \ ['writelines'] assert pycompletions('TestClass.member6.from', name) == \ ['fromkeys'] assert pycompletions('TestClass.member7.from', name) == \ ['fromkeys'] assert pycompletions('TestClass.member10.ext', name) == \ ['extend'] assert pycompletions('TestClass.member11.ar', name) == \ ['args'] assert pycompletions('modvar.num', name) == ['numerator'] assert pycompletions('mod_re.ma', name) == ['match'] assert pydocstring('TestClass._member1', name) == '' assert pydocstring('TestClass._member2', name) == '' assert pydocstring('TestClass.__member3', name) == '' # Check for super class assert pycompletions('TestClass.week' , name) == ['weekday'] assert pycompletions('TestClass.utc' , name) == [] # Check signature, documentation and location assert pysignature('TestClass.testmeth', name) == \ 'testmeth: (self, arg1=1)' assert pydocstring('testfunc', name) == \ 'Doc for testfunc.' assert pylocation('TestClass.testclassmeth', name) == \ (name, num_src_lines - 10) # Verify that loaded symbols are not affected by transient # syntax error fh.write('while') fh.flush() assert pyparse(name) == \ 'invalid syntax (%s, line %d)' % (os.path.basename(name), num_src_lines + 1) assert pycompletions('dat' , name) == ['date'] # Replace file contents and check new imports fh.seek(0) fh.truncate(0) fh.write('import urllib\n') fh.flush() assert pyparse(name) == None assert pycompletions('dat' , name) == [] assert pycompletions('url' , name) == ['urllib'] def run_tests(): test_complete() test_completions() test_help() test_signature() test_location() test_docstring() test_parse_source() if __name__ == "__main__": run_tests()
tmerrick1/spack
refs/heads/develop
var/spack/repos/builtin/packages/bismark/package.py
5
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Bismark(Package): """A tool to map bisulfite converted sequence reads and determine cytosine methylation states""" homepage = "https://www.bioinformatics.babraham.ac.uk/projects/bismark" url = "https://github.com/FelixKrueger/Bismark/archive/0.19.0.tar.gz" version('0.19.0', 'f403654aded77bf0d1dac1203867ded1') version('0.18.2', '42334b7e3ed53ba246f30f1f846b4af8') depends_on('bowtie2', type='run') depends_on('perl', type='run') depends_on('samtools', type='run') def install(self, spec, prefix): mkdirp(prefix.bin) install('bam2nuc', prefix.bin) install('bismark', prefix.bin) install('bismark_genome_preparation', prefix.bin) install('bismark_methylation_extractor', prefix.bin) install('bismark2bedGraph', prefix.bin) install('bismark2report', prefix.bin) install('bismark2summary', prefix.bin) install('coverage2cytosine', prefix.bin) install('deduplicate_bismark', prefix.bin) install('filter_non_conversion', prefix.bin) install('NOMe_filtering', prefix.bin)
amisrs/angular-flask
refs/heads/master
angular_flask/lib/python2.7/site-packages/docker/models/services.py
3
import copy from docker.errors import create_unexpected_kwargs_error from docker.types import TaskTemplate, ContainerSpec from .resource import Model, Collection class Service(Model): """A service.""" id_attribute = 'ID' @property def name(self): """The service's name.""" return self.attrs['Spec']['Name'] @property def version(self): """ The version number of the service. If this is not the same as the server, the :py:meth:`update` function will not work and you will need to call :py:meth:`reload` before calling it again. """ return self.attrs.get('Version').get('Index') def remove(self): """ Stop and remove the service. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ return self.client.api.remove_service(self.id) def tasks(self, filters=None): """ List the tasks in this service. Args: filters (dict): A map of filters to process on the tasks list. Valid filters: ``id``, ``name``, ``node``, ``label``, and ``desired-state``. Returns: (:py:class:`list`): List of task dictionaries. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ if filters is None: filters = {} filters['service'] = self.id return self.client.api.tasks(filters=filters) def update(self, **kwargs): """ Update a service's configuration. Similar to the ``docker service update`` command. Takes the same parameters as :py:meth:`~ServiceCollection.create`. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ # Image is required, so if it hasn't been set, use current image if 'image' not in kwargs: spec = self.attrs['Spec']['TaskTemplate']['ContainerSpec'] kwargs['image'] = spec['Image'] create_kwargs = _get_create_service_kwargs('update', kwargs) return self.client.api.update_service( self.id, self.version, **create_kwargs ) def logs(self, **kwargs): """ Get log stream for the service. Note: This method works only for services with the ``json-file`` or ``journald`` logging drivers. Args: details (bool): Show extra details provided to logs. Default: ``False`` follow (bool): Keep connection open to read logs as they are sent by the Engine. Default: ``False`` stdout (bool): Return logs from ``stdout``. Default: ``False`` stderr (bool): Return logs from ``stderr``. Default: ``False`` since (int): UNIX timestamp for the logs staring point. Default: 0 timestamps (bool): Add timestamps to every log line. tail (string or int): Number of log lines to be returned, counting from the current end of the logs. Specify an integer or ``'all'`` to output all log lines. Default: ``all`` Returns (generator): Logs for the service. """ is_tty = self.attrs['Spec']['TaskTemplate']['ContainerSpec'].get( 'TTY', False ) return self.client.api.service_logs(self.id, is_tty=is_tty, **kwargs) class ServiceCollection(Collection): """Services on the Docker server.""" model = Service def create(self, image, command=None, **kwargs): """ Create a service. Similar to the ``docker service create`` command. Args: image (str): The image name to use for the containers. command (list of str or str): Command to run. args (list of str): Arguments to the command. constraints (list of str): Placement constraints. container_labels (dict): Labels to apply to the container. endpoint_spec (EndpointSpec): Properties that can be configured to access and load balance a service. Default: ``None``. env (list of str): Environment variables, in the form ``KEY=val``. hostname (string): Hostname to set on the container. labels (dict): Labels to apply to the service. log_driver (str): Log driver to use for containers. log_driver_options (dict): Log driver options. mode (ServiceMode): Scheduling mode for the service. Default:``None`` mounts (list of str): Mounts for the containers, in the form ``source:target:options``, where options is either ``ro`` or ``rw``. name (str): Name to give to the service. networks (list of str): List of network names or IDs to attach the service to. Default: ``None``. resources (Resources): Resource limits and reservations. restart_policy (RestartPolicy): Restart policy for containers. secrets (list of :py:class:`docker.types.SecretReference`): List of secrets accessible to containers for this service. stop_grace_period (int): Amount of time to wait for containers to terminate before forcefully killing them. update_config (UpdateConfig): Specification for the update strategy of the service. Default: ``None`` user (str): User to run commands as. workdir (str): Working directory for commands to run. Returns: (:py:class:`Service`) The created service. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ kwargs['image'] = image kwargs['command'] = command create_kwargs = _get_create_service_kwargs('create', kwargs) service_id = self.client.api.create_service(**create_kwargs) return self.get(service_id) def get(self, service_id): """ Get a service. Args: service_id (str): The ID of the service. Returns: (:py:class:`Service`): The service. Raises: :py:class:`docker.errors.NotFound` If the service does not exist. :py:class:`docker.errors.APIError` If the server returns an error. """ return self.prepare_model(self.client.api.inspect_service(service_id)) def list(self, **kwargs): """ List services. Args: filters (dict): Filters to process on the nodes list. Valid filters: ``id`` and ``name``. Default: ``None``. Returns: (list of :py:class:`Service`): The services. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ return [ self.prepare_model(s) for s in self.client.api.services(**kwargs) ] # kwargs to copy straight over to ContainerSpec CONTAINER_SPEC_KWARGS = [ 'image', 'command', 'args', 'env', 'hostname', 'workdir', 'user', 'labels', 'mounts', 'stop_grace_period', 'secrets', ] # kwargs to copy straight over to TaskTemplate TASK_TEMPLATE_KWARGS = [ 'resources', 'restart_policy', ] # kwargs to copy straight over to create_service CREATE_SERVICE_KWARGS = [ 'name', 'labels', 'mode', 'update_config', 'networks', 'endpoint_spec', ] def _get_create_service_kwargs(func_name, kwargs): # Copy over things which can be copied directly create_kwargs = {} for key in copy.copy(kwargs): if key in CREATE_SERVICE_KWARGS: create_kwargs[key] = kwargs.pop(key) container_spec_kwargs = {} for key in copy.copy(kwargs): if key in CONTAINER_SPEC_KWARGS: container_spec_kwargs[key] = kwargs.pop(key) task_template_kwargs = {} for key in copy.copy(kwargs): if key in TASK_TEMPLATE_KWARGS: task_template_kwargs[key] = kwargs.pop(key) if 'container_labels' in kwargs: container_spec_kwargs['labels'] = kwargs.pop('container_labels') if 'constraints' in kwargs: task_template_kwargs['placement'] = { 'Constraints': kwargs.pop('constraints') } if 'log_driver' in kwargs: task_template_kwargs['log_driver'] = { 'Name': kwargs.pop('log_driver'), 'Options': kwargs.pop('log_driver_options', {}) } # All kwargs should have been consumed by this point, so raise # error if any are left if kwargs: raise create_unexpected_kwargs_error(func_name, kwargs) container_spec = ContainerSpec(**container_spec_kwargs) task_template_kwargs['container_spec'] = container_spec create_kwargs['task_template'] = TaskTemplate(**task_template_kwargs) return create_kwargs
cardsurf/xcrawler
refs/heads/master
examples/wikipedia_fallback_list_example.py
2
from xcrawler import XCrawler, Page, PageScraper class RelatedTopic: def __init__(self): self.name = None self.url = None class WikipediaScraper(PageScraper): def extract(self, page): ''' A web page may contain incomplete data. An IndexError occurs when trying to access extracted data with an incorrect index. try: item.name = names.get[i] except IndexError: item.name = "ANameIsMissing!" When dealing with incomplete data use the `get` method of the FallbackList class. The `get` method returns a fallback value when an IndexError occurs: item.name = names.get(i, fallback="NoName") ''' names = page.xpath("//div[@class='div-col columns column-count column-count-2']/ul[1]/li/a/text()") urls = page.xpath("//div[@class='div-col columns column-count column-count-2']/ul[1]/li/a/@href") topics = [] for i in range(0, 30): topic = RelatedTopic() topic.name = names.get(i, fallback="NoName") topic.url = urls.get(i) topics.append(topic) return topics start_pages = [ Page("https://en.wikipedia.org/wiki/Arithmetic", WikipediaScraper()) ] crawler = XCrawler(start_pages) crawler.config.output_file_name = "wikipedia_fallback_list_example_output.csv" crawler.run()
jimi-c/ansible
refs/heads/devel
lib/ansible/plugins/action/enos_config.py
49
# (C) 2017 Red Hat Inc. # Copyright (C) 2017 Lenovo. # # GNU General Public License v3.0+ # # 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. # # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # # Contains Action Plugin methods for ENOS Config Module # Lenovo Networking from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import re import time import glob from ansible.plugins.action.enos import ActionModule as _ActionModule from ansible.module_utils._text import to_text from ansible.module_utils.six.moves.urllib.parse import urlsplit from ansible.utils.vars import merge_hash PRIVATE_KEYS_RE = re.compile('__.+__') class ActionModule(_ActionModule): def run(self, tmp=None, task_vars=None): if self._task.args.get('src'): try: self._handle_template() except ValueError as exc: return dict(failed=True, msg=to_text(exc)) result = super(ActionModule, self).run(tmp, task_vars) del tmp # tmp no longer has any effect if self._task.args.get('backup') and result.get('__backup__'): # User requested backup and no error occurred in module. # NOTE: If there is a parameter error, _backup key may not be in results. filepath = self._write_backup(task_vars['inventory_hostname'], result['__backup__']) result['backup_path'] = filepath # strip out any keys that have two leading and two trailing # underscore characters for key in list(result.keys()): if PRIVATE_KEYS_RE.match(key): del result[key] return result def _get_working_path(self): cwd = self._loader.get_basedir() if self._task._role is not None: cwd = self._task._role._role_path return cwd def _write_backup(self, host, contents): backup_path = self._get_working_path() + '/backup' if not os.path.exists(backup_path): os.mkdir(backup_path) for fn in glob.glob('%s/%s*' % (backup_path, host)): os.remove(fn) tstamp = time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime(time.time())) filename = '%s/%s_config.%s' % (backup_path, host, tstamp) open(filename, 'w').write(contents) return filename def _handle_template(self): src = self._task.args.get('src') working_path = self._get_working_path() if os.path.isabs(src) or urlsplit('src').scheme: source = src else: source = self._loader.path_dwim_relative(working_path, 'templates', src) if not source: source = self._loader.path_dwim_relative(working_path, src) if not os.path.exists(source): raise ValueError('path specified in src not found') try: with open(source, 'r') as f: template_data = to_text(f.read()) except IOError: return dict(failed=True, msg='unable to load src file') # Create a template search path in the following order: # [working_path, self_role_path, dependent_role_paths, dirname(source)] searchpath = [working_path] if self._task._role is not None: searchpath.append(self._task._role._role_path) if hasattr(self._task, "_block:"): dep_chain = self._task._block.get_dep_chain() if dep_chain is not None: for role in dep_chain: searchpath.append(role._role_path) searchpath.append(os.path.dirname(source)) self._templar.environment.loader.searchpath = searchpath self._task.args['src'] = self._templar.template(template_data)
eeshangarg/oh-mainline
refs/heads/master
vendor/packages/twisted/twisted/words/test/test_ircsupport.py
17
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.words.im.ircsupport}. """ from twisted.trial.unittest import TestCase from twisted.test.proto_helpers import StringTransport from twisted.words.im.basechat import Conversation, ChatUI from twisted.words.im.ircsupport import IRCAccount, IRCProto class StubConversation(Conversation): def show(self): pass class StubChatUI(ChatUI): def getGroupConversation(self, group, Class=StubConversation, stayHidden=0): return ChatUI.getGroupConversation(self, group, Class, stayHidden) class IRCProtoTests(TestCase): """ Tests for L{IRCProto}. """ def setUp(self): self.account = IRCAccount( "Some account", False, "alice", None, "example.com", 6667) self.proto = IRCProto(self.account, StubChatUI(), None) def test_login(self): """ When L{IRCProto} is connected to a transport, it sends I{NICK} and I{USER} commands with the username from the account object. """ transport = StringTransport() self.proto.makeConnection(transport) self.assertEquals( transport.value(), "NICK alice\r\n" "USER alice foo bar :Twisted-IM user\r\n") def test_authenticate(self): """ If created with an account with a password, L{IRCProto} sends a I{PASS} command before the I{NICK} and I{USER} commands. """ self.account.password = "secret" transport = StringTransport() self.proto.makeConnection(transport) self.assertEquals( transport.value(), "PASS :secret\r\n" "NICK alice\r\n" "USER alice foo bar :Twisted-IM user\r\n") def test_channels(self): """ If created with an account with a list of channels, L{IRCProto} joins each of those channels after registering. """ self.account.channels = ['#foo', '#bar'] transport = StringTransport() self.proto.makeConnection(transport) self.assertEquals( transport.value(), "NICK alice\r\n" "USER alice foo bar :Twisted-IM user\r\n" "JOIN #foo\r\n" "JOIN #bar\r\n")
grimmjow8/ansible
refs/heads/devel
contrib/inventory/vbox.py
57
#!/usr/bin/env python # This file is part of Ansible, # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. import sys from subprocess import Popen,PIPE try: import json except ImportError: import simplejson as json class SetEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, set): return list(obj) return json.JSONEncoder.default(self, obj) VBOX="VBoxManage" def get_hosts(host=None): returned = {} try: if host: p = Popen([VBOX, 'showvminfo', host], stdout=PIPE) else: returned = { 'all': set(), '_metadata': {} } p = Popen([VBOX, 'list', '-l', 'vms'], stdout=PIPE) except: sys.exit(1) hostvars = {} prevkey = pref_k = '' for line in p.stdout.readlines(): try: k,v = line.split(':',1) except: continue if k == '': continue v = v.strip() if k.startswith('Name'): if v not in hostvars: curname = v hostvars[curname] = {} try: # try to get network info x = Popen([VBOX, 'guestproperty', 'get', curname,"/VirtualBox/GuestInfo/Net/0/V4/IP"],stdout=PIPE) ipinfo = x.stdout.read() if 'Value' in ipinfo: a,ip = ipinfo.split(':',1) hostvars[curname]['ansible_ssh_host'] = ip.strip() except: pass continue if not host: if k == 'Groups': for group in v.split('/'): if group: if group not in returned: returned[group] = set() returned[group].add(curname) returned['all'].add(curname) continue pref_k = 'vbox_' + k.strip().replace(' ','_') if k.startswith(' '): if prevkey not in hostvars[curname]: hostvars[curname][prevkey] = {} hostvars[curname][prevkey][pref_k]= v else: if v != '': hostvars[curname][pref_k] = v prevkey = pref_k if not host: returned['_metadata']['hostvars'] = hostvars else: returned = hostvars[host] return returned if __name__ == '__main__': inventory = {} hostname = None if len(sys.argv) > 1: if sys.argv[1] == "--host": hostname = sys.argv[2] if hostname: inventory = get_hosts(hostname) else: inventory = get_hosts() sys.stdout.write(json.dumps(inventory, indent=2, cls=SetEncoder))
box/box-python-sdk
refs/heads/main
test/unit/auth/test_jwt_auth.py
1
# coding: utf-8 from __future__ import absolute_import, unicode_literals from contextlib import contextmanager from datetime import datetime, timedelta import io from itertools import cycle, product import json import random import string from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, generate_private_key as generate_rsa_private_key from cryptography.hazmat.primitives import serialization from mock import Mock, mock_open, patch, sentinel, call import pytest import pytz import requests from six import binary_type, string_types, text_type from boxsdk.auth.jwt_auth import JWTAuth from boxsdk.exception import BoxOAuthException from boxsdk.config import API from boxsdk.object.user import User @pytest.fixture(params=[16, 32, 128]) def jti_length(request): return request.param @pytest.fixture(params=('RS256', 'RS512')) def jwt_algorithm(request): return request.param @pytest.fixture(scope='module') def jwt_key_id(): return 'jwt_key_id_1' @pytest.fixture(scope='module') def rsa_private_key_object(): return generate_rsa_private_key(public_exponent=65537, key_size=4096, backend=default_backend()) @pytest.fixture(params=(None, b'strong_password')) def rsa_passphrase(request): return request.param @pytest.fixture def rsa_private_key_bytes(rsa_private_key_object, rsa_passphrase): encryption = serialization.BestAvailableEncryption(rsa_passphrase) if rsa_passphrase else serialization.NoEncryption() return rsa_private_key_object.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=encryption, ) @pytest.fixture(scope='function') def successful_token_response(successful_token_mock, successful_token_json_response): # pylint:disable=redefined-outer-name response = successful_token_json_response.copy() del response['refresh_token'] successful_token_mock.json = Mock(return_value=response) successful_token_mock.ok = True successful_token_mock.content = json.dumps(response) successful_token_mock.status_code = 200 return successful_token_mock @pytest.mark.parametrize(('key_file', 'key_data'), [(None, None), ('fake sys path', 'fake key data')]) @pytest.mark.parametrize('rsa_passphrase', [None]) def test_jwt_auth_init_raises_type_error_unless_exactly_one_of_rsa_private_key_file_or_data_is_given(key_file, key_data, rsa_private_key_bytes): kwargs = dict( rsa_private_key_data=rsa_private_key_bytes, client_id=None, client_secret=None, jwt_key_id=None, enterprise_id=None, ) JWTAuth(**kwargs) kwargs.update(rsa_private_key_file_sys_path=key_file, rsa_private_key_data=key_data) with pytest.raises(TypeError): JWTAuth(**kwargs) @pytest.mark.parametrize('key_data', [object(), u'ƒøø']) @pytest.mark.parametrize('rsa_passphrase', [None]) def test_jwt_auth_init_raises_type_error_if_rsa_private_key_data_has_unexpected_type(key_data, rsa_private_key_bytes): kwargs = dict( rsa_private_key_data=rsa_private_key_bytes, client_id=None, client_secret=None, jwt_key_id=None, enterprise_id=None, ) JWTAuth(**kwargs) kwargs.update(rsa_private_key_data=key_data) with pytest.raises(TypeError): JWTAuth(**kwargs) @pytest.mark.parametrize('rsa_private_key_data_type', [io.BytesIO, text_type, binary_type, RSAPrivateKey]) def test_jwt_auth_init_accepts_rsa_private_key_data(rsa_private_key_bytes, rsa_passphrase, rsa_private_key_data_type): if rsa_private_key_data_type is text_type: rsa_private_key_data = text_type(rsa_private_key_bytes.decode('ascii')) elif rsa_private_key_data_type is RSAPrivateKey: rsa_private_key_data = serialization.load_pem_private_key( rsa_private_key_bytes, password=rsa_passphrase, backend=default_backend(), ) else: rsa_private_key_data = rsa_private_key_data_type(rsa_private_key_bytes) JWTAuth( rsa_private_key_data=rsa_private_key_data, rsa_private_key_passphrase=rsa_passphrase, client_id=None, client_secret=None, jwt_key_id=None, enterprise_id=None, ) @pytest.fixture(params=[False, True]) def pass_private_key_by_path(request): """For jwt_auth_init_mocks, whether to pass the private key via sys_path (True) or pass the data directly (False).""" return request.param @pytest.fixture def jwt_auth_init_mocks( mock_box_session, successful_token_response, jwt_algorithm, jwt_key_id, rsa_passphrase, rsa_private_key_bytes, pass_private_key_by_path, ): # pylint:disable=redefined-outer-name @contextmanager def _jwt_auth_init_mocks(**kwargs): assert_authed = kwargs.pop('assert_authed', True) fake_client_id = 'fake_client_id' fake_client_secret = 'fake_client_secret' assertion = Mock() data = { 'grant_type': JWTAuth._GRANT_TYPE, # pylint:disable=protected-access 'client_id': fake_client_id, 'client_secret': fake_client_secret, 'assertion': assertion, 'box_device_id': '0', 'box_device_name': 'my_awesome_device', } mock_box_session.request.return_value = successful_token_response with patch('boxsdk.auth.jwt_auth.open', mock_open(read_data=rsa_private_key_bytes), create=True) as jwt_auth_open: with patch('cryptography.hazmat.primitives.serialization.load_pem_private_key') as load_pem_private_key: oauth = JWTAuth( client_id=fake_client_id, client_secret=fake_client_secret, rsa_private_key_file_sys_path=(sentinel.rsa_path if pass_private_key_by_path else None), rsa_private_key_data=(None if pass_private_key_by_path else rsa_private_key_bytes), rsa_private_key_passphrase=rsa_passphrase, session=mock_box_session, box_device_name='my_awesome_device', jwt_algorithm=jwt_algorithm, jwt_key_id=jwt_key_id, enterprise_id=kwargs.pop('enterprise_id', None), **kwargs ) if pass_private_key_by_path: jwt_auth_open.assert_called_once_with(sentinel.rsa_path, 'rb') jwt_auth_open.return_value.read.assert_called_once_with() # pylint:disable=no-member else: jwt_auth_open.assert_not_called() load_pem_private_key.assert_called_once_with( rsa_private_key_bytes, password=rsa_passphrase, backend=default_backend(), ) yield oauth, assertion, fake_client_id, load_pem_private_key.return_value if assert_authed: mock_box_session.request.assert_called_once_with( 'POST', '{0}/token'.format(API.OAUTH2_API_URL), data=data, headers={'content-type': 'application/x-www-form-urlencoded'}, access_token=None, ) assert oauth.access_token == successful_token_response.json()['access_token'] return _jwt_auth_init_mocks def test_refresh_authenticates_with_user_if_enterprise_id_and_user_both_passed_to_constructor(jwt_auth_init_and_auth_mocks): user = 'fake_user_id' with jwt_auth_init_and_auth_mocks(sub=user, sub_type='user', enterprise_id='fake_enterprise_id', user=user) as oauth: oauth.refresh(None) @pytest.mark.parametrize('jwt_auth_method_name', ['authenticate_user', 'authenticate_instance']) def test_authenticate_raises_value_error_if_sub_was_never_given(jwt_auth_init_mocks, jwt_auth_method_name): with jwt_auth_init_mocks(assert_authed=False) as params: auth = params[0] authenticate_method = getattr(auth, jwt_auth_method_name) with pytest.raises(ValueError): authenticate_method() def test_jwt_auth_constructor_raises_type_error_if_user_is_unsupported_type(jwt_auth_init_mocks): with pytest.raises(TypeError): with jwt_auth_init_mocks(user=object()): assert False def test_authenticate_user_raises_type_error_if_user_is_unsupported_type(jwt_auth_init_mocks): with jwt_auth_init_mocks(assert_authed=False) as params: auth = params[0] with pytest.raises(TypeError): auth.authenticate_user(object()) @pytest.mark.parametrize('user_id_for_init', [None, 'fake_user_id_1']) def test_authenticate_user_saves_user_id_for_future_calls(jwt_auth_init_and_auth_mocks, user_id_for_init, jwt_encode): def assert_jwt_encode_call_args(user_id): assert jwt_encode.call_args[0][0]['sub'] == user_id assert jwt_encode.call_args[0][0]['box_sub_type'] == 'user' jwt_encode.call_args = None with jwt_auth_init_and_auth_mocks(sub=None, sub_type=None, assert_authed=False, user=user_id_for_init) as auth: for new_user_id in ['fake_user_id_2', 'fake_user_id_3']: auth.authenticate_user(new_user_id) assert_jwt_encode_call_args(new_user_id) auth.authenticate_user() assert_jwt_encode_call_args(new_user_id) def test_authenticate_instance_raises_value_error_if_different_enterprise_id_is_given(jwt_auth_init_mocks): with jwt_auth_init_mocks(enterprise_id='fake_enterprise_id_1', assert_authed=False) as params: auth = params[0] with pytest.raises(ValueError): auth.authenticate_instance('fake_enterprise_id_2') def test_authenticate_instance_saves_enterprise_id_for_future_calls(jwt_auth_init_and_auth_mocks): enterprise_id = 'fake_enterprise_id' with jwt_auth_init_and_auth_mocks(sub=enterprise_id, sub_type='enterprise', assert_authed=False) as auth: auth.authenticate_instance(enterprise_id) auth.authenticate_instance() auth.authenticate_instance(enterprise_id) with pytest.raises(ValueError): auth.authenticate_instance('fake_enterprise_id_2') @pytest.yield_fixture def jwt_encode(): with patch('jwt.encode') as patched_jwt_encode: yield patched_jwt_encode @pytest.fixture def jwt_auth_auth_mocks(jti_length, jwt_algorithm, jwt_key_id, jwt_encode): @contextmanager def _jwt_auth_auth_mocks(sub, sub_type, oauth, assertion, client_id, secret, assert_authed=True): # pylint:disable=redefined-outer-name with patch('boxsdk.auth.jwt_auth.datetime') as mock_datetime: with patch('boxsdk.auth.jwt_auth.random.SystemRandom') as mock_system_random: jwt_encode.return_value = assertion mock_datetime.utcnow.return_value = datetime(2015, 7, 6, 12, 1, 2) mock_datetime.return_value = datetime(1970, 1, 1) now_plus_30 = mock_datetime.utcnow.return_value + timedelta(seconds=30) exp = int((now_plus_30 - datetime(1970, 1, 1)).total_seconds()) system_random = mock_system_random.return_value system_random.randint.return_value = jti_length random_choices = [random.random() for _ in range(jti_length)] # Use cycle so that we can do auth more than once inside the context manager. system_random.random.side_effect = cycle(random_choices) ascii_alphabet = string.ascii_letters + string.digits ascii_len = len(ascii_alphabet) jti = ''.join(ascii_alphabet[int(r * ascii_len)] for r in random_choices) yield oauth if assert_authed: system_random.randint.assert_called_once_with(16, 128) assert len(system_random.random.mock_calls) == jti_length jwt_encode.assert_called_once_with({ 'iss': client_id, 'sub': sub, 'box_sub_type': sub_type, 'aud': 'https://api.box.com/oauth2/token', 'jti': jti, 'exp': exp, }, secret, algorithm=jwt_algorithm, headers={'kid': jwt_key_id}) return _jwt_auth_auth_mocks @pytest.fixture def jwt_auth_init_and_auth_mocks(jwt_auth_init_mocks, jwt_auth_auth_mocks): @contextmanager def _jwt_auth_init_and_auth_mocks(sub, sub_type, *jwt_auth_init_mocks_args, **jwt_auth_init_mocks_kwargs): assert_authed = jwt_auth_init_mocks_kwargs.pop('assert_authed', True) with jwt_auth_init_mocks(*jwt_auth_init_mocks_args, assert_authed=assert_authed, **jwt_auth_init_mocks_kwargs) as params: with jwt_auth_auth_mocks(sub, sub_type, *params, assert_authed=assert_authed) as oauth: yield oauth return _jwt_auth_init_and_auth_mocks @pytest.mark.parametrize( ('user', 'pass_in_init'), list(product([str('fake_user_id'), text_type('fake_user_id'), User(None, 'fake_user_id')], [False, True])), ) def test_authenticate_user_sends_post_request_with_correct_params(jwt_auth_init_and_auth_mocks, user, pass_in_init): # pylint:disable=redefined-outer-name if isinstance(user, User): user_id = user.object_id elif isinstance(user, string_types): user_id = user else: raise NotImplementedError init_kwargs = {} authenticate_params = [] if pass_in_init: init_kwargs['user'] = user else: authenticate_params.append(user) with jwt_auth_init_and_auth_mocks(user_id, 'user', **init_kwargs) as oauth: oauth.authenticate_user(*authenticate_params) @pytest.mark.parametrize(('pass_in_init', 'pass_in_auth'), [(True, False), (False, True), (True, True)]) def test_authenticate_instance_sends_post_request_with_correct_params(jwt_auth_init_and_auth_mocks, pass_in_init, pass_in_auth): # pylint:disable=redefined-outer-name enterprise_id = 'fake_enterprise_id' init_kwargs = {} auth_params = [] if pass_in_init: init_kwargs['enterprise_id'] = enterprise_id if pass_in_auth: auth_params.append(enterprise_id) with jwt_auth_init_and_auth_mocks(enterprise_id, 'enterprise', **init_kwargs) as oauth: oauth.authenticate_instance(*auth_params) def test_refresh_app_user_sends_post_request_with_correct_params(jwt_auth_init_and_auth_mocks): # pylint:disable=redefined-outer-name fake_user_id = 'fake_user_id' with jwt_auth_init_and_auth_mocks(fake_user_id, 'user', user=fake_user_id) as oauth: oauth.refresh(None) def test_refresh_instance_sends_post_request_with_correct_params(jwt_auth_init_and_auth_mocks): # pylint:disable=redefined-outer-name enterprise_id = 'fake_enterprise_id' with jwt_auth_init_and_auth_mocks(enterprise_id, 'enterprise', enterprise_id=enterprise_id) as oauth: oauth.refresh(None) @pytest.fixture() def jwt_subclass_that_just_stores_params(): class StoreParamJWTAuth(JWTAuth): def __init__(self, **kwargs): self.kwargs = kwargs super(StoreParamJWTAuth, self).__init__(**kwargs) return StoreParamJWTAuth @pytest.fixture def fake_client_id(): return 'fake_client_id' @pytest.fixture def fake_client_secret(): return 'fake_client_secret' @pytest.fixture def fake_enterprise_id(): return 'fake_enterprise_id' @pytest.fixture def app_config_json_content( fake_client_id, fake_client_secret, fake_enterprise_id, jwt_key_id, rsa_private_key_bytes, rsa_passphrase, ): template = r""" {{ "boxAppSettings": {{ "clientID": "{client_id}", "clientSecret": "{client_secret}", "appAuth": {{ "publicKeyID": "{jwt_key_id}", "privateKey": "{private_key}", "passphrase": {passphrase} }} }}, "enterpriseID": {enterprise_id} }}""" return template.format( client_id=fake_client_id, client_secret=fake_client_secret, jwt_key_id=jwt_key_id, private_key=rsa_private_key_bytes.replace(b"\n", b"\\n").decode(), passphrase=json.dumps(rsa_passphrase and rsa_passphrase.decode()), enterprise_id=json.dumps(fake_enterprise_id), ) @pytest.fixture() def assert_jwt_kwargs_expected( fake_client_id, fake_client_secret, fake_enterprise_id, jwt_key_id, rsa_private_key_bytes, rsa_passphrase, ): def _assert_jwt_kwargs_expected(jwt_auth): assert jwt_auth.kwargs['client_id'] == fake_client_id assert jwt_auth.kwargs['client_secret'] == fake_client_secret assert jwt_auth.kwargs['enterprise_id'] == fake_enterprise_id assert jwt_auth.kwargs['jwt_key_id'] == jwt_key_id assert jwt_auth.kwargs['rsa_private_key_data'] == rsa_private_key_bytes.decode() assert jwt_auth.kwargs['rsa_private_key_passphrase'] == (rsa_passphrase and rsa_passphrase.decode()) return _assert_jwt_kwargs_expected def test_from_config_file( jwt_subclass_that_just_stores_params, app_config_json_content, assert_jwt_kwargs_expected, ): # pylint:disable=redefined-outer-name with patch('boxsdk.auth.jwt_auth.open', mock_open(read_data=app_config_json_content), create=True): jwt_auth_from_config_file = jwt_subclass_that_just_stores_params.from_settings_file('fake_config_file_sys_path') assert_jwt_kwargs_expected(jwt_auth_from_config_file) def test_from_settings_dictionary( jwt_subclass_that_just_stores_params, app_config_json_content, assert_jwt_kwargs_expected, ): jwt_auth_from_dictionary = jwt_subclass_that_just_stores_params.from_settings_dictionary(json.loads(app_config_json_content)) assert_jwt_kwargs_expected(jwt_auth_from_dictionary) @pytest.fixture def expect_auth_retry(status_code, error_description, include_date_header, error_code): return status_code == 400 and 'exp' in error_description and include_date_header and error_code == 'invalid_grant' @pytest.fixture def box_datetime(): return datetime.now(tz=pytz.utc) - timedelta(100) @pytest.fixture def unsuccessful_jwt_response(box_datetime, status_code, error_description, include_date_header, error_code): headers = {'Date': box_datetime.strftime('%a, %d %b %Y %H:%M:%S %Z')} if include_date_header else {} unsuccessful_response = Mock(requests.Response(), headers=headers) unsuccessful_response.json.return_value = {'error_description': error_description, 'error': error_code} unsuccessful_response.status_code = status_code unsuccessful_response.ok = False return unsuccessful_response @pytest.mark.parametrize('jwt_algorithm', ('RS512',)) @pytest.mark.parametrize('rsa_passphrase', (None,)) @pytest.mark.parametrize('pass_private_key_by_path', (False,)) @pytest.mark.parametrize('status_code', (400, 401)) @pytest.mark.parametrize('error_description', ('invalid box_sub_type claim', 'invalid kid', "check the 'exp' claim")) @pytest.mark.parametrize('error_code', ('invalid_grant', 'bad_request')) @pytest.mark.parametrize('include_date_header', (True, False)) def test_auth_retry_for_invalid_exp_claim( jwt_auth_init_mocks, expect_auth_retry, unsuccessful_jwt_response, box_datetime, ): # pylint:disable=redefined-outer-name enterprise_id = 'fake_enterprise_id' with jwt_auth_init_mocks(assert_authed=False) as params: auth = params[0] with patch.object(auth, '_construct_and_send_jwt_auth') as mock_send_jwt: mock_send_jwt.side_effect = [BoxOAuthException(400, network_response=unsuccessful_jwt_response), 'jwt_token'] if not expect_auth_retry: with pytest.raises(BoxOAuthException): auth.authenticate_instance(enterprise_id) else: auth.authenticate_instance(enterprise_id) expected_calls = [call(enterprise_id, 'enterprise', None)] if expect_auth_retry: expected_calls.append(call(enterprise_id, 'enterprise', box_datetime.replace(microsecond=0, tzinfo=None))) assert len(mock_send_jwt.mock_calls) == len(expected_calls) mock_send_jwt.assert_has_calls(expected_calls) @pytest.mark.parametrize('jwt_algorithm', ('RS512',)) @pytest.mark.parametrize('rsa_passphrase', (None,)) @pytest.mark.parametrize('pass_private_key_by_path', (False,)) @pytest.mark.parametrize('status_code', (429,)) @pytest.mark.parametrize('error_description', ('Request rate limit exceeded',)) @pytest.mark.parametrize('error_code', ('rate_limit_exceeded',)) @pytest.mark.parametrize('include_date_header', (False,)) def test_auth_retry_for_rate_limit_error( jwt_auth_init_mocks, unsuccessful_jwt_response, ): # pylint:disable=redefined-outer-name enterprise_id = 'fake_enterprise_id' with jwt_auth_init_mocks(assert_authed=False) as params: auth = params[0] with patch.object(auth, '_construct_and_send_jwt_auth') as mock_send_jwt: side_effect = [] expected_calls = [] # Retries multiple times, but less than max retries. Then succeeds when it gets a token. for _ in range(API.MAX_RETRY_ATTEMPTS - 2): side_effect.append(BoxOAuthException(429, network_response=unsuccessful_jwt_response)) expected_calls.append(call(enterprise_id, 'enterprise', None)) side_effect.append('jwt_token') expected_calls.append(call(enterprise_id, 'enterprise', None)) mock_send_jwt.side_effect = side_effect auth.authenticate_instance(enterprise_id) assert len(mock_send_jwt.mock_calls) == len(expected_calls) mock_send_jwt.assert_has_calls(expected_calls) @pytest.mark.parametrize('jwt_algorithm', ('RS512',)) @pytest.mark.parametrize('rsa_passphrase', (None,)) @pytest.mark.parametrize('pass_private_key_by_path', (False,)) @pytest.mark.parametrize('status_code', (429,)) @pytest.mark.parametrize('error_description', ('Request rate limit exceeded',)) @pytest.mark.parametrize('error_code', ('rate_limit_exceeded',)) @pytest.mark.parametrize('include_date_header', (False,)) def test_auth_max_retries_for_rate_limit_error( jwt_auth_init_mocks, unsuccessful_jwt_response, ): # pylint:disable=redefined-outer-name enterprise_id = 'fake_enterprise_id' with jwt_auth_init_mocks(assert_authed=False) as params: auth = params[0] with patch.object(auth, '_construct_and_send_jwt_auth') as mock_send_jwt: side_effect = [] expected_calls = [] # Retries max number of times, then throws the error for _ in range(API.MAX_RETRY_ATTEMPTS + 1): side_effect.append(BoxOAuthException(429, network_response=unsuccessful_jwt_response)) expected_calls.append(call(enterprise_id, 'enterprise', None)) mock_send_jwt.side_effect = side_effect with pytest.raises(BoxOAuthException) as error: auth.authenticate_instance(enterprise_id) assert error.value.status == 429 assert len(mock_send_jwt.mock_calls) == len(expected_calls) mock_send_jwt.assert_has_calls(expected_calls) @pytest.mark.parametrize('jwt_algorithm', ('RS512',)) @pytest.mark.parametrize('rsa_passphrase', (None,)) @pytest.mark.parametrize('pass_private_key_by_path', (False,)) @pytest.mark.parametrize('status_code', (500,)) @pytest.mark.parametrize('error_description', ('Internal Server Error',)) @pytest.mark.parametrize('error_code', ('internal_server_error',)) @pytest.mark.parametrize('include_date_header', (False,)) def test_auth_retry_for_internal_server_error( jwt_auth_init_mocks, unsuccessful_jwt_response, ): # pylint:disable=redefined-outer-name enterprise_id = 'fake_enterprise_id' with jwt_auth_init_mocks(assert_authed=False) as params: auth = params[0] with patch.object(auth, '_construct_and_send_jwt_auth') as mock_send_jwt: side_effect = [] expected_calls = [] # Retries multiple times, but less than max retries. Then succeeds when it gets a token. for _ in range(API.MAX_RETRY_ATTEMPTS - 2): side_effect.append(BoxOAuthException(500, network_response=unsuccessful_jwt_response)) expected_calls.append(call(enterprise_id, 'enterprise', None)) side_effect.append('jwt_token') expected_calls.append(call(enterprise_id, 'enterprise', None)) mock_send_jwt.side_effect = side_effect auth.authenticate_instance(enterprise_id) assert len(mock_send_jwt.mock_calls) == len(expected_calls) mock_send_jwt.assert_has_calls(expected_calls) @pytest.mark.parametrize('jwt_algorithm', ('RS512',)) @pytest.mark.parametrize('rsa_passphrase', (None,)) @pytest.mark.parametrize('pass_private_key_by_path', (False,)) @pytest.mark.parametrize('status_code', (500,)) @pytest.mark.parametrize('error_description', ('Internal Server Error',)) @pytest.mark.parametrize('error_code', ('internal_server_error',)) @pytest.mark.parametrize('include_date_header', (False,)) def test_auth_max_retries_for_internal_server_error( jwt_auth_init_mocks, unsuccessful_jwt_response, ): # pylint:disable=redefined-outer-name enterprise_id = 'fake_enterprise_id' with jwt_auth_init_mocks(assert_authed=False) as params: auth = params[0] with patch.object(auth, '_construct_and_send_jwt_auth') as mock_send_jwt: side_effect = [] expected_calls = [] # Retries max number of times, then throws the error for _ in range(API.MAX_RETRY_ATTEMPTS + 1): side_effect.append(BoxOAuthException(500, network_response=unsuccessful_jwt_response)) expected_calls.append(call(enterprise_id, 'enterprise', None)) mock_send_jwt.side_effect = side_effect with pytest.raises(BoxOAuthException) as error: auth.authenticate_instance(enterprise_id) assert error.value.status == 500 assert len(mock_send_jwt.mock_calls) == len(expected_calls) mock_send_jwt.assert_has_calls(expected_calls)
lokirius/python-for-android
refs/heads/master
python3-alpha/python3-src/Lib/test/test_bz2.py
50
#!/usr/bin/env python3 from test import support from test.support import TESTFN import unittest from io import BytesIO import os import subprocess import sys try: import threading except ImportError: threading = None # Skip tests if the bz2 module doesn't exist. bz2 = support.import_module('bz2') from bz2 import BZ2File, BZ2Compressor, BZ2Decompressor has_cmdline_bunzip2 = sys.platform not in ("win32", "os2emx") class BaseTest(unittest.TestCase): "Base for other testcases." TEXT = b'root:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:\ndaemon:x:2:2:daemon:/sbin:\nadm:x:3:4:adm:/var/adm:\nlp:x:4:7:lp:/var/spool/lpd:\nsync:x:5:0:sync:/sbin:/bin/sync\nshutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\nhalt:x:7:0:halt:/sbin:/sbin/halt\nmail:x:8:12:mail:/var/spool/mail:\nnews:x:9:13:news:/var/spool/news:\nuucp:x:10:14:uucp:/var/spool/uucp:\noperator:x:11:0:operator:/root:\ngames:x:12:100:games:/usr/games:\ngopher:x:13:30:gopher:/usr/lib/gopher-data:\nftp:x:14:50:FTP User:/var/ftp:/bin/bash\nnobody:x:65534:65534:Nobody:/home:\npostfix:x:100:101:postfix:/var/spool/postfix:\nniemeyer:x:500:500::/home/niemeyer:/bin/bash\npostgres:x:101:102:PostgreSQL Server:/var/lib/pgsql:/bin/bash\nmysql:x:102:103:MySQL server:/var/lib/mysql:/bin/bash\nwww:x:103:104::/var/www:/bin/false\n' DATA = b'BZh91AY&SY.\xc8N\x18\x00\x01>_\x80\x00\x10@\x02\xff\xf0\x01\x07n\x00?\xe7\xff\xe00\x01\x99\xaa\x00\xc0\x03F\x86\x8c#&\x83F\x9a\x03\x06\xa6\xd0\xa6\x93M\x0fQ\xa7\xa8\x06\x804hh\x12$\x11\xa4i4\xf14S\xd2<Q\xb5\x0fH\xd3\xd4\xdd\xd5\x87\xbb\xf8\x94\r\x8f\xafI\x12\xe1\xc9\xf8/E\x00pu\x89\x12]\xc9\xbbDL\nQ\x0e\t1\x12\xdf\xa0\xc0\x97\xac2O9\x89\x13\x94\x0e\x1c7\x0ed\x95I\x0c\xaaJ\xa4\x18L\x10\x05#\x9c\xaf\xba\xbc/\x97\x8a#C\xc8\xe1\x8cW\xf9\xe2\xd0\xd6M\xa7\x8bXa<e\x84t\xcbL\xb3\xa7\xd9\xcd\xd1\xcb\x84.\xaf\xb3\xab\xab\xad`n}\xa0lh\tE,\x8eZ\x15\x17VH>\x88\xe5\xcd9gd6\x0b\n\xe9\x9b\xd5\x8a\x99\xf7\x08.K\x8ev\xfb\xf7xw\xbb\xdf\xa1\x92\xf1\xdd|/";\xa2\xba\x9f\xd5\xb1#A\xb6\xf6\xb3o\xc9\xc5y\\\xebO\xe7\x85\x9a\xbc\xb6f8\x952\xd5\xd7"%\x89>V,\xf7\xa6z\xe2\x9f\xa3\xdf\x11\x11"\xd6E)I\xa9\x13^\xca\xf3r\xd0\x03U\x922\xf26\xec\xb6\xed\x8b\xc3U\x13\x9d\xc5\x170\xa4\xfa^\x92\xacDF\x8a\x97\xd6\x19\xfe\xdd\xb8\xbd\x1a\x9a\x19\xa3\x80ankR\x8b\xe5\xd83]\xa9\xc6\x08\x82f\xf6\xb9"6l$\xb8j@\xc0\x8a\xb0l1..\xbak\x83ls\x15\xbc\xf4\xc1\x13\xbe\xf8E\xb8\x9d\r\xa8\x9dk\x84\xd3n\xfa\xacQ\x07\xb1%y\xaav\xb4\x08\xe0z\x1b\x16\xf5\x04\xe9\xcc\xb9\x08z\x1en7.G\xfc]\xc9\x14\xe1B@\xbb!8`' DATA_CRLF = b'BZh91AY&SY\xaez\xbbN\x00\x01H\xdf\x80\x00\x12@\x02\xff\xf0\x01\x07n\x00?\xe7\xff\xe0@\x01\xbc\xc6`\x86*\x8d=M\xa9\x9a\x86\xd0L@\x0fI\xa6!\xa1\x13\xc8\x88jdi\x8d@\x03@\x1a\x1a\x0c\x0c\x83 \x00\xc4h2\x19\x01\x82D\x84e\t\xe8\x99\x89\x19\x1ah\x00\r\x1a\x11\xaf\x9b\x0fG\xf5(\x1b\x1f?\t\x12\xcf\xb5\xfc\x95E\x00ps\x89\x12^\xa4\xdd\xa2&\x05(\x87\x04\x98\x89u\xe40%\xb6\x19\'\x8c\xc4\x89\xca\x07\x0e\x1b!\x91UIFU%C\x994!DI\xd2\xfa\xf0\xf1N8W\xde\x13A\xf5\x9cr%?\x9f3;I45A\xd1\x8bT\xb1<l\xba\xcb_\xc00xY\x17r\x17\x88\x08\x08@\xa0\ry@\x10\x04$)`\xf2\xce\x89z\xb0s\xec\x9b.iW\x9d\x81\xb5-+t\x9f\x1a\'\x97dB\xf5x\xb5\xbe.[.\xd7\x0e\x81\xe7\x08\x1cN`\x88\x10\xca\x87\xc3!"\x80\x92R\xa1/\xd1\xc0\xe6mf\xac\xbd\x99\xcca\xb3\x8780>\xa4\xc7\x8d\x1a\\"\xad\xa1\xabyBg\x15\xb9l\x88\x88\x91k"\x94\xa4\xd4\x89\xae*\xa6\x0b\x10\x0c\xd6\xd4m\xe86\xec\xb5j\x8a\x86j\';\xca.\x01I\xf2\xaaJ\xe8\x88\x8cU+t3\xfb\x0c\n\xa33\x13r2\r\x16\xe0\xb3(\xbf\x1d\x83r\xe7M\xf0D\x1365\xd8\x88\xd3\xa4\x92\xcb2\x06\x04\\\xc1\xb0\xea//\xbek&\xd8\xe6+t\xe5\xa1\x13\xada\x16\xder5"w]\xa2i\xb7[\x97R \xe2IT\xcd;Z\x04dk4\xad\x8a\t\xd3\x81z\x10\xf1:^`\xab\x1f\xc5\xdc\x91N\x14$+\x9e\xae\xd3\x80' if has_cmdline_bunzip2: def decompress(self, data): pop = subprocess.Popen("bunzip2", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) pop.stdin.write(data) pop.stdin.close() ret = pop.stdout.read() pop.stdout.close() if pop.wait() != 0: ret = bz2.decompress(data) return ret else: # bunzip2 isn't available to run on Windows. def decompress(self, data): return bz2.decompress(data) class BZ2FileTest(BaseTest): "Test BZ2File type miscellaneous methods." def setUp(self): self.filename = TESTFN def tearDown(self): if os.path.isfile(self.filename): os.unlink(self.filename) def createTempFile(self, crlf=0): with open(self.filename, "wb") as f: if crlf: data = self.DATA_CRLF else: data = self.DATA f.write(data) def testRead(self): # "Test BZ2File.read()" self.createTempFile() with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.read, None) self.assertEqual(bz2f.read(), self.TEXT) def testRead0(self): # Test BBZ2File.read(0)" self.createTempFile() with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.read, None) self.assertEqual(bz2f.read(0), b"") def testReadChunk10(self): # "Test BZ2File.read() in chunks of 10 bytes" self.createTempFile() with BZ2File(self.filename) as bz2f: text = b'' while 1: str = bz2f.read(10) if not str: break text += str self.assertEqual(text, self.TEXT) def testRead100(self): # "Test BZ2File.read(100)" self.createTempFile() with BZ2File(self.filename) as bz2f: self.assertEqual(bz2f.read(100), self.TEXT[:100]) def testReadLine(self): # "Test BZ2File.readline()" self.createTempFile() with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.readline, None) sio = BytesIO(self.TEXT) for line in sio.readlines(): self.assertEqual(bz2f.readline(), line) def testReadLines(self): # "Test BZ2File.readlines()" self.createTempFile() with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.readlines, None) sio = BytesIO(self.TEXT) self.assertEqual(bz2f.readlines(), sio.readlines()) def testIterator(self): # "Test iter(BZ2File)" self.createTempFile() with BZ2File(self.filename) as bz2f: sio = BytesIO(self.TEXT) self.assertEqual(list(iter(bz2f)), sio.readlines()) def testClosedIteratorDeadlock(self): # "Test that iteration on a closed bz2file releases the lock." # http://bugs.python.org/issue3309 self.createTempFile() bz2f = BZ2File(self.filename) bz2f.close() self.assertRaises(ValueError, bz2f.__next__) # This call will deadlock of the above .__next__ call failed to # release the lock. self.assertRaises(ValueError, bz2f.readlines) def testWrite(self): # "Test BZ2File.write()" with BZ2File(self.filename, "w") as bz2f: self.assertRaises(TypeError, bz2f.write) bz2f.write(self.TEXT) with open(self.filename, 'rb') as f: self.assertEqual(self.decompress(f.read()), self.TEXT) def testWriteChunks10(self): # "Test BZ2File.write() with chunks of 10 bytes" with BZ2File(self.filename, "w") as bz2f: n = 0 while 1: str = self.TEXT[n*10:(n+1)*10] if not str: break bz2f.write(str) n += 1 with open(self.filename, 'rb') as f: self.assertEqual(self.decompress(f.read()), self.TEXT) def testWriteLines(self): # "Test BZ2File.writelines()" with BZ2File(self.filename, "w") as bz2f: self.assertRaises(TypeError, bz2f.writelines) sio = BytesIO(self.TEXT) bz2f.writelines(sio.readlines()) # patch #1535500 self.assertRaises(ValueError, bz2f.writelines, ["a"]) with open(self.filename, 'rb') as f: self.assertEqual(self.decompress(f.read()), self.TEXT) def testWriteMethodsOnReadOnlyFile(self): with BZ2File(self.filename, "w") as bz2f: bz2f.write(b"abc") with BZ2File(self.filename, "r") as bz2f: self.assertRaises(IOError, bz2f.write, b"a") self.assertRaises(IOError, bz2f.writelines, [b"a"]) def testSeekForward(self): # "Test BZ2File.seek(150, 0)" self.createTempFile() with BZ2File(self.filename) as bz2f: self.assertRaises(TypeError, bz2f.seek) bz2f.seek(150) self.assertEqual(bz2f.read(), self.TEXT[150:]) def testSeekBackwards(self): # "Test BZ2File.seek(-150, 1)" self.createTempFile() with BZ2File(self.filename) as bz2f: bz2f.read(500) bz2f.seek(-150, 1) self.assertEqual(bz2f.read(), self.TEXT[500-150:]) def testSeekBackwardsFromEnd(self): # "Test BZ2File.seek(-150, 2)" self.createTempFile() with BZ2File(self.filename) as bz2f: bz2f.seek(-150, 2) self.assertEqual(bz2f.read(), self.TEXT[len(self.TEXT)-150:]) def testSeekPostEnd(self): # "Test BZ2File.seek(150000)" self.createTempFile() with BZ2File(self.filename) as bz2f: bz2f.seek(150000) self.assertEqual(bz2f.tell(), len(self.TEXT)) self.assertEqual(bz2f.read(), b"") def testSeekPostEndTwice(self): # "Test BZ2File.seek(150000) twice" self.createTempFile() with BZ2File(self.filename) as bz2f: bz2f.seek(150000) bz2f.seek(150000) self.assertEqual(bz2f.tell(), len(self.TEXT)) self.assertEqual(bz2f.read(), b"") def testSeekPreStart(self): # "Test BZ2File.seek(-150, 0)" self.createTempFile() with BZ2File(self.filename) as bz2f: bz2f.seek(-150) self.assertEqual(bz2f.tell(), 0) self.assertEqual(bz2f.read(), self.TEXT) def testOpenDel(self): # "Test opening and deleting a file many times" self.createTempFile() for i in range(10000): o = BZ2File(self.filename) del o def testOpenNonexistent(self): # "Test opening a nonexistent file" self.assertRaises(IOError, BZ2File, "/non/existent") def testBug1191043(self): # readlines() for files containing no newline data = b'BZh91AY&SY\xd9b\x89]\x00\x00\x00\x03\x80\x04\x00\x02\x00\x0c\x00 \x00!\x9ah3M\x13<]\xc9\x14\xe1BCe\x8a%t' with open(self.filename, "wb") as f: f.write(data) with BZ2File(self.filename) as bz2f: lines = bz2f.readlines() self.assertEqual(lines, [b'Test']) with BZ2File(self.filename) as bz2f: xlines = list(bz2f.readlines()) self.assertEqual(xlines, [b'Test']) def testContextProtocol(self): # BZ2File supports the context management protocol f = None with BZ2File(self.filename, "wb") as f: f.write(b"xxx") f = BZ2File(self.filename, "rb") f.close() try: with f: pass except ValueError: pass else: self.fail("__enter__ on a closed file didn't raise an exception") try: with BZ2File(self.filename, "wb") as f: 1/0 except ZeroDivisionError: pass else: self.fail("1/0 didn't raise an exception") @unittest.skipUnless(threading, 'Threading required for this test.') def testThreading(self): # Using a BZ2File from several threads doesn't deadlock (issue #7205). data = b"1" * 2**20 nthreads = 10 with bz2.BZ2File(self.filename, 'wb') as f: def comp(): for i in range(5): f.write(data) threads = [threading.Thread(target=comp) for i in range(nthreads)] for t in threads: t.start() for t in threads: t.join() def testMixedIterationReads(self): # Issue #8397: mixed iteration and reads should be forbidden. with bz2.BZ2File(self.filename, 'wb') as f: # The internal buffer size is hard-wired to 8192 bytes, we must # write out more than that for the test to stop half through # the buffer. f.write(self.TEXT * 100) with bz2.BZ2File(self.filename, 'rb') as f: next(f) self.assertRaises(ValueError, f.read) self.assertRaises(ValueError, f.readline) self.assertRaises(ValueError, f.readlines) class BZ2CompressorTest(BaseTest): def testCompress(self): # "Test BZ2Compressor.compress()/flush()" bz2c = BZ2Compressor() self.assertRaises(TypeError, bz2c.compress) data = bz2c.compress(self.TEXT) data += bz2c.flush() self.assertEqual(self.decompress(data), self.TEXT) def testCompressChunks10(self): # "Test BZ2Compressor.compress()/flush() with chunks of 10 bytes" bz2c = BZ2Compressor() n = 0 data = b'' while 1: str = self.TEXT[n*10:(n+1)*10] if not str: break data += bz2c.compress(str) n += 1 data += bz2c.flush() self.assertEqual(self.decompress(data), self.TEXT) class BZ2DecompressorTest(BaseTest): def test_Constructor(self): self.assertRaises(TypeError, BZ2Decompressor, 42) def testDecompress(self): # "Test BZ2Decompressor.decompress()" bz2d = BZ2Decompressor() self.assertRaises(TypeError, bz2d.decompress) text = bz2d.decompress(self.DATA) self.assertEqual(text, self.TEXT) def testDecompressChunks10(self): # "Test BZ2Decompressor.decompress() with chunks of 10 bytes" bz2d = BZ2Decompressor() text = b'' n = 0 while 1: str = self.DATA[n*10:(n+1)*10] if not str: break text += bz2d.decompress(str) n += 1 self.assertEqual(text, self.TEXT) def testDecompressUnusedData(self): # "Test BZ2Decompressor.decompress() with unused data" bz2d = BZ2Decompressor() unused_data = b"this is unused data" text = bz2d.decompress(self.DATA+unused_data) self.assertEqual(text, self.TEXT) self.assertEqual(bz2d.unused_data, unused_data) def testEOFError(self): # "Calling BZ2Decompressor.decompress() after EOS must raise EOFError" bz2d = BZ2Decompressor() text = bz2d.decompress(self.DATA) self.assertRaises(EOFError, bz2d.decompress, b"anything") class FuncTest(BaseTest): "Test module functions" def testCompress(self): # "Test compress() function" data = bz2.compress(self.TEXT) self.assertEqual(self.decompress(data), self.TEXT) def testDecompress(self): # "Test decompress() function" text = bz2.decompress(self.DATA) self.assertEqual(text, self.TEXT) def testDecompressEmpty(self): # "Test decompress() function with empty string" text = bz2.decompress(b"") self.assertEqual(text, b"") def testDecompressIncomplete(self): # "Test decompress() function with incomplete data" self.assertRaises(ValueError, bz2.decompress, self.DATA[:-10]) def test_main(): support.run_unittest( BZ2FileTest, BZ2CompressorTest, BZ2DecompressorTest, FuncTest ) support.reap_children() if __name__ == '__main__': test_main() # vim:ts=4:sw=4
kiruthikak/foursquared.eclair
refs/heads/master
util/gen_parser.py
262
#!/usr/bin/python import datetime import sys import textwrap import common from xml.dom import pulldom PARSER = """\ /** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.parsers; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.types.%(type_name)s; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Auto-generated: %(timestamp)s * * @author Joe LaPenna (joe@joelapenna.com) * @param <T> */ public class %(type_name)sParser extends AbstractParser<%(type_name)s> { private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.PARSER_DEBUG; @Override public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException, FoursquareError, FoursquareParseException { parser.require(XmlPullParser.START_TAG, null, null); %(type_name)s %(top_node_name)s = new %(type_name)s(); while (parser.nextTag() == XmlPullParser.START_TAG) { String name = parser.getName(); %(stanzas)s } else { // Consume something we don't understand. if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name); skipSubTree(parser); } } return %(top_node_name)s; } }""" BOOLEAN_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText())); """ GROUP_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser)); """ COMPLEX_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser)); """ STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(parser.nextText()); """ def main(): type_name, top_node_name, attributes = common.WalkNodesForAttributes( sys.argv[1]) GenerateClass(type_name, top_node_name, attributes) def GenerateClass(type_name, top_node_name, attributes): """generate it. type_name: the type of object the parser returns top_node_name: the name of the object the parser returns. per common.WalkNodsForAttributes """ stanzas = [] for name in sorted(attributes): typ, children = attributes[name] replacements = Replacements(top_node_name, name, typ, children) if typ == common.BOOLEAN: stanzas.append(BOOLEAN_STANZA % replacements) elif typ == common.GROUP: stanzas.append(GROUP_STANZA % replacements) elif typ in common.COMPLEX: stanzas.append(COMPLEX_STANZA % replacements) else: stanzas.append(STANZA % replacements) if stanzas: # pop off the extranious } else for the first conditional stanza. stanzas[0] = stanzas[0].replace('} else ', '', 1) replacements = Replacements(top_node_name, name, typ, [None]) replacements['stanzas'] = '\n'.join(stanzas).strip() print PARSER % replacements def Replacements(top_node_name, name, typ, children): # CameCaseClassName type_name = ''.join([word.capitalize() for word in top_node_name.split('_')]) # CamelCaseClassName camel_name = ''.join([word.capitalize() for word in name.split('_')]) # camelCaseLocalName attribute_name = camel_name.lower().capitalize() # mFieldName field_name = 'm' + camel_name if children[0]: sub_parser_camel_case = children[0] + 'Parser' else: sub_parser_camel_case = (camel_name[:-1] + 'Parser') return { 'type_name': type_name, 'name': name, 'top_node_name': top_node_name, 'camel_name': camel_name, 'parser_name': typ + 'Parser', 'attribute_name': attribute_name, 'field_name': field_name, 'typ': typ, 'timestamp': datetime.datetime.now(), 'sub_parser_camel_case': sub_parser_camel_case, 'sub_type': children[0] } if __name__ == '__main__': main()
petteyg/intellij-community
refs/heads/master
python/testData/resolve/AttributeAssignedNearby.py
83
def foo(bar): bar.xyzzy = 1 print bar.xyzzy # <ref>
x303597316/hue
refs/heads/master
desktop/core/ext-py/PyYAML-3.09/examples/pygments-lexer/yaml.py
63
""" yaml.py Lexer for YAML, a human-friendly data serialization language (http://yaml.org/). Written by Kirill Simonov <xi@resolvent.net>. License: Whatever suitable for inclusion into the Pygments package. """ from pygments.lexer import \ ExtendedRegexLexer, LexerContext, include, bygroups from pygments.token import \ Text, Comment, Punctuation, Name, Literal __all__ = ['YAMLLexer'] class YAMLLexerContext(LexerContext): """Indentation context for the YAML lexer.""" def __init__(self, *args, **kwds): super(YAMLLexerContext, self).__init__(*args, **kwds) self.indent_stack = [] self.indent = -1 self.next_indent = 0 self.block_scalar_indent = None def something(TokenClass): """Do not produce empty tokens.""" def callback(lexer, match, context): text = match.group() if not text: return yield match.start(), TokenClass, text context.pos = match.end() return callback def reset_indent(TokenClass): """Reset the indentation levels.""" def callback(lexer, match, context): text = match.group() context.indent_stack = [] context.indent = -1 context.next_indent = 0 context.block_scalar_indent = None yield match.start(), TokenClass, text context.pos = match.end() return callback def save_indent(TokenClass, start=False): """Save a possible indentation level.""" def callback(lexer, match, context): text = match.group() extra = '' if start: context.next_indent = len(text) if context.next_indent < context.indent: while context.next_indent < context.indent: context.indent = context.indent_stack.pop() if context.next_indent > context.indent: extra = text[context.indent:] text = text[:context.indent] else: context.next_indent += len(text) if text: yield match.start(), TokenClass, text if extra: yield match.start()+len(text), TokenClass.Error, extra context.pos = match.end() return callback def set_indent(TokenClass, implicit=False): """Set the previously saved indentation level.""" def callback(lexer, match, context): text = match.group() if context.indent < context.next_indent: context.indent_stack.append(context.indent) context.indent = context.next_indent if not implicit: context.next_indent += len(text) yield match.start(), TokenClass, text context.pos = match.end() return callback def set_block_scalar_indent(TokenClass): """Set an explicit indentation level for a block scalar.""" def callback(lexer, match, context): text = match.group() context.block_scalar_indent = None if not text: return increment = match.group(1) if increment: current_indent = max(context.indent, 0) increment = int(increment) context.block_scalar_indent = current_indent + increment if text: yield match.start(), TokenClass, text context.pos = match.end() return callback def parse_block_scalar_empty_line(IndentTokenClass, ContentTokenClass): """Process an empty line in a block scalar.""" def callback(lexer, match, context): text = match.group() if (context.block_scalar_indent is None or len(text) <= context.block_scalar_indent): if text: yield match.start(), IndentTokenClass, text else: indentation = text[:context.block_scalar_indent] content = text[context.block_scalar_indent:] yield match.start(), IndentTokenClass, indentation yield (match.start()+context.block_scalar_indent, ContentTokenClass, content) context.pos = match.end() return callback def parse_block_scalar_indent(TokenClass): """Process indentation spaces in a block scalar.""" def callback(lexer, match, context): text = match.group() if context.block_scalar_indent is None: if len(text) <= max(context.indent, 0): context.stack.pop() context.stack.pop() return context.block_scalar_indent = len(text) else: if len(text) < context.block_scalar_indent: context.stack.pop() context.stack.pop() return if text: yield match.start(), TokenClass, text context.pos = match.end() return callback def parse_plain_scalar_indent(TokenClass): """Process indentation spaces in a plain scalar.""" def callback(lexer, match, context): text = match.group() if len(text) <= context.indent: context.stack.pop() context.stack.pop() return if text: yield match.start(), TokenClass, text context.pos = match.end() return callback class YAMLLexer(ExtendedRegexLexer): """Lexer for the YAML language.""" name = 'YAML' aliases = ['yaml'] filenames = ['*.yaml', '*.yml'] mimetypes = ['text/x-yaml'] tokens = { # the root rules 'root': [ # ignored whitespaces (r'[ ]+(?=#|$)', Text.Blank), # line breaks (r'\n+', Text.Break), # a comment (r'#[^\n]*', Comment.Single), # the '%YAML' directive (r'^%YAML(?=[ ]|$)', reset_indent(Name.Directive), 'yaml-directive'), # the %TAG directive (r'^%TAG(?=[ ]|$)', reset_indent(Name.Directive), 'tag-directive'), # document start and document end indicators (r'^(?:---|\.\.\.)(?=[ ]|$)', reset_indent(Punctuation.Document), 'block-line'), # indentation spaces (r'[ ]*(?![ \t\n\r\f\v]|$)', save_indent(Text.Indent, start=True), ('block-line', 'indentation')), ], # trailing whitespaces after directives or a block scalar indicator 'ignored-line': [ # ignored whitespaces (r'[ ]+(?=#|$)', Text.Blank), # a comment (r'#[^\n]*', Comment.Single), # line break (r'\n', Text.Break, '#pop:2'), ], # the %YAML directive 'yaml-directive': [ # the version number (r'([ ]+)([0-9]+\.[0-9]+)', bygroups(Text.Blank, Literal.Version), 'ignored-line'), ], # the %YAG directive 'tag-directive': [ # a tag handle and the corresponding prefix (r'([ ]+)(!|![0-9A-Za-z_-]*!)' r'([ ]+)(!|!?[0-9A-Za-z;/?:@&=+$,_.!~*\'()\[\]%-]+)', bygroups(Text.Blank, Name.Type, Text.Blank, Name.Type), 'ignored-line'), ], # block scalar indicators and indentation spaces 'indentation': [ # trailing whitespaces are ignored (r'[ ]*$', something(Text.Blank), '#pop:2'), # whitespaces preceeding block collection indicators (r'[ ]+(?=[?:-](?:[ ]|$))', save_indent(Text.Indent)), # block collection indicators (r'[?:-](?=[ ]|$)', set_indent(Punctuation.Indicator)), # the beginning a block line (r'[ ]*', save_indent(Text.Indent), '#pop'), ], # an indented line in the block context 'block-line': [ # the line end (r'[ ]*(?=#|$)', something(Text.Blank), '#pop'), # whitespaces separating tokens (r'[ ]+', Text.Blank), # tags, anchors and aliases, include('descriptors'), # block collections and scalars include('block-nodes'), # flow collections and quoted scalars include('flow-nodes'), # a plain scalar (r'(?=[^ \t\n\r\f\v?:,\[\]{}#&*!|>\'"%@`-]|[?:-][^ \t\n\r\f\v])', something(Literal.Scalar.Plain), 'plain-scalar-in-block-context'), ], # tags, anchors, aliases 'descriptors' : [ # a full-form tag (r'!<[0-9A-Za-z;/?:@&=+$,_.!~*\'()\[\]%-]+>', Name.Type), # a tag in the form '!', '!suffix' or '!handle!suffix' (r'!(?:[0-9A-Za-z_-]+)?' r'(?:![0-9A-Za-z;/?:@&=+$,_.!~*\'()\[\]%-]+)?', Name.Type), # an anchor (r'&[0-9A-Za-z_-]+', Name.Anchor), # an alias (r'\*[0-9A-Za-z_-]+', Name.Alias), ], # block collections and scalars 'block-nodes': [ # implicit key (r':(?=[ ]|$)', set_indent(Punctuation.Indicator, implicit=True)), # literal and folded scalars (r'[|>]', Punctuation.Indicator, ('block-scalar-content', 'block-scalar-header')), ], # flow collections and quoted scalars 'flow-nodes': [ # a flow sequence (r'\[', Punctuation.Indicator, 'flow-sequence'), # a flow mapping (r'\{', Punctuation.Indicator, 'flow-mapping'), # a single-quoted scalar (r'\'', Literal.Scalar.Flow.Quote, 'single-quoted-scalar'), # a double-quoted scalar (r'\"', Literal.Scalar.Flow.Quote, 'double-quoted-scalar'), ], # the content of a flow collection 'flow-collection': [ # whitespaces (r'[ ]+', Text.Blank), # line breaks (r'\n+', Text.Break), # a comment (r'#[^\n]*', Comment.Single), # simple indicators (r'[?:,]', Punctuation.Indicator), # tags, anchors and aliases include('descriptors'), # nested collections and quoted scalars include('flow-nodes'), # a plain scalar (r'(?=[^ \t\n\r\f\v?:,\[\]{}#&*!|>\'"%@`])', something(Literal.Scalar.Plain), 'plain-scalar-in-flow-context'), ], # a flow sequence indicated by '[' and ']' 'flow-sequence': [ # include flow collection rules include('flow-collection'), # the closing indicator (r'\]', Punctuation.Indicator, '#pop'), ], # a flow mapping indicated by '{' and '}' 'flow-mapping': [ # include flow collection rules include('flow-collection'), # the closing indicator (r'\}', Punctuation.Indicator, '#pop'), ], # block scalar lines 'block-scalar-content': [ # line break (r'\n', Text.Break), # empty line (r'^[ ]+$', parse_block_scalar_empty_line(Text.Indent, Literal.Scalar.Block)), # indentation spaces (we may leave the state here) (r'^[ ]*', parse_block_scalar_indent(Text.Indent)), # line content (r'[^\n\r\f\v]+', Literal.Scalar.Block), ], # the content of a literal or folded scalar 'block-scalar-header': [ # indentation indicator followed by chomping flag (r'([1-9])?[+-]?(?=[ ]|$)', set_block_scalar_indent(Punctuation.Indicator), 'ignored-line'), # chomping flag followed by indentation indicator (r'[+-]?([1-9])?(?=[ ]|$)', set_block_scalar_indent(Punctuation.Indicator), 'ignored-line'), ], # ignored and regular whitespaces in quoted scalars 'quoted-scalar-whitespaces': [ # leading and trailing whitespaces are ignored (r'^[ ]+|[ ]+$', Text.Blank), # line breaks are ignored (r'\n+', Text.Break), # other whitespaces are a part of the value (r'[ ]+', Literal.Scalar.Flow), ], # single-quoted scalars 'single-quoted-scalar': [ # include whitespace and line break rules include('quoted-scalar-whitespaces'), # escaping of the quote character (r'\'\'', Literal.Scalar.Flow.Escape), # regular non-whitespace characters (r'[^ \t\n\r\f\v\']+', Literal.Scalar.Flow), # the closing quote (r'\'', Literal.Scalar.Flow.Quote, '#pop'), ], # double-quoted scalars 'double-quoted-scalar': [ # include whitespace and line break rules include('quoted-scalar-whitespaces'), # escaping of special characters (r'\\[0abt\tn\nvfre "\\N_LP]', Literal.Scalar.Flow.Escape), # escape codes (r'\\(?:x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})', Literal.Scalar.Flow.Escape), # regular non-whitespace characters (r'[^ \t\n\r\f\v\"\\]+', Literal.Scalar.Flow), # the closing quote (r'"', Literal.Scalar.Flow.Quote, '#pop'), ], # the beginning of a new line while scanning a plain scalar 'plain-scalar-in-block-context-new-line': [ # empty lines (r'^[ ]+$', Text.Blank), # line breaks (r'\n+', Text.Break), # document start and document end indicators (r'^(?=---|\.\.\.)', something(Punctuation.Document), '#pop:3'), # indentation spaces (we may leave the block line state here) (r'^[ ]*', parse_plain_scalar_indent(Text.Indent), '#pop'), ], # a plain scalar in the block context 'plain-scalar-in-block-context': [ # the scalar ends with the ':' indicator (r'[ ]*(?=:[ ]|:$)', something(Text.Blank), '#pop'), # the scalar ends with whitespaces followed by a comment (r'[ ]+(?=#)', Text.Blank, '#pop'), # trailing whitespaces are ignored (r'[ ]+$', Text.Blank), # line breaks are ignored (r'\n+', Text.Break, 'plain-scalar-in-block-context-new-line'), # other whitespaces are a part of the value (r'[ ]+', Literal.Scalar.Plain), # regular non-whitespace characters (r'(?::(?![ \t\n\r\f\v])|[^ \t\n\r\f\v:])+', Literal.Scalar.Plain), ], # a plain scalar is the flow context 'plain-scalar-in-flow-context': [ # the scalar ends with an indicator character (r'[ ]*(?=[,:?\[\]{}])', something(Text.Blank), '#pop'), # the scalar ends with a comment (r'[ ]+(?=#)', Text.Blank, '#pop'), # leading and trailing whitespaces are ignored (r'^[ ]+|[ ]+$', Text.Blank), # line breaks are ignored (r'\n+', Text.Break), # other whitespaces are a part of the value (r'[ ]+', Literal.Scalar.Plain), # regular non-whitespace characters (r'[^ \t\n\r\f\v,:?\[\]{}]+', Literal.Scalar.Plain), ], } def get_tokens_unprocessed(self, text=None, context=None): if context is None: context = YAMLLexerContext(text, 0) return super(YAMLLexer, self).get_tokens_unprocessed(text, context)
obi-two/Rebelion
refs/heads/master
data/scripts/templates/object/building/base/shared_base_cantina.py
2
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Building() result.template = "object/building/base/shared_base_cantina.iff" result.attribute_template_id = -1 result.stfName("building_name","base_cantina") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
matthiascy/panda3d
refs/heads/master
direct/src/ffi/FFIEnvironment.py
11
import FFIConstants class FFIEnvironment: def __init__(self): self.reset() def reset(self): self.types = {} self.globalFunctions = [] self.downcastFunctions = [] self.globalValues = [] self.manifests = [] def addType(self, typeDescriptor, name): if name in self.types: FFIConstants.notify.info('Redefining type named: ' + name) self.types[name] = typeDescriptor def getTypeNamed(self, name): try: self.types[name] except KeyError: raise 'Type not found in FFIEnvironment' def addGlobalFunction(self, typeDescriptors): self.globalFunctions.extend(typeDescriptors) def addDowncastFunction(self, typeDescriptor): self.downcastFunctions.append(typeDescriptor) def addGlobalValue(self, typeDescriptor): self.globalValues.append(typeDescriptor) def addManifest(self, typeDescriptor): self.manifests.append(typeDescriptor)
phildini/logtacts
refs/heads/master
contacts/tests/test_api_views.py
1
from django.test import TestCase from rest_framework.test import APIRequestFactory from rest_framework.test import force_authenticate from common.factories import UserFactory from contacts import factories from contacts.api import serializers from contacts.api import views from contacts.models import LogEntry class TagListAPIViewTests(TestCase): def setUp(self): self.factory = APIRequestFactory() self.book = factories.BookFactory.create() self.user = UserFactory.create(username='phildini') bookowner = factories.BookOwnerFactory.create( book=self.book, user=self.user, ) def test_tag_list_view(self): tag = factories.TagFactory.create(book=self.book) request = self.factory.get('/api/tags/', format='json') force_authenticate(request, user=self.user) response = views.TagListCreateAPIView.as_view()(request) response.render() self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 1) def test_tag_list_view_wrong_user_for_book(self): tag = factories.TagFactory.create(book=self.book) request = self.factory.get('/api/tags/', format='json') user = UserFactory.create(username='asheesh') force_authenticate(request, user=user) response = views.TagListCreateAPIView.as_view()(request) response.render() self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 0) def test_tag_create_view(self): request = self.factory.post( '/api/tags/', {'tag': 'Test tag', 'book': str(self.book.id)}, format='json', ) force_authenticate(request, user=self.user) response = views.TagListCreateAPIView.as_view()(request) response.render() self.assertEqual(response.status_code, 201) def test_tag_create_view_wrong_book_for_user(self): request = self.factory.post( '/api/tags/', {'tag': 'Test tag', 'book': str(self.book.id)}, format='json', ) user = UserFactory.create(username='nicholle') force_authenticate(request, user=user) response = views.TagListCreateAPIView.as_view()(request) response.render() self.assertEqual(response.status_code, 401) class ContactListCreateAPIViewTests(TestCase): def setUp(self): self.factory = APIRequestFactory() self.book = factories.BookFactory.create() self.user = UserFactory.create(username='phildini') bookowner = factories.BookOwnerFactory.create( book=self.book, user=self.user, ) def test_contact_list_view(self): contact = factories.ContactFactory.create(book=self.book) request = self.factory.get('/api/contacts/', format='json') force_authenticate(request, user=self.user) response = views.ContactListCreateAPIView.as_view()(request) response.render() self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 1) def test_contact_list_view_wrong_user_for_book(self): contact = factories.ContactFactory.create(book=self.book) request = self.factory.get('/api/contacts/', format='json') user = UserFactory.create(username='asheesh') force_authenticate(request, user=user) response = views.ContactListCreateAPIView.as_view()(request) response.render() self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 0) # def test_contact_create_view(self): # request = self.factory.post( # '/api/contacts/', # {'name': 'Philip', 'book': str(self.book.id)}, # format='json', # ) # force_authenticate(request, user=self.user) # response = views.ContactListCreateAPIView.as_view()(request) # response.render() # self.assertEqual(response.status_code, 201) def test_contact_create_view_wrong_book_for_user(self): request = self.factory.post( '/api/contacts/', {'name': 'Philip', 'book': str(self.book.id)}, format='json', ) user = UserFactory.create(username='asheesh') force_authenticate(request, user=user) response = views.ContactListCreateAPIView.as_view()(request) response.render() self.assertEqual(response.status_code, 401) class ContactDetailEditAPIViewTests(TestCase): def setUp(self): self.factory = APIRequestFactory() self.book = factories.BookFactory.create() self.user = UserFactory.create(username='phildini') bookowner = factories.BookOwnerFactory.create( book=self.book, user=self.user, ) def test_contact_detail_edit_view_200(self): contact = factories.ContactFactory.create(book=self.book) request = self.factory.get( '/api/contacts/{}'.format(contact.pk), format='json', ) force_authenticate(request, user=self.user) response = views.ContactDetailEditAPIView.as_view()( request, pk=contact.id, ) response.render() self.assertEqual(response.status_code, 200) def test_contact_detail_successful_edits(self): contact = factories.ContactFactory.create(book=self.book) request = self.factory.put( '/api/contacts/{}'.format(contact.pk), {'name': 'Asheesh'}, format='json', ) force_authenticate(request, user=self.user) response = views.ContactDetailEditAPIView.as_view()( request, pk=contact.id, ) response.render() self.assertEqual(response.status_code, 200) def test_contact_detail_edit_creates_log(self): contact = factories.ContactFactory.create(book=self.book) request = self.factory.put( '/api/contacts/{}'.format(contact.pk), {'name': 'Asheesh'}, format='json', ) force_authenticate(request, user=self.user) response = views.ContactDetailEditAPIView.as_view()( request, pk=contact.id, ) response.render() new_log = LogEntry.objects.get( logged_by=self.user, contact=contact, kind='edit', ) def test_contact_detail_raises_404_if_wrong_user(self): contact = factories.ContactFactory.create(book=self.book) request = self.factory.get( '/api/contacts/{}'.format(contact.pk), format='json', ) user = UserFactory.create(username="asheesh") force_authenticate(request, user=user) response = views.ContactDetailEditAPIView.as_view()( request, pk=contact.id, ) response.render() self.assertEqual(response.status_code, 404) class LogListCreateAPIViewTests(TestCase): def setUp(self): self.factory = APIRequestFactory() self.book = factories.BookFactory.create() self.user = UserFactory.create(username='phildini') bookowner = factories.BookOwnerFactory.create( book=self.book, user=self.user, ) self.contact = factories.ContactFactory(book=self.book) self.url = '/api/contacts/{}/tags/'.format(self.contact.id) self.log = factories.LogFactory.create(contact=self.contact) def test_log_list_view(self): request = self.factory.get(self.url, format='json') force_authenticate(request, user=self.user) response = views.LogListCreateAPIView.as_view()( request, pk=self.contact.id, ) response.render() self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 1) def test_log_list_view_wrong_user_for_book(self): request = self.factory.get(self.url, format='json') user = UserFactory.create(username='asheesh') force_authenticate(request, user=user) response = views.LogListCreateAPIView.as_view()( request, pk=self.contact.id, ) response.render() self.assertEqual(response.status_code, 404) def test_log_create_view(self): request = self.factory.post( self.url, {'contact': str(self.contact.id)}, format='json', ) force_authenticate(request, user=self.user) response = views.LogListCreateAPIView.as_view()( request, pk=self.contact.id, ) response.render() self.assertEqual(response.status_code, 201) def test_log_create_view_wrong_book_for_user(self): request = self.factory.post( '/api/contacts/', {'contact': str(self.contact.id)}, format='json', ) user = UserFactory.create(username='asheesh') force_authenticate(request, user=user) response = views.LogListCreateAPIView.as_view()( request, pk=self.contact.id, ) response.render() self.assertEqual(response.status_code, 404)
agamdua/MyCloud
refs/heads/master
MyCloud/users/admin.py
38
# -*- coding: utf-8 -*- from django.contrib import admin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import User class UserAdmin(admin.ModelAdmin): create_form_class = UserCreationForm update_form_class = UserChangeForm admin.site.register(User, UserAdmin)
manthey/girder
refs/heads/master
tests/cases/notification_test.py
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2013 Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### import time from .. import base from girder.constants import SettingKey from girder.exceptions import ValidationException from girder.models.notification import ProgressState from girder.models.setting import Setting from girder.models.token import Token from girder.models.user import User from girder.utility.progress import ProgressContext def setUpModule(): base.startServer() def tearDownModule(): base.stopServer() class NotificationTestCase(base.TestCase): def setUp(self): base.TestCase.setUp(self) self.admin = User().createUser( email='admin@email.com', login='admin', firstName='first', lastName='last', password='mypasswd') def _testStream(self, user, token=None): # Should only work for users or token sessions resp = self.request(path='/notification/stream', method='GET') self.assertStatus(resp, 401) self.assertEqual( resp.json['message'], 'You must be logged in or have a valid auth token.') resp = self.request(path='/notification/stream', method='GET', user=user, token=token, isJson=False, params={'timeout': 0}) self.assertStatusOk(resp) self.assertEqual(self.getBody(resp), '') # Should not work when disabled Setting().set(SettingKey.ENABLE_NOTIFICATION_STREAM, False) resp = self.request(path='/notification/stream', method='GET', user=user, token=token, isJson=False, params={'timeout': 0}) self.assertStatus(resp, 503) Setting().set(SettingKey.ENABLE_NOTIFICATION_STREAM, True) # Use a very high rate-limit interval so that we don't fail on slow # build boxes with ProgressContext( True, user=user, token=token, title='Test', total=100, interval=100) as progress: progress.update(current=1) # Rate limiting should make it so we didn't write the immediate # update within the time interval. resp = self.request(path='/notification/stream', method='GET', user=user, token=token, isJson=False, params={'timeout': 0}) messages = self.getSseMessages(resp) self.assertEqual(len(messages), 1) self.assertEqual(messages[0]['type'], 'progress') self.assertEqual(messages[0]['data']['total'], 100) self.assertEqual(messages[0]['data']['current'], 0) self.assertFalse(ProgressState.isComplete( messages[0]['data']['state'])) # Now use a very short interval to test that we do save changes progress.interval = 0.01 time.sleep(0.02) progress.update(current=2) resp = self.request(path='/notification/stream', method='GET', user=user, token=token, isJson=False, params={'timeout': 0}) messages = self.getSseMessages(resp) self.assertEqual(len(messages), 1) self.assertEqual(messages[0]['data']['current'], 2) # If we use a non-numeric value, nothing bad should happen time.sleep(0.02) progress.update(current='not_a_number') resp = self.request(path='/notification/stream', method='GET', user=user, token=token, isJson=False, params={'timeout': 0}) messages = self.getSseMessages(resp) self.assertEqual(len(messages), 1) self.assertEqual(messages[0]['data']['current'], 'not_a_number') # Updating the progress without saving and then exiting should # send the update. progress.interval = 1000 progress.update(current=3) # The message should contain a timestamp self.assertIn('_girderTime', messages[0]) self.assertIsInstance(messages[0]['_girderTime'], int) # Test that the "since" parameter correctly filters out messages since = messages[0]['_girderTime'] + 1 resp = self.request(path='/notification/stream', method='GET', user=user, token=token, isJson=False, params={'timeout': 0, 'since': since}) messages = self.getSseMessages(resp) self.assertEqual(len(messages), 0) # Exiting the context manager should flush the most recent update. resp = self.request(path='/notification/stream', method='GET', user=user, token=token, isJson=False, params={'timeout': 0}) messages = self.getSseMessages(resp) self.assertEqual(len(messages), 1) self.assertEqual(messages[0]['data']['current'], 3) # Test a ValidationException within the progress context try: with ProgressContext(True, user=user, token=token, title='Test', total=100): raise ValidationException('Test Message') except ValidationException: pass # Exiting the context manager should flush the most recent update. resp = self.request(path='/notification/stream', method='GET', user=user, token=token, isJson=False, params={'timeout': 0}) messages = self.getSseMessages(resp) self.assertEqual(messages[-1]['data']['message'], 'Error: Test Message') def testUserStream(self): self._testStream(self.admin) def testTokenStream(self): resp = self.request(path='/token/session', method='GET') self.assertStatusOk(resp) token = resp.json['token'] tokenDoc = Token().load(token, force=True, objectId=False) self._testStream(None, tokenDoc)
yajiedesign/mxnet
refs/heads/master
tests/python/unittest/onnx/backend.py
12
# 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. # coding: utf-8 """MXNet/Gluon backend wrapper for onnx test infrastructure""" from mxnet.contrib.onnx.onnx2mx.import_onnx import GraphProto from mxnet.contrib.onnx.mx2onnx.export_onnx import MXNetGraph import mxnet as mx import numpy as np try: from onnx import helper, TensorProto, mapping from onnx.backend.base import Backend except ImportError: raise ImportError("Onnx and protobuf need to be installed. Instructions to" + " install - https://github.com/onnx/onnx#installation") from backend_rep import MXNetBackendRep, GluonBackendRep # MXNetBackend class will take an ONNX model with inputs, perform a computation, # and then return the output. # Implemented by following onnx docs guide: # https://github.com/onnx/onnx/blob/master/docs/ImplementingAnOnnxBackend.md class MXNetBackend(Backend): """MXNet/Gluon backend for ONNX""" backend = 'mxnet' operation = 'import' @classmethod def set_params(cls, backend, operation): cls.backend = backend cls.operation = operation @staticmethod def perform_import_export(sym, arg_params, aux_params, input_shape): """ Import ONNX model to mxnet model and then export to ONNX model and then import it back to mxnet for verifying the result""" graph = GraphProto() params = {} params.update(arg_params) params.update(aux_params) # exporting to onnx graph proto format converter = MXNetGraph() graph_proto = converter.create_onnx_graph_proto(sym, params, in_shape=input_shape, in_type=mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype('float32')]) # importing back to MXNET for verifying result. sym, arg_params, aux_params = graph.from_onnx(graph_proto) return sym, arg_params, aux_params @classmethod def prepare(cls, model, device='CPU', **kwargs): """For running end to end model(used for onnx test backend) Parameters ---------- model : onnx ModelProto object loaded onnx graph device : 'CPU' specifying device to run test on kwargs : other arguments Returns ------- MXNetBackendRep : object Returns object of MXNetBackendRep class which will be in turn used to run inference on the input model and return the result for comparison. """ backend = kwargs.get('backend', cls.backend) operation = kwargs.get('operation', cls.operation) graph = GraphProto() if device == 'CPU': ctx = mx.cpu() else: raise NotImplementedError("ONNX tests are run only for CPU context.") if backend == 'mxnet': sym, arg_params, aux_params = graph.from_onnx(model.graph) if operation == 'export': metadata = graph.get_graph_metadata(model.graph) input_data = metadata['input_tensor_data'] input_shape = [data[1] for data in input_data] sym, arg_params, aux_params = MXNetBackend.perform_import_export(sym, arg_params, aux_params, input_shape) return MXNetBackendRep(sym, arg_params, aux_params, device) elif backend == 'gluon': if operation == 'import': net = graph.graph_to_gluon(model.graph, ctx) return GluonBackendRep(net, device) elif operation == 'export': raise NotImplementedError("Gluon->ONNX export not implemented.") @classmethod def supports_device(cls, device): """Supports only CPU for testing""" return device == 'CPU' prepare = MXNetBackend.prepare supports_device = MXNetBackend.supports_device
josherick/bokeh
refs/heads/master
examples/charts/file/bar.py
37
from collections import OrderedDict import numpy as np import pandas as pd from bokeh.charts import Bar, output_file, show, vplot, hplot from bokeh.models import Range1d from bokeh.sampledata.olympics2014 import data as original_data width = 700 height = 500 legend_position = "top_right" data = {d['abbr']: d['medals'] for d in original_data['data'] if d['medals']['total'] > 0} countries = sorted(data.keys(), key=lambda x: data[x]['total'], reverse=True) gold = np.array([data[abbr]['gold'] for abbr in countries], dtype=np.float) silver = np.array([data[abbr]['silver'] for abbr in countries], dtype=np.float) bronze = np.array([data[abbr]['bronze'] for abbr in countries], dtype=np.float) # dict input medals = OrderedDict(bronze=bronze, silver=silver, gold=gold) dict_stacked = Bar( medals, countries, title="OrderedDict input | Stacked", legend=legend_position, xlabel="countries", ylabel="medals", width=width, height=height, stacked=True ) # data frame input df = pd.DataFrame(medals, index=countries) df_grouped = Bar( df, title="Data Frame input | Grouped", legend=legend_position, xlabel="countries", ylabel="medals", width=width, height=height ) # Numpy array input with different data to affect the ranges random = np.random.rand(3, 8) mixed = random - np.random.rand(3, 8) categories = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] np_stacked = Bar( random, cat=categories, title="Numpy Array input | Stacked", ylabel="Random Number", xlabel="", width=width, height=height, stacked=True ) np_negative_grouped = Bar( random * -1, cat=categories, title="All negative input | Grouped", ylabel="Random Number", width=width, height=height ) np_custom = Bar( mixed, cat=categories, title="Custom range (start=-3, end=0.4)", ylabel="Random Number", width=width, height=height, continuous_range=Range1d(start=-3, end=0.4) ) np_mixed_grouped = Bar( mixed, cat=categories, title="Mixed-sign input | Grouped", ylabel="Random Number", width=width, height=height ) # collect and display output_file("bar.html") show(vplot( hplot(dict_stacked, df_grouped), hplot(np_stacked, np_negative_grouped), hplot(np_mixed_grouped, np_custom), ))
ampax/edx-platform-backup
refs/heads/live
cms/djangoapps/contentstore/tests/test_i18n.py
7
from unittest import skip from django.contrib.auth.models import User from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from contentstore.tests.utils import AjaxEnabledTestClient class InternationalizationTest(ModuleStoreTestCase): """ Tests to validate Internationalization. """ def setUp(self): """ These tests need a user in the DB so that the django Test Client can log them in. They inherit from the ModuleStoreTestCase class so that the mongodb collection will be cleared out before each test case execution and deleted afterwards. """ self.uname = 'testuser' self.email = 'test+courses@edx.org' self.password = 'foo' # Create the use so we can log them in. self.user = User.objects.create_user(self.uname, self.email, self.password) # Note that we do not actually need to do anything # for registration if we directly mark them active. self.user.is_active = True # Staff has access to view all courses self.user.is_staff = True self.user.save() self.course_data = { 'org': 'MITx', 'number': '999', 'display_name': 'Robot Super Course', } def test_course_plain_english(self): """Test viewing the index page with no courses""" self.client = AjaxEnabledTestClient() self.client.login(username=self.uname, password=self.password) resp = self.client.get_html('/home/') self.assertContains(resp, '<h1 class="page-header">Studio Home</h1>', status_code=200, html=True) def test_course_explicit_english(self): """Test viewing the index page with no courses""" self.client = AjaxEnabledTestClient() self.client.login(username=self.uname, password=self.password) resp = self.client.get_html( '/home/', {}, HTTP_ACCEPT_LANGUAGE='en', ) self.assertContains(resp, '<h1 class="page-header">Studio Home</h1>', status_code=200, html=True) # **** # NOTE: # **** # # This test will break when we replace this fake 'test' language # with actual Esperanto. This test will need to be updated with # actual Esperanto at that time. # Test temporarily disable since it depends on creation of dummy strings @skip def test_course_with_accents(self): """Test viewing the index page with no courses""" self.client = AjaxEnabledTestClient() self.client.login(username=self.uname, password=self.password) resp = self.client.get_html( '/home/', {}, HTTP_ACCEPT_LANGUAGE='eo' ) TEST_STRING = ( u'<h1 class="title-1">' u'My \xc7\xf6\xfcrs\xe9s L#' u'</h1>' ) self.assertContains(resp, TEST_STRING, status_code=200, html=True)
gacarrillor/QGIS
refs/heads/master
tests/src/python/test_qgsgraduatedsymbolrenderer.py
30
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsGraduatedSymbolRenderer .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __author__ = 'Chris Crook' __date__ = '3/10/2014' __copyright__ = 'Copyright 2014, The QGIS Project' import qgis # NOQA from qgis.testing import unittest, start_app from qgis.core import (QgsGraduatedSymbolRenderer, QgsRendererRange, QgsRendererRangeLabelFormat, QgsMarkerSymbol, QgsGradientColorRamp, QgsVectorLayer, QgsFeature, QgsGeometry, QgsPointXY, QgsReadWriteContext, QgsRenderContext ) from qgis.PyQt.QtCore import Qt from qgis.PyQt.QtXml import QDomDocument from qgis.PyQt.QtGui import QColor start_app() # =========================================================== # Utility functions def createMarkerSymbol(): symbol = QgsMarkerSymbol.createSimple({ "color": "100,150,50", "name": "square", "size": "3.0" }) return symbol def createMemoryLayer(values): ml = QgsVectorLayer("Point?crs=epsg:4236&field=id:integer&field=value:double", "test_data", "memory") # Data as list of x, y, id, value assert ml.isValid() pr = ml.dataProvider() fields = pr.fields() for id, value in enumerate(values): x = id * 10.0 feat = QgsFeature(fields) feat['id'] = id feat['value'] = value g = QgsGeometry.fromPointXY(QgsPointXY(x, x)) feat.setGeometry(g) pr.addFeatures([feat]) ml.updateExtents() return ml def createColorRamp(): return QgsGradientColorRamp( QColor(255, 0, 0), QColor(0, 0, 255) ) def createLabelFormat(): format = QgsRendererRangeLabelFormat() template = "%1 - %2 meters" precision = 5 format.setFormat(template) format.setPrecision(precision) format.setTrimTrailingZeroes(True) return format # Note: Dump functions are not designed for a user friendly dump, just # for a moderately compact representation of a rendererer that is independent # of the renderer source code and so appropriate for use in unit tests. def dumpRangeBreaks(ranges): return dumpRangeList(ranges, breaksOnly=True) def dumpRangeLabels(ranges): return dumpRangeList(ranges, labelsOnly=True) def dumpLabelFormat(format): return ( ':' + format.format() + ':' + str(format.precision()) + ':' + str(format.trimTrailingZeroes()) + ':') def dumpRangeList(rlist, breaksOnly=False, labelsOnly=False): rstr = '(' format = "{0:.4f}-{1:.4f}" if not breaksOnly: format = format + ":{2}:{3}:{4}:" if labelsOnly: format = '{2}' for r in rlist: rstr = rstr + format.format( r.lowerValue(), r.upperValue(), r.label(), r.symbol().dump(), r.renderState(), ) + "," return rstr + ')' # Crude dump for deterministic ramp - just dumps colors at a range of values def dumpColorRamp(ramp): if ramp is None: return ':None:' rampstr = ':' for x in (0.0, 0.33, 0.66, 1.0): rampstr = rampstr + ramp.color(x).name() + ':' return rampstr def dumpGraduatedRenderer(r): rstr = ':' rstr = rstr + r.classAttribute() + ':' rstr = rstr + str(r.mode()) + ':' symbol = r.sourceSymbol() if symbol is None: rstr = rstr + 'None' + ':' else: rstr = rstr + symbol.dump() + ':' rstr = rstr + dumpColorRamp(r.sourceColorRamp()) rstr = rstr + dumpRangeList(r.ranges()) return rstr # ================================================================= # Tests class TestQgsGraduatedSymbolRenderer(unittest.TestCase): def testQgsRendererRange_1(self): """Test QgsRendererRange getter/setter functions""" range = QgsRendererRange() self.assertTrue(range) lower = 123.45 upper = 234.56 label = "Test label" symbol = createMarkerSymbol() range.setLowerValue(lower) self.assertEqual(range.lowerValue(), lower, "Lower value getter/setter failed") range.setUpperValue(upper) self.assertEqual(range.upperValue(), upper, "Upper value getter/setter failed") range.setLabel(label) self.assertEqual(range.label(), label, "Label getter/setter failed") range.setRenderState(True) self.assertTrue(range.renderState(), "Render state getter/setter failed") range.setRenderState(False) self.assertFalse(range.renderState(), "Render state getter/setter failed") range.setSymbol(symbol.clone()) self.assertEqual(symbol.dump(), range.symbol().dump(), "Symbol getter/setter failed") range2 = QgsRendererRange(lower, upper, symbol.clone(), label, False) self.assertEqual(range2.lowerValue(), lower, "Lower value from constructor failed") self.assertEqual(range2.upperValue(), upper, "Upper value from constructor failed") self.assertEqual(range2.label(), label, "Label from constructor failed") self.assertEqual(range2.symbol().dump(), symbol.dump(), "Symbol from constructor failed") self.assertFalse(range2.renderState(), "Render state getter/setter failed") def testQgsRendererRangeLabelFormat_1(self): """Test QgsRendererRangeLabelFormat getter/setter functions""" format = QgsRendererRangeLabelFormat() self.assertTrue(format, "QgsRendererRangeLabelFomat construction failed") template = "%1 - %2 meters" precision = 5 format.setFormat(template) self.assertEqual(format.format(), template, "Format getter/setter failed") format.setPrecision(precision) self.assertEqual(format.precision(), precision, "Precision getter/setter failed") format.setTrimTrailingZeroes(True) self.assertTrue(format.trimTrailingZeroes(), "TrimTrailingZeroes getter/setter failed") format.setTrimTrailingZeroes(False) self.assertFalse(format.trimTrailingZeroes(), "TrimTrailingZeroes getter/setter failed") minprecision = -6 maxprecision = 15 self.assertEqual(QgsRendererRangeLabelFormat.MIN_PRECISION, minprecision, "Minimum precision != -6") self.assertEqual(QgsRendererRangeLabelFormat.MAX_PRECISION, maxprecision, "Maximum precision != 15") format.setPrecision(-10) self.assertEqual(format.precision(), minprecision, "Minimum precision not enforced") format.setPrecision(20) self.assertEqual(format.precision(), maxprecision, "Maximum precision not enforced") def testQgsRendererRangeLabelFormat_2(self): """Test QgsRendererRangeLabelFormat number format""" format = QgsRendererRangeLabelFormat() # Tests have precision, trim, value, expected # (Note: Not sure what impact of locale is on these tests) tests = ( (2, False, 1.0, '1.00'), (2, True, 1.0, '1'), (2, False, 1.234, '1.23'), (2, True, 1.234, '1.23'), (2, False, 1.236, '1.24'), (2, False, -1.236, '-1.24'), (2, False, -0.004, '0.00'), (2, True, 1.002, '1'), (2, True, 1.006, '1.01'), (2, True, 1.096, '1.1'), (3, True, 1.096, '1.096'), (-2, True, 1496.45, '1500'), (-2, True, 149.45, '100'), (-2, True, 79.45, '100'), (-2, True, 49.45, '0'), (-2, True, -49.45, '0'), (-2, True, -149.45, '-100'), ) for f in tests: precision, trim, value, expected = f format.setPrecision(precision) format.setTrimTrailingZeroes(trim) result = format.formatNumber(value) self.assertEqual(result, expected, "Number format error {0}:{1}:{2} => {3}".format( precision, trim, value, result)) # Label tests - label format, expected result. # Labels will be evaluated with lower=1.23 upper=2.34, precision=2 ltests = ( ("%1 - %2", "1.23 - 2.34"), ("%1", "1.23"), ("%2", "2.34"), ("%2%", "2.34%"), ("%1%1", "1.231.23"), ("from %1 to %2 meters", "from 1.23 to 2.34 meters"), ("from %2 to %1 meters", "from 2.34 to 1.23 meters"), ) format.setPrecision(2) format.setTrimTrailingZeroes(False) lower = 1.232 upper = 2.339 for t in ltests: label, expected = t format.setFormat(label) result = format.labelForLowerUpper(lower, upper) self.assertEqual(result, expected, "Label format error {0} => {1}".format( label, result)) range = QgsRendererRange() range.setLowerValue(lower) range.setUpperValue(upper) label = ltests[0][0] format.setFormat(label) result = format.labelForRange(range) self.assertEqual(result, ltests[0][1], "Label for range error {0} => {1}".format( label, result)) def testQgsGraduatedSymbolRenderer_1(self): """Test QgsGraduatedSymbolRenderer: Basic get/set functions """ # Create a renderer renderer = QgsGraduatedSymbolRenderer() symbol = createMarkerSymbol() renderer.setSourceSymbol(symbol.clone()) self.assertEqual(symbol.dump(), renderer.sourceSymbol().dump(), "Get/set renderer source symbol") attr = '"value"*"value"' renderer.setClassAttribute(attr) self.assertEqual(attr, renderer.classAttribute(), "Get/set renderer class attribute") for m in ( QgsGraduatedSymbolRenderer.Custom, QgsGraduatedSymbolRenderer.EqualInterval, QgsGraduatedSymbolRenderer.Quantile, QgsGraduatedSymbolRenderer.Jenks, QgsGraduatedSymbolRenderer.Pretty, QgsGraduatedSymbolRenderer.StdDev, ): renderer.setMode(m) self.assertEqual(m, renderer.mode(), "Get/set renderer mode") format = createLabelFormat() renderer.setLabelFormat(format) self.assertEqual( dumpLabelFormat(format), dumpLabelFormat(renderer.labelFormat()), "Get/set renderer label format") ramp = createColorRamp() renderer.setSourceColorRamp(ramp) self.assertEqual( dumpColorRamp(ramp), dumpColorRamp(renderer.sourceColorRamp()), "Get/set renderer color ramp") renderer.setSourceColorRamp(ramp) self.assertEqual( dumpColorRamp(ramp), dumpColorRamp(renderer.sourceColorRamp()), "Get/set renderer color ramp") # test for classificatio with varying size renderer.setGraduatedMethod(QgsGraduatedSymbolRenderer.GraduatedSize) renderer.setSourceColorRamp(None) renderer.addClassLowerUpper(0, 2) renderer.addClassLowerUpper(2, 4) renderer.addClassLowerUpper(4, 6) renderer.setSymbolSizes(2, 13) self.assertEqual(renderer.maxSymbolSize(), 13) self.assertEqual(renderer.minSymbolSize(), 2) refSizes = [2, (13 + 2) * .5, 13] ctx = QgsRenderContext() for idx, symbol in enumerate(renderer.symbols(ctx)): self.assertEqual(symbol.size(), refSizes[idx]) def testQgsGraduatedSymbolRenderer_2(self): """Test QgsGraduatedSymbolRenderer: Adding /removing/editing classes """ # Create a renderer renderer = QgsGraduatedSymbolRenderer() symbol = createMarkerSymbol() renderer.setSourceSymbol(symbol.clone()) symbol.setColor(QColor(255, 0, 0)) # Add class without start and end ranges renderer.addClass(symbol.clone()) renderer.addClass(symbol.clone()) renderer.updateRangeLabel(1, 'Second range') renderer.updateRangeLowerValue(1, 10.0) renderer.updateRangeUpperValue(1, 25.0) renderer.updateRangeRenderState(1, False) symbol.setColor(QColor(0, 0, 255)) renderer.updateRangeSymbol(1, symbol.clone()) # Add as a rangeobject symbol.setColor(QColor(0, 255, 0)) range = QgsRendererRange(20.0, 25.5, symbol.clone(), 'Third range', False) renderer.addClassRange(range) # Add class by lower and upper renderer.addClassLowerUpper(25.5, 30.5) # (Update label for sorting tests) renderer.updateRangeLabel(3, 'Another range') self.assertEqual( dumpRangeLabels(renderer.ranges()), '(0.0 - 0.0,Second range,Third range,Another range,)', 'Added ranges labels not correct') self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(0.0000-0.0000,10.0000-25.0000,20.0000-25.5000,25.5000-30.5000,)', 'Added ranges lower/upper values not correct') # Check that clone function works renderer2 = renderer.clone() self.assertEqual( dumpGraduatedRenderer(renderer), dumpGraduatedRenderer(renderer2), "clone function doesn't replicate renderer properly" ) # Check save and reload from Dom works doc = QDomDocument() element = renderer.save(doc, QgsReadWriteContext()) renderer2 = QgsGraduatedSymbolRenderer.create(element, QgsReadWriteContext()) self.assertEqual( dumpGraduatedRenderer(renderer), dumpGraduatedRenderer(renderer2), "Save/create from DOM doesn't replicate renderer properly" ) # Check sorting renderer.sortByLabel() self.assertEqual( dumpRangeList(renderer.ranges(), labelsOnly=True), '(0.0 - 0.0,Another range,Second range,Third range,)', 'sortByLabel not correct') renderer.sortByValue() self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(0.0000-0.0000,10.0000-25.0000,20.0000-25.5000,25.5000-30.5000,)', 'sortByValue not correct') renderer.sortByValue(Qt.DescendingOrder) self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(25.5000-30.5000,20.0000-25.5000,10.0000-25.0000,0.0000-0.0000,)', 'sortByValue descending not correct') # Check deleting renderer.deleteClass(2) self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(25.5000-30.5000,20.0000-25.5000,0.0000-0.0000,)', 'deleteClass not correct') renderer.deleteAllClasses() self.assertEqual(len(renderer.ranges()), 0, "deleteAllClasses didn't delete all") # void addClass( QgsSymbol* symbol ); # //! \note available in python bindings as addClassRange # void addClass( QgsRendererRange range ) /PyName=addClassRange/; # //! \note available in python bindings as addClassLowerUpper # void addClass( double lower, double upper ) /PyName=addClassLowerUpper/; # void deleteClass( int idx ); # void deleteAllClasses(); def testQgsGraduatedSymbolRenderer_3(self): """Test QgsGraduatedSymbolRenderer: Reading attribute data, calculating classes """ # Create a renderer renderer = QgsGraduatedSymbolRenderer() symbol = createMarkerSymbol() renderer.setSourceSymbol(symbol.clone()) # Test retrieving data values from a layer ml = createMemoryLayer((1.2, 0.5, 5.0, 1.0, 1.0, 1.2)) renderer.setClassAttribute("value") # Equal interval calculations renderer.updateClasses(ml, renderer.EqualInterval, 3) self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(0.5000-2.0000,2.0000-3.5000,3.5000-5.0000,)', 'Equal interval classification not correct') # Quantile classes renderer.updateClasses(ml, renderer.Quantile, 3) self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(0.5000-1.0000,1.0000-1.2000,1.2000-5.0000,)', 'Quantile classification not correct') renderer.updateClasses(ml, renderer.Quantile, 4) self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(0.5000-1.0000,1.0000-1.1000,1.1000-1.2000,1.2000-5.0000,)', 'Quantile classification not correct') def testUsedAttributes(self): renderer = QgsGraduatedSymbolRenderer() ctx = QgsRenderContext() # attribute can contain either attribute name or an expression. # Sometimes it is not possible to distinguish between those two, # e.g. "a - b" can be both a valid attribute name or expression. # Since we do not have access to fields here, the method should return both options. renderer.setClassAttribute("value") self.assertEqual(renderer.usedAttributes(ctx), {"value"}) renderer.setClassAttribute("value - 1") self.assertEqual(renderer.usedAttributes(ctx), {"value", "value - 1"}) renderer.setClassAttribute("valuea - valueb") self.assertEqual(renderer.usedAttributes(ctx), {"valuea", "valuea - valueb", "valueb"}) def testFilterNeedsGeometry(self): renderer = QgsGraduatedSymbolRenderer() renderer.setClassAttribute("value") self.assertFalse(renderer.filterNeedsGeometry()) renderer.setClassAttribute("$area") self.assertTrue(renderer.filterNeedsGeometry()) renderer.setClassAttribute("value - $area") self.assertTrue(renderer.filterNeedsGeometry()) if __name__ == "__main__": unittest.main()
cyrixhero/YouCompleteMe
refs/heads/master
install.py
23
#!/usr/bin/env python import os import subprocess import sys import os.path as p import glob DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) ) DIR_OF_OLD_LIBS = p.join( DIR_OF_THIS_SCRIPT, 'python' ) def Main(): build_file = p.join( DIR_OF_THIS_SCRIPT, 'third_party', 'ycmd', 'build.py' ) if not p.isfile( build_file ): sys.exit( 'File ' + build_file + ' does not exist; you probably forgot ' 'to run:\n\tgit submodule update --init --recursive\n\n' ) python_binary = sys.executable subprocess.call( [ python_binary, build_file ] + sys.argv[1:] ) # Remove old YCM libs if present so that YCM can start. old_libs = ( glob.glob( p.join( DIR_OF_OLD_LIBS, '*ycm_core.*' ) ) + glob.glob( p.join( DIR_OF_OLD_LIBS, '*ycm_client_support.*' ) ) + glob.glob( p.join( DIR_OF_OLD_LIBS, '*clang*.*') ) ) for lib in old_libs: os.remove( lib ) if __name__ == "__main__": Main()
snnn/tensorflow
refs/heads/master
tensorflow/contrib/constrained_optimization/python/external_regret_optimizer_test.py
25
# 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. # ============================================================================== """Tests for constrained_optimization.python.external_regret_optimizer.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.constrained_optimization.python import external_regret_optimizer from tensorflow.contrib.constrained_optimization.python import test_util from tensorflow.python.ops import standard_ops from tensorflow.python.platform import test from tensorflow.python.training import gradient_descent class AdditiveExternalRegretOptimizerWrapper( external_regret_optimizer.AdditiveExternalRegretOptimizer): """Testing wrapper class around AdditiveExternalRegretOptimizer. This class is identical to AdditiveExternalRegretOptimizer, except that it caches the internal optimization state when _lagrange_multipliers() is called, so that we can test that the Lagrange multipliers take on their expected values. """ def __init__(self, optimizer, constraint_optimizer=None, maximum_multiplier_radius=None): """Same as AdditiveExternalRegretOptimizer.__init__.""" super(AdditiveExternalRegretOptimizerWrapper, self).__init__( optimizer=optimizer, constraint_optimizer=constraint_optimizer, maximum_multiplier_radius=maximum_multiplier_radius) self._cached_lagrange_multipliers = None @property def lagrange_multipliers(self): """Returns the cached Lagrange multipliers.""" return self._cached_lagrange_multipliers def _lagrange_multipliers(self, state): """Caches the internal state for testing.""" self._cached_lagrange_multipliers = super( AdditiveExternalRegretOptimizerWrapper, self)._lagrange_multipliers(state) return self._cached_lagrange_multipliers class ExternalRegretOptimizerTest(test.TestCase): def test_project_multipliers_wrt_euclidean_norm(self): """Tests Euclidean projection routine on some known values.""" multipliers1 = standard_ops.constant([-0.1, -0.6, -0.3]) expected_projected_multipliers1 = np.array([0.0, 0.0, 0.0]) multipliers2 = standard_ops.constant([-0.1, 0.6, 0.3]) expected_projected_multipliers2 = np.array([0.0, 0.6, 0.3]) multipliers3 = standard_ops.constant([0.4, 0.7, -0.2, 0.5, 0.1]) expected_projected_multipliers3 = np.array([0.2, 0.5, 0.0, 0.3, 0.0]) with self.cached_session() as session: projected_multipliers1 = session.run( external_regret_optimizer._project_multipliers_wrt_euclidean_norm( multipliers1, 1.0)) projected_multipliers2 = session.run( external_regret_optimizer._project_multipliers_wrt_euclidean_norm( multipliers2, 1.0)) projected_multipliers3 = session.run( external_regret_optimizer._project_multipliers_wrt_euclidean_norm( multipliers3, 1.0)) self.assertAllClose( expected_projected_multipliers1, projected_multipliers1, rtol=0, atol=1e-6) self.assertAllClose( expected_projected_multipliers2, projected_multipliers2, rtol=0, atol=1e-6) self.assertAllClose( expected_projected_multipliers3, projected_multipliers3, rtol=0, atol=1e-6) def test_additive_external_regret_optimizer(self): """Tests that the Lagrange multipliers update as expected.""" minimization_problem = test_util.ConstantMinimizationProblem( np.array([0.6, -0.1, 0.4])) optimizer = AdditiveExternalRegretOptimizerWrapper( gradient_descent.GradientDescentOptimizer(1.0), maximum_multiplier_radius=1.0) train_op = optimizer.minimize_constrained(minimization_problem) expected_multipliers = [ np.array([0.0, 0.0, 0.0]), np.array([0.6, 0.0, 0.4]), np.array([0.7, 0.0, 0.3]), np.array([0.8, 0.0, 0.2]), np.array([0.9, 0.0, 0.1]), np.array([1.0, 0.0, 0.0]), np.array([1.0, 0.0, 0.0]), ] multipliers = [] with self.cached_session() as session: session.run(standard_ops.global_variables_initializer()) while len(multipliers) < len(expected_multipliers): multipliers.append(session.run(optimizer.lagrange_multipliers)) session.run(train_op) for expected, actual in zip(expected_multipliers, multipliers): self.assertAllClose(expected, actual, rtol=0, atol=1e-6) if __name__ == "__main__": test.main()
johnwang117/learn-python-the-hard-way
refs/heads/master
ex29.py
1
people = 20 cats = 30 dogs = 15 if people < cats: print('Too many cats! The world is doomed!') if people > cats: print('Not many cats! The world is saved!') if people < dogs: print('The world is drooled on!') if people > dogs: print('The wold is dry!') dogs += 5 if people >= dogs: print('People are greater than or equal to dogs.') if people <= dogs: print('People are less than or equal to dogs.') if people == dogs: print('People are dogs.')
FNCS/ns-3.26
refs/heads/master
doc/tutorial/pickle-to-xml.py
392
#!/usr/bin/python # output xml format: # <pages> # <page url="xx"><prev url="yyy">zzz</prev><next url="hhh">lll</next><fragment>file.frag</fragment></page> # ... # </pages> import pickle import os import codecs def dump_pickles(out, dirname, filename, path): f = open(os.path.join(dirname, filename), 'r') data = pickle.load(f) fragment_file = codecs.open(data['current_page_name'] + '.frag', mode='w', encoding='utf-8') fragment_file.write(data['body']) fragment_file.close() out.write(' <page url="%s">\n' % path) out.write(' <fragment>%s.frag</fragment>\n' % data['current_page_name']) if data['prev'] is not None: out.write(' <prev url="%s">%s</prev>\n' % (os.path.normpath(os.path.join(path, data['prev']['link'])), data['prev']['title'])) if data['next'] is not None: out.write(' <next url="%s">%s</next>\n' % (os.path.normpath(os.path.join(path, data['next']['link'])), data['next']['title'])) out.write(' </page>\n') f.close() if data['next'] is not None: next_path = os.path.normpath(os.path.join(path, data['next']['link'])) next_filename = os.path.basename(next_path) + '.fpickle' dump_pickles(out, dirname, next_filename, next_path) return import sys sys.stdout.write('<pages>\n') dump_pickles(sys.stdout, os.path.dirname(sys.argv[1]), os.path.basename(sys.argv[1]), '/') sys.stdout.write('</pages>')
cvegaj/ElectriCERT
refs/heads/master
cert-tools/env/lib/python2.7/site-packages/setuptools/windows_support.py
1015
import platform import ctypes def windows_only(func): if platform.system() != 'Windows': return lambda *args, **kwargs: None return func @windows_only def hide_file(path): """ Set the hidden attribute on a file or directory. From http://stackoverflow.com/questions/19622133/ `path` must be text. """ __import__('ctypes.wintypes') SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD SetFileAttributes.restype = ctypes.wintypes.BOOL FILE_ATTRIBUTE_HIDDEN = 0x02 ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN) if not ret: raise ctypes.WinError()
jvicu2001/alexis-bot
refs/heads/dev
bot/events/bot_mention_event.py
1
from .message_event import MessageEvent class BotMentionEvent(MessageEvent): """ This event is triggered when the bot is mentioned in any chat. """ def __init__(self, message, bot): super().__init__(message, bot) if not bot.user.mentioned_in(message): # This shouldn't even happen, but anyways raise RuntimeError('The message does not contain a bot mention') # StartsWith mention event, when the message starts with the bot mention mentions = ['<@{}>'.format(bot.user.id), '<@!{}>'.format(bot.user.id)] self.starts_with = message.content.startswith(tuple(mentions)) self.args = [] self.argc = 0 if self.starts_with: # Parse the message like if it was a command self.args = message.content.replace(' ', ' ').split(' ')[1:] self.argc = len(self.args) self.text = ' '.join(self.args) async def handle(self): """ Calls all the registered event handlers, only if permission conditions are met. """ for cmd in self.bot.manager.mention_handlers: if cmd.bot_owner_only and not self.bot_owner: continue if cmd.owner_only and not (self.owner or self.bot_owner): continue if not cmd.allow_pm and self.is_pm: continue await cmd.handle(self)
joshbohde/scikit-learn
refs/heads/master
sklearn/hmm.py
2
# Hidden Markov Models # # Author: Ron Weiss <ronweiss@gmail.com> import string import numpy as np from .utils import check_random_state from .utils.extmath import logsum from .base import BaseEstimator from .mixture import (GMM, lmvnpdf, normalize, sample_gaussian, _distribute_covar_matrix_to_match_cvtype, _validate_covars) from . import cluster import warnings warnings.warn('sklearn.hmm is orphaned, undocumented and has known numerical' ' stability issues. If nobody volunteers to write documentation' ' and make it more stable, this module will be removed in' ' version 0.11.') ZEROLOGPROB = -1e200 class _BaseHMM(BaseEstimator): """Hidden Markov Model base class. Representation of a hidden Markov model probability distribution. This class allows for easy evaluation of, sampling from, and maximum-likelihood estimation of the parameters of a HMM. See the instance documentation for details specific to a particular object. Attributes ---------- n_components : int (read-only) Number of states in the model. transmat : array, shape (`n_components`, `n_components`) Matrix of transition probabilities between states. startprob : array, shape ('n_components`,) Initial state occupation distribution. Methods ------- eval(X) Compute the log likelihood of `X` under the HMM. decode(X) Find most likely state sequence for each point in `X` using the Viterbi algorithm. rvs(n=1) Generate `n` samples from the HMM. fit(X) Estimate HMM parameters from `X`. predict(X) Like decode, find most likely state sequence corresponding to `X`. score(X) Compute the log likelihood of `X` under the model. See Also -------- GMM : Gaussian mixture model """ # This class implements the public interface to all HMMs that # derive from it, including all of the machinery for the # forward-backward and Viterbi algorithms. Subclasses need only # implement _generate_sample_from_state(), _compute_log_likelihood(), # _init(), _initialize_sufficient_statistics(), # _accumulate_sufficient_statistics(), and _do_mstep(), all of # which depend on the specific emission distribution. # # Subclasses will probably also want to implement properties for # the emission distribution parameters to expose them publically. def __init__(self, n_components=1, startprob=None, transmat=None, startprob_prior=None, transmat_prior=None): self.n_components = n_components if startprob is None: startprob = np.tile(1.0 / n_components, n_components) self.startprob = startprob if startprob_prior is None: startprob_prior = 1.0 self.startprob_prior = startprob_prior if transmat is None: transmat = np.tile(1.0 / n_components, (n_components, n_components)) self.transmat = transmat if transmat_prior is None: transmat_prior = 1.0 self.transmat_prior = transmat_prior def eval(self, obs, maxrank=None, beamlogprob=-np.Inf): """Compute the log probability under the model and compute posteriors Implements rank and beam pruning in the forward-backward algorithm to speed up inference in large models. Parameters ---------- obs : array_like, shape (n, n_features) Sequence of n_features-dimensional data points. Each row corresponds to a single point in the sequence. maxrank : int Maximum rank to evaluate for rank pruning. If not None, only consider the top `maxrank` states in the inner sum of the forward algorithm recursion. Defaults to None (no rank pruning). See The HTK Book for more details. beamlogprob : float Width of the beam-pruning beam in log-probability units. Defaults to -numpy.Inf (no beam pruning). See The HTK Book for more details. Returns ------- logprob : array_like, shape (n,) Log probabilities of the sequence `obs` posteriors: array_like, shape (n, n_components) Posterior probabilities of each state for each observation See Also -------- score : Compute the log probability under the model decode : Find most likely state sequence corresponding to a `obs` """ obs = np.asanyarray(obs) framelogprob = self._compute_log_likelihood(obs) logprob, fwdlattice = self._do_forward_pass(framelogprob, maxrank, beamlogprob) bwdlattice = self._do_backward_pass(framelogprob, fwdlattice, maxrank, beamlogprob) gamma = fwdlattice + bwdlattice # gamma is guaranteed to be correctly normalized by logprob at # all frames, unless we do approximate inference using pruning. # So, we will normalize each frame explicitly in case we # pruned too aggressively. posteriors = np.exp(gamma.T - logsum(gamma, axis=1)).T posteriors += np.finfo(np.float32).eps posteriors /= np.sum(posteriors, axis=1).reshape((-1,1)) return logprob, posteriors def score(self, obs, maxrank=None, beamlogprob=-np.Inf): """Compute the log probability under the model. Parameters ---------- obs : array_like, shape (n, n_features) Sequence of n_features-dimensional data points. Each row corresponds to a single data point. maxrank : int Maximum rank to evaluate for rank pruning. If not None, only consider the top `maxrank` states in the inner sum of the forward algorithm recursion. Defaults to None (no rank pruning). See The HTK Book for more details. beamlogprob : float Width of the beam-pruning beam in log-probability units. Defaults to -numpy.Inf (no beam pruning). See The HTK Book for more details. Returns ------- logprob : array_like, shape (n,) Log probabilities of each data point in `obs` See Also -------- eval : Compute the log probability under the model and posteriors decode : Find most likely state sequence corresponding to a `obs` """ obs = np.asanyarray(obs) framelogprob = self._compute_log_likelihood(obs) logprob, fwdlattice = self._do_forward_pass(framelogprob, maxrank, beamlogprob) return logprob def decode(self, obs, maxrank=None, beamlogprob=-np.Inf): """Find most likely state sequence corresponding to `obs`. Uses the Viterbi algorithm. Parameters ---------- obs : array_like, shape (n, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. maxrank : int Maximum rank to evaluate for rank pruning. If not None, only consider the top `maxrank` states in the inner sum of the forward algorithm recursion. Defaults to None (no rank pruning). See The HTK Book for more details. beamlogprob : float Width of the beam-pruning beam in log-probability units. Defaults to -numpy.Inf (no beam pruning). See The HTK Book for more details. Returns ------- viterbi_logprob : float Log probability of the maximum likelihood path through the HMM states : array_like, shape (n,) Index of the most likely states for each observation See Also -------- eval : Compute the log probability under the model and posteriors score : Compute the log probability under the model """ obs = np.asanyarray(obs) framelogprob = self._compute_log_likelihood(obs) logprob, state_sequence = self._do_viterbi_pass(framelogprob, maxrank, beamlogprob) return logprob, state_sequence def predict(self, obs, **kwargs): """Find most likely state sequence corresponding to `obs`. Parameters ---------- obs : array_like, shape (n, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. maxrank : int Maximum rank to evaluate for rank pruning. If not None, only consider the top `maxrank` states in the inner sum of the forward algorithm recursion. Defaults to None (no rank pruning). See The HTK Book for more details. beamlogprob : float Width of the beam-pruning beam in log-probability units. Defaults to -numpy.Inf (no beam pruning). See The HTK Book for more details. Returns ------- states : array_like, shape (n,) Index of the most likely states for each observation """ logprob, state_sequence = self.decode(obs, **kwargs) return state_sequence def predict_proba(self, obs, **kwargs): """Compute the posterior probability for each state in the model Parameters ---------- obs : array_like, shape (n, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. See eval() for a list of accepted keyword arguments. Returns ------- T : array-like, shape (n, n_components) Returns the probability of the sample for each state in the model. """ logprob, posteriors = self.eval(obs, **kwargs) return posteriors def rvs(self, n=1, random_state=None): """Generate random samples from the model. Parameters ---------- n : int Number of samples to generate. Returns ------- obs : array_like, length `n` List of samples """ random_state = check_random_state(random_state) startprob_pdf = self.startprob startprob_cdf = np.cumsum(startprob_pdf) transmat_pdf = self.transmat transmat_cdf = np.cumsum(transmat_pdf, 1) # Initial state. rand = random_state.rand() currstate = (startprob_cdf > rand).argmax() obs = [self._generate_sample_from_state( currstate, random_state=random_state)] for x in xrange(n - 1): rand = random_state.rand() currstate = (transmat_cdf[currstate] > rand).argmax() obs.append(self._generate_sample_from_state( currstate, random_state=random_state)) return np.array(obs) def fit(self, obs, n_iter=10, thresh=1e-2, params=string.letters, init_params=string.letters, maxrank=None, beamlogprob=-np.Inf, **kwargs): """Estimate model parameters. An initialization step is performed before entering the EM algorithm. If you want to avoid this step, set the keyword argument init_params to the empty string ''. Likewise, if you would like just to do an initialization, call this method with n_iter=0. Parameters ---------- obs : list List of array-like observation sequences (shape (n_i, n_features)). n_iter : int, optional Number of iterations to perform. thresh : float, optional Convergence threshold. params : string, optional Controls which parameters are updated in the training process. Can contain any combination of 's' for startprob, 't' for transmat, 'm' for means, and 'c' for covars, etc. Defaults to all parameters. init_params : string, optional Controls which parameters are initialized prior to training. Can contain any combination of 's' for startprob, 't' for transmat, 'm' for means, and 'c' for covars, etc. Defaults to all parameters. maxrank : int, optional Maximum rank to evaluate for rank pruning. If not None, only consider the top `maxrank` states in the inner sum of the forward algorithm recursion. Defaults to None (no rank pruning). See "The HTK Book" for more details. beamlogprob : float, optional Width of the beam-pruning beam in log-probability units. Defaults to -numpy.Inf (no beam pruning). See "The HTK Book" for more details. Notes ----- In general, `logprob` should be non-decreasing unless aggressive pruning is used. Decreasing `logprob` is generally a sign of overfitting (e.g. a covariance parameter getting too small). You can fix this by getting more training data, or decreasing `covars_prior`. """ self._init(obs, init_params) logprob = [] for i in xrange(n_iter): # Expectation step stats = self._initialize_sufficient_statistics() curr_logprob = 0 for seq in obs: framelogprob = self._compute_log_likelihood(seq) lpr, fwdlattice = self._do_forward_pass(framelogprob, maxrank, beamlogprob) bwdlattice = self._do_backward_pass(framelogprob, fwdlattice, maxrank, beamlogprob) gamma = fwdlattice + bwdlattice posteriors = np.exp(gamma.T - logsum(gamma, axis=1)).T curr_logprob += lpr self._accumulate_sufficient_statistics( stats, seq, framelogprob, posteriors, fwdlattice, bwdlattice, params) logprob.append(curr_logprob) # Check for convergence. if i > 0 and abs(logprob[-1] - logprob[-2]) < thresh: break # Maximization step self._do_mstep(stats, params, **kwargs) return self def _get_startprob(self): """Mixing startprob for each state.""" return np.exp(self._log_startprob) def _set_startprob(self, startprob): if len(startprob) != self.n_components: raise ValueError('startprob must have length n_components') if not np.allclose(np.sum(startprob), 1.0): raise ValueError('startprob must sum to 1.0') self._log_startprob = np.log(np.asanyarray(startprob).copy()) startprob = property(_get_startprob, _set_startprob) def _get_transmat(self): """Matrix of transition probabilities.""" return np.exp(self._log_transmat) def _set_transmat(self, transmat): if np.asanyarray(transmat).shape != (self.n_components, self.n_components): raise ValueError('transmat must have shape (n_components, n_components)') if not np.all(np.allclose(np.sum(transmat, axis=1), 1.0)): raise ValueError('Rows of transmat must sum to 1.0') self._log_transmat = np.log(np.asanyarray(transmat).copy()) underflow_idx = np.isnan(self._log_transmat) self._log_transmat[underflow_idx] = -np.Inf transmat = property(_get_transmat, _set_transmat) def _do_viterbi_pass(self, framelogprob, maxrank=None, beamlogprob=-np.Inf): nobs = len(framelogprob) lattice = np.zeros((nobs, self.n_components)) traceback = np.zeros((nobs, self.n_components), dtype=np.int) lattice[0] = self._log_startprob + framelogprob[0] for n in xrange(1, nobs): idx = self._prune_states(lattice[n - 1], maxrank, beamlogprob) pr = self._log_transmat[idx].T + lattice[n - 1, idx] lattice[n] = np.max(pr, axis=1) + framelogprob[n] traceback[n] = np.argmax(pr, axis=1) lattice[lattice <= ZEROLOGPROB] = -np.Inf # Do traceback. reverse_state_sequence = [] s = lattice[-1].argmax() logprob = lattice[-1, s] for frame in reversed(traceback): reverse_state_sequence.append(s) s = frame[s] reverse_state_sequence.reverse() return logprob, np.array(reverse_state_sequence) def _do_forward_pass(self, framelogprob, maxrank=None, beamlogprob=-np.Inf): nobs = len(framelogprob) fwdlattice = np.zeros((nobs, self.n_components)) fwdlattice[0] = self._log_startprob + framelogprob[0] for n in xrange(1, nobs): idx = self._prune_states(fwdlattice[n - 1], maxrank, beamlogprob) fwdlattice[n] = (logsum(self._log_transmat[idx].T + fwdlattice[n - 1, idx], axis=1) + framelogprob[n]) fwdlattice[fwdlattice <= ZEROLOGPROB] = -np.Inf return logsum(fwdlattice[-1]), fwdlattice def _do_backward_pass(self, framelogprob, fwdlattice, maxrank=None, beamlogprob=-np.Inf): nobs = len(framelogprob) bwdlattice = np.zeros((nobs, self.n_components)) for n in xrange(nobs - 1, 0, -1): # Do HTK style pruning (p. 137 of HTK Book version 3.4). # Don't bother computing backward probability if # fwdlattice * bwdlattice is more than a certain distance # from the total log likelihood. idx = self._prune_states(bwdlattice[n] + fwdlattice[n], None, -50) #beamlogprob) #-np.Inf) bwdlattice[n - 1] = logsum(self._log_transmat[:, idx] + bwdlattice[n, idx] + framelogprob[n, idx], axis=1) bwdlattice[bwdlattice <= ZEROLOGPROB] = -np.Inf return bwdlattice def _prune_states(self, lattice_frame, maxrank, beamlogprob): """ Returns indices of the active states in `lattice_frame` after rank and beam pruning. """ # Beam pruning threshlogprob = logsum(lattice_frame) + beamlogprob # Rank pruning if maxrank: # How big should our rank pruning histogram be? nbins = 3 * len(lattice_frame) lattice_min = lattice_frame[lattice_frame > ZEROLOGPROB].min() - 1 hst, cdf = np.histogram(lattice_frame, bins=nbins, range=(lattice_min, lattice_frame.max())) # Want to look at the high ranks. hst = hst[::-1].cumsum() cdf = cdf[::-1] rankthresh = cdf[hst >= min(maxrank, self.n_components)].max() # Only change the threshold if it is stricter than the beam # threshold. threshlogprob = max(threshlogprob, rankthresh) # Which states are active? state_idx, = np.nonzero(lattice_frame >= threshlogprob) return state_idx def _compute_log_likelihood(self, obs): pass def _generate_sample_from_state(self, state, random_state=None): pass def _init(self, obs, params): if 's' in params: self.startprob[:] = 1.0 / self.n_components if 't' in params: self.transmat[:] = 1.0 / self.n_components # Methods used by self.fit() def _initialize_sufficient_statistics(self): stats = {'nobs': 0, 'start': np.zeros(self.n_components), 'trans': np.zeros((self.n_components, self.n_components))} return stats def _accumulate_sufficient_statistics(self, stats, seq, framelogprob, posteriors, fwdlattice, bwdlattice, params): stats['nobs'] += 1 if 's' in params: stats['start'] += posteriors[0] if 't' in params: for t in xrange(len(framelogprob)): zeta = (fwdlattice[t - 1][:, np.newaxis] + self._log_transmat + framelogprob[t] + bwdlattice[t]) stats['trans'] += np.exp(zeta - logsum(zeta)) def _do_mstep(self, stats, params, **kwargs): # Based on Huang, Acero, Hon, "Spoken Language Processing", # p. 443 - 445 if 's' in params: self.startprob = normalize( np.maximum(self.startprob_prior - 1.0 + stats['start'], 1e-20)) if 't' in params: self.transmat = normalize( np.maximum(self.transmat_prior - 1.0 + stats['trans'], 1e-20), axis=1) class GaussianHMM(_BaseHMM): """Hidden Markov Model with Gaussian emissions Representation of a hidden Markov model probability distribution. This class allows for easy evaluation of, sampling from, and maximum-likelihood estimation of the parameters of a HMM. Attributes ---------- cvtype : string (read-only) String describing the type of covariance parameters used by the model. Must be one of 'spherical', 'tied', 'diag', 'full'. n_features : int (read-only) Dimensionality of the Gaussian emissions. n_components : int (read-only) Number of states in the model. transmat : array, shape (`n_components`, `n_components`) Matrix of transition probabilities between states. startprob : array, shape ('n_components`,) Initial state occupation distribution. means : array, shape (`n_components`, `n_features`) Mean parameters for each state. covars : array Covariance parameters for each state. The shape depends on `cvtype`: (`n_components`,) if 'spherical', (`n_features`, `n_features`) if 'tied', (`n_components`, `n_features`) if 'diag', (`n_components`, `n_features`, `n_features`) if 'full' Methods ------- eval(X) Compute the log likelihood of `X` under the HMM. decode(X) Find most likely state sequence for each point in `X` using the Viterbi algorithm. rvs(n=1) Generate `n` samples from the HMM. init(X) Initialize HMM parameters from `X`. fit(X) Estimate HMM parameters from `X` using the Baum-Welch algorithm. predict(X) Like decode, find most likely state sequence corresponding to `X`. score(X) Compute the log likelihood of `X` under the model. Examples -------- >>> from sklearn.hmm import GaussianHMM >>> GaussianHMM(n_components=2) GaussianHMM(covars_prior=0.01, covars_weight=1, cvtype='diag', means_prior=None, means_weight=0, n_components=2, startprob=array([ 0.5, 0.5]), startprob_prior=1.0, transmat=array([[ 0.5, 0.5], [ 0.5, 0.5]]), transmat_prior=1.0) See Also -------- GMM : Gaussian mixture model """ def __init__(self, n_components=1, cvtype='diag', startprob=None, transmat=None, startprob_prior=None, transmat_prior=None, means_prior=None, means_weight=0, covars_prior=1e-2, covars_weight=1): """Create a hidden Markov model with Gaussian emissions. Initializes parameters such that every state has zero mean and identity covariance. Parameters ---------- n_components : int Number of states. cvtype : string String describing the type of covariance parameters to use. Must be one of 'spherical', 'tied', 'diag', 'full'. Defaults to 'diag'. """ super(GaussianHMM, self).__init__(n_components, startprob, transmat, startprob_prior=startprob_prior, transmat_prior=transmat_prior) self._cvtype = cvtype if not cvtype in ['spherical', 'tied', 'diag', 'full']: raise ValueError('bad cvtype') self.means_prior = means_prior self.means_weight = means_weight self.covars_prior = covars_prior self.covars_weight = covars_weight # Read-only properties. @property def cvtype(self): """Covariance type of the model. Must be one of 'spherical', 'tied', 'diag', 'full'. """ return self._cvtype def _get_means(self): """Mean parameters for each state.""" return self._means def _set_means(self, means): means = np.asanyarray(means) if hasattr(self, 'n_features') and \ means.shape != (self.n_components, self.n_features): raise ValueError('means must have shape (n_components, n_features)') self._means = means.copy() self.n_features = self._means.shape[1] means = property(_get_means, _set_means) def _get_covars(self): """Return covars as a full matrix.""" if self.cvtype == 'full': return self._covars elif self.cvtype == 'diag': return [np.diag(cov) for cov in self._covars] elif self.cvtype == 'tied': return [self._covars] * self.n_components elif self.cvtype == 'spherical': return [np.eye(self.n_features) * f for f in self._covars] def _set_covars(self, covars): covars = np.asanyarray(covars) _validate_covars(covars, self._cvtype, self.n_components, self.n_features) self._covars = covars.copy() covars = property(_get_covars, _set_covars) def _compute_log_likelihood(self, obs): return lmvnpdf(obs, self._means, self._covars, self._cvtype) def _generate_sample_from_state(self, state, random_state=None): if self._cvtype == 'tied': cv = self._covars else: cv = self._covars[state] return sample_gaussian(self._means[state], cv, self._cvtype, random_state=random_state) def _init(self, obs, params='stmc'): super(GaussianHMM, self)._init(obs, params=params) if (hasattr(self, 'n_features') and self.n_features != obs[0].shape[1]): raise ValueError('Unexpected number of dimensions, got %s but ' 'expected %s' % (obs[0].shape[1], self.n_features)) self.n_features = obs[0].shape[1] if 'm' in params: self._means = cluster.KMeans( k=self.n_components).fit(obs[0]).cluster_centers_ if 'c' in params: cv = np.cov(obs[0].T) if not cv.shape: cv.shape = (1, 1) self._covars = _distribute_covar_matrix_to_match_cvtype( cv, self._cvtype, self.n_components) def _initialize_sufficient_statistics(self): stats = super(GaussianHMM, self)._initialize_sufficient_statistics() stats['post'] = np.zeros(self.n_components) stats['obs'] = np.zeros((self.n_components, self.n_features)) stats['obs**2'] = np.zeros((self.n_components, self.n_features)) stats['obs*obs.T'] = np.zeros((self.n_components, self.n_features, self.n_features)) return stats def _accumulate_sufficient_statistics(self, stats, obs, framelogprob, posteriors, fwdlattice, bwdlattice, params): super(GaussianHMM, self)._accumulate_sufficient_statistics( stats, obs, framelogprob, posteriors, fwdlattice, bwdlattice, params) if 'm' in params or 'c' in params: stats['post'] += posteriors.sum(axis=0) stats['obs'] += np.dot(posteriors.T, obs) if 'c' in params: if self._cvtype in ('spherical', 'diag'): stats['obs**2'] += np.dot(posteriors.T, obs ** 2) elif self._cvtype in ('tied', 'full'): for t, o in enumerate(obs): obsobsT = np.outer(o, o) for c in xrange(self.n_components): stats['obs*obs.T'][c] += posteriors[t, c] * obsobsT def _do_mstep(self, stats, params, **kwargs): super(GaussianHMM, self)._do_mstep(stats, params) # Based on Huang, Acero, Hon, "Spoken Language Processing", # p. 443 - 445 denom = stats['post'][:, np.newaxis] if 'm' in params: prior = self.means_prior weight = self.means_weight if prior is None: weight = 0 prior = 0 self._means = (weight * prior + stats['obs']) / (weight + denom) if 'c' in params: covars_prior = self.covars_prior covars_weight = self.covars_weight if covars_prior is None: covars_weight = 0 covars_prior = 0 means_prior = self.means_prior means_weight = self.means_weight if means_prior is None: means_weight = 0 means_prior = 0 meandiff = self._means - means_prior if self._cvtype in ('spherical', 'diag'): cv_num = (means_weight * (meandiff) ** 2 + stats['obs**2'] - 2 * self._means * stats['obs'] + self._means ** 2 * denom) cv_den = max(covars_weight - 1, 0) + denom if self._cvtype == 'spherical': self._covars = (covars_prior / cv_den.mean(axis=1) + np.mean(cv_num / cv_den, axis=1)) elif self._cvtype == 'diag': self._covars = (covars_prior + cv_num) / cv_den elif self._cvtype in ('tied', 'full'): cvnum = np.empty((self.n_components, self.n_features, self.n_features)) for c in xrange(self.n_components): obsmean = np.outer(stats['obs'][c], self._means[c]) cvnum[c] = (means_weight * np.outer(meandiff[c], meandiff[c]) + stats['obs*obs.T'][c] - obsmean - obsmean.T + np.outer(self._means[c], self._means[c]) * stats['post'][c]) cvweight = max(covars_weight - self.n_features, 0) if self._cvtype == 'tied': self._covars = ((covars_prior + cvnum.sum(axis=0)) / (cvweight + stats['post'].sum())) elif self._cvtype == 'full': self._covars = ((covars_prior + cvnum) / (cvweight + stats['post'][:, None, None])) class MultinomialHMM(_BaseHMM): """Hidden Markov Model with multinomial (discrete) emissions Attributes ---------- n_components : int (read-only) Number of states in the model. n_symbols : int Number of possible symbols emitted by the model (in the observations). transmat : array, shape (`n_components`, `n_components`) Matrix of transition probabilities between states. startprob : array, shape ('n_components`,) Initial state occupation distribution. emissionprob: array, shape ('n_components`, 'n_symbols`) Probability of emitting a given symbol when in each state. Methods ------- eval(X) Compute the log likelihood of `X` under the HMM. decode(X) Find most likely state sequence for each point in `X` using the Viterbi algorithm. rvs(n=1) Generate `n` samples from the HMM. init(X) Initialize HMM parameters from `X`. fit(X) Estimate HMM parameters from `X` using the Baum-Welch algorithm. predict(X) Like decode, find most likely state sequence corresponding to `X`. score(X) Compute the log likelihood of `X` under the model. Examples -------- >>> from sklearn.hmm import MultinomialHMM >>> MultinomialHMM(n_components=2) ... #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE MultinomialHMM(n_components=2, startprob=array([ 0.5, 0.5]), startprob_prior=1.0, transmat=array([[ 0.5, 0.5], [ 0.5, 0.5]]), transmat_prior=1.0) See Also -------- GaussianHMM : HMM with Gaussian emissions """ def __init__(self, n_components=1, startprob=None, transmat=None, startprob_prior=None, transmat_prior=None): """Create a hidden Markov model with multinomial emissions. Parameters ---------- n_components : int Number of states. """ super(MultinomialHMM, self).__init__(n_components, startprob, transmat, startprob_prior=startprob_prior, transmat_prior=transmat_prior) def _get_emissionprob(self): """Emission probability distribution for each state.""" return np.exp(self._log_emissionprob) def _set_emissionprob(self, emissionprob): emissionprob = np.asanyarray(emissionprob) if hasattr(self, 'n_symbols') and \ emissionprob.shape != (self.n_components, self.n_symbols): raise ValueError('emissionprob must have shape ' '(n_components, n_symbols)') self._log_emissionprob = np.log(emissionprob) underflow_idx = np.isnan(self._log_emissionprob) self._log_emissionprob[underflow_idx] = -np.Inf self.n_symbols = self._log_emissionprob.shape[1] emissionprob = property(_get_emissionprob, _set_emissionprob) def _compute_log_likelihood(self, obs): return self._log_emissionprob[:, obs].T def _generate_sample_from_state(self, state, random_state=None): cdf = np.cumsum(self.emissionprob[state, :]) random_state = check_random_state(random_state) rand = random_state.rand() symbol = (cdf > rand).argmax() return symbol def _init(self, obs, params='ste'): super(MultinomialHMM, self)._init(obs, params=params) if 'e' in params: emissionprob = normalize(np.random.rand(self.n_components, self.n_symbols), 1) self.emissionprob = emissionprob def _initialize_sufficient_statistics(self): stats = super(MultinomialHMM, self)._initialize_sufficient_statistics() stats['obs'] = np.zeros((self.n_components, self.n_symbols)) return stats def _accumulate_sufficient_statistics(self, stats, obs, framelogprob, posteriors, fwdlattice, bwdlattice, params): super(MultinomialHMM, self)._accumulate_sufficient_statistics( stats, obs, framelogprob, posteriors, fwdlattice, bwdlattice, params) if 'e' in params: for t, symbol in enumerate(obs): stats['obs'][:, symbol] += posteriors[t, :] def _do_mstep(self, stats, params, **kwargs): super(MultinomialHMM, self)._do_mstep(stats, params) if 'e' in params: self.emissionprob = (stats['obs'] / stats['obs'].sum(1)[:, np.newaxis]) class GMMHMM(_BaseHMM): """Hidden Markov Model with Gaussin mixture emissions Attributes ---------- n_components : int (read-only) Number of states in the model. transmat : array, shape (`n_components`, `n_components`) Matrix of transition probabilities between states. startprob : array, shape ('n_components`,) Initial state occupation distribution. gmms: array of GMM objects, length 'n_components` GMM emission distributions for each state Methods ------- eval(X) Compute the log likelihood of `X` under the HMM. decode(X) Find most likely state sequence for each point in `X` using the Viterbi algorithm. rvs(n=1) Generate `n` samples from the HMM. init(X) Initialize HMM parameters from `X`. fit(X) Estimate HMM parameters from `X` using the Baum-Welch algorithm. predict(X) Like decode, find most likely state sequence corresponding to `X`. score(X) Compute the log likelihood of `X` under the model. Examples -------- >>> from sklearn.hmm import GMMHMM >>> GMMHMM(n_components=2, n_mix=10, cvtype='diag') ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE GMMHMM(cvtype='diag', gmms=[GMM(cvtype='diag', n_components=10), GMM(cvtype='diag', n_components=10)], n_components=2, n_mix=10, startprob=array([ 0.5, 0.5]), startprob_prior=1.0, transmat=array([[ 0.5, 0.5], [ 0.5, 0.5]]), transmat_prior=1.0) See Also -------- GaussianHMM : HMM with Gaussian emissions """ def __init__(self, n_components=1, n_mix=1, startprob=None, transmat=None, startprob_prior=None, transmat_prior=None, gmms=None, cvtype=None): """Create a hidden Markov model with GMM emissions. Parameters ---------- n_components : int Number of states. """ super(GMMHMM, self).__init__(n_components, startprob, transmat, startprob_prior=startprob_prior, transmat_prior=transmat_prior) # XXX: Hotfit for n_mix that is incompatible with the scikit's # BaseEstimator API self.n_mix = n_mix self.cvtype = cvtype if gmms is None: gmms = [] for x in xrange(self.n_components): if cvtype is None: g = GMM(n_mix) else: g = GMM(n_mix, cvtype=cvtype) gmms.append(g) self.gmms = gmms def _compute_log_likelihood(self, obs): return np.array([g.score(obs) for g in self.gmms]).T def _generate_sample_from_state(self, state, random_state=None): return self.gmms[state].rvs(1, random_state=random_state).flatten() def _init(self, obs, params='stwmc'): super(GMMHMM, self)._init(obs, params=params) allobs = np.concatenate(obs, 0) for g in self.gmms: g.fit(allobs, n_iter=0, init_params=params) def _initialize_sufficient_statistics(self): stats = super(GMMHMM, self)._initialize_sufficient_statistics() stats['norm'] = [np.zeros(g.weights.shape) for g in self.gmms] stats['means'] = [np.zeros(np.shape(g.means)) for g in self.gmms] stats['covars'] = [np.zeros(np.shape(g._covars)) for g in self.gmms] return stats def _accumulate_sufficient_statistics(self, stats, obs, framelogprob, posteriors, fwdlattice, bwdlattice, params): super(GMMHMM, self)._accumulate_sufficient_statistics( stats, obs, framelogprob, posteriors, fwdlattice, bwdlattice, params) for state, g in enumerate(self.gmms): _, lgmm_posteriors = g.eval(obs, return_log=True) lgmm_posteriors += np.log(posteriors[:, state][:, np.newaxis] + np.finfo(np.float).eps) gmm_posteriors = np.exp(lgmm_posteriors) tmp_gmm = GMM(g.n_components, cvtype=g.cvtype) tmp_gmm.n_features = g.n_features tmp_gmm.covars = _distribute_covar_matrix_to_match_cvtype( np.eye(g.n_features), g.cvtype, g.n_components) norm = tmp_gmm._do_mstep(obs, gmm_posteriors, params) if np.any(np.isnan(tmp_gmm.covars)): raise ValueError stats['norm'][state] += norm if 'm' in params: stats['means'][state] += tmp_gmm.means * norm[:, np.newaxis] if 'c' in params: if tmp_gmm.cvtype == 'tied': stats['covars'][state] += tmp_gmm._covars * norm.sum() else: cvnorm = np.copy(norm) shape = np.ones(tmp_gmm._covars.ndim) shape[0] = np.shape(tmp_gmm._covars)[0] cvnorm.shape = shape stats['covars'][state] += tmp_gmm._covars * cvnorm def _do_mstep(self, stats, params, covars_prior=1e-2, **kwargs): super(GMMHMM, self)._do_mstep(stats, params) # All that is left to do is to apply covars_prior to the # parameters updated in _accumulate_sufficient_statistics. for state, g in enumerate(self.gmms): norm = stats['norm'][state] if 'w' in params: g.weights = normalize(norm) if 'm' in params: g.means = stats['means'][state] / norm[:, np.newaxis] if 'c' in params: if g.cvtype == 'tied': g.covars = ((stats['covars'][state] + covars_prior * np.eye(g.n_features)) / norm.sum()) else: cvnorm = np.copy(norm) shape = np.ones(g._covars.ndim) shape[0] = np.shape(g._covars)[0] cvnorm.shape = shape if g.cvtype == 'spherical' or g.cvtype == 'diag': g.covars = (stats['covars'][state] + covars_prior) / cvnorm elif g.cvtype == 'full': eye = np.eye(g.n_features) g.covars = ((stats['covars'][state] + covars_prior * eye[np.newaxis, :, :]) / cvnorm)
lina1/django-shop
refs/heads/master
shop/tests/templatetags.py
18
from django.test.testcases import TestCase from classytags.tests import DummyParser, DummyTokens from ..models.productmodel import Product from ..templatetags.shop_tags import Products class ProductsTestCase(TestCase): """Tests for the Products templatetag.""" def _create_fixture(self): Product.objects.create( name='product 1', slug='product-1', active=True, unit_price=42) Product.objects.create( name='product 2', slug='product-2', active=True, unit_price=42) Product.objects.create( name='product 3', slug='product-3', active=False, unit_price=42) def test01_should_return_all_active_products(self): self._create_fixture() tag = Products(DummyParser(), DummyTokens()) result = tag.get_context({}, None) self.assertTrue('products' in result) self.assertEqual(len(result['products']), 2) def test02_should_return_objects_given_as_argument(self): self._create_fixture() tag = Products(DummyParser(), DummyTokens()) arg_objects = Product.objects.filter(active=False) result = tag.get_context({}, arg_objects) self.assertTrue('products' in result) self.assertEqual(len(result['products']), 1) def test03_should_return_empty_array_if_no_objects_found(self): self._create_fixture() tag = Products(DummyParser(), DummyTokens()) arg_objects = Product.objects.filter(slug='non-existant-slug') result = tag.get_context({}, arg_objects) self.assertEqual(len(result['products']), 0)
ston380/account-financial-reporting
refs/heads/8.0
account_tax_report_no_zeroes/report/report_vat.py
14
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models from openerp.addons.account.report.report_vat import tax_report from functools import partial class TaxReport(tax_report): def __init__(self, cr, uid, name, context=None): super(TaxReport, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'get_lines': partial(self._get_lines, context=context), }) def _get_lines(self, based_on, company_id=False, parent=False, level=0, context=None): result = super(TaxReport, self)._get_lines( based_on, company_id=company_id, parent=parent, level=level, context=context) return filter(lambda x: x['tax_amount'], result) class ReportVat(models.AbstractModel): _inherit = 'report.account.report_vat' _wrapped_report_class = TaxReport
VigTech/Vigtech-Services
refs/heads/master
env/lib/python2.7/site-packages/django/conf/urls/i18n.py
113
import warnings from django.conf import settings from django.conf.urls import patterns, url from django.core.urlresolvers import LocaleRegexURLResolver from django.utils import six from django.utils.deprecation import RemovedInDjango20Warning from django.views.i18n import set_language def i18n_patterns(prefix, *args): """ Adds the language code prefix to every URL pattern within this function. This may only be used in the root URLconf, not in an included URLconf. """ if isinstance(prefix, six.string_types): warnings.warn( "Calling i18n_patterns() with the `prefix` argument and with tuples " "instead of django.conf.urls.url() instances is deprecated and " "will no longer work in Django 2.0. Use a list of " "django.conf.urls.url() instances instead.", RemovedInDjango20Warning, stacklevel=2 ) pattern_list = patterns(prefix, *args) else: pattern_list = [prefix] + list(args) if not settings.USE_I18N: return pattern_list return [LocaleRegexURLResolver(pattern_list)] urlpatterns = [ url(r'^setlang/$', set_language, name='set_language'), ]
rubencabrera/odoo
refs/heads/8.0
openerp/modules/graph.py
260
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2010-2014 OpenERP s.a. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## """ Modules dependency graph. """ import os, sys, imp from os.path import join as opj import itertools import zipimport import openerp import openerp.osv as osv import openerp.tools as tools import openerp.tools.osutil as osutil from openerp.tools.safe_eval import safe_eval as eval from openerp.tools.translate import _ import zipfile import openerp.release as release import re import base64 from zipfile import PyZipFile, ZIP_DEFLATED from cStringIO import StringIO import logging _logger = logging.getLogger(__name__) class Graph(dict): """ Modules dependency graph. The graph is a mapping from module name to Nodes. """ def add_node(self, name, info): max_depth, father = 0, None for d in info['depends']: n = self.get(d) or Node(d, self, None) # lazy creation, do not use default value for get() if n.depth >= max_depth: father = n max_depth = n.depth if father: return father.add_child(name, info) else: return Node(name, self, info) def update_from_db(self, cr): if not len(self): return # update the graph with values from the database (if exist) ## First, we set the default values for each package in graph additional_data = dict((key, {'id': 0, 'state': 'uninstalled', 'dbdemo': False, 'installed_version': None}) for key in self.keys()) ## Then we get the values from the database cr.execute('SELECT name, id, state, demo AS dbdemo, latest_version AS installed_version' ' FROM ir_module_module' ' WHERE name IN %s',(tuple(additional_data),) ) ## and we update the default values with values from the database additional_data.update((x['name'], x) for x in cr.dictfetchall()) for package in self.values(): for k, v in additional_data[package.name].items(): setattr(package, k, v) def add_module(self, cr, module, force=None): self.add_modules(cr, [module], force) def add_modules(self, cr, module_list, force=None): if force is None: force = [] packages = [] len_graph = len(self) for module in module_list: # This will raise an exception if no/unreadable descriptor file. # NOTE The call to load_information_from_description_file is already # done by db.initialize, so it is possible to not do it again here. info = openerp.modules.module.load_information_from_description_file(module) if info and info['installable']: packages.append((module, info)) # TODO directly a dict, like in get_modules_with_version else: _logger.warning('module %s: not installable, skipped', module) dependencies = dict([(p, info['depends']) for p, info in packages]) current, later = set([p for p, info in packages]), set() while packages and current > later: package, info = packages[0] deps = info['depends'] # if all dependencies of 'package' are already in the graph, add 'package' in the graph if reduce(lambda x, y: x and y in self, deps, True): if not package in current: packages.pop(0) continue later.clear() current.remove(package) node = self.add_node(package, info) for kind in ('init', 'demo', 'update'): if package in tools.config[kind] or 'all' in tools.config[kind] or kind in force: setattr(node, kind, True) else: later.add(package) packages.append((package, info)) packages.pop(0) self.update_from_db(cr) for package in later: unmet_deps = filter(lambda p: p not in self, dependencies[package]) _logger.error('module %s: Unmet dependencies: %s', package, ', '.join(unmet_deps)) result = len(self) - len_graph if result != len(module_list): _logger.warning('Some modules were not loaded.') return result def __iter__(self): level = 0 done = set(self.keys()) while done: level_modules = sorted((name, module) for name, module in self.items() if module.depth==level) for name, module in level_modules: done.remove(name) yield module level += 1 def __str__(self): return '\n'.join(str(n) for n in self if n.depth == 0) class Node(object): """ One module in the modules dependency graph. Node acts as a per-module singleton. A node is constructed via Graph.add_module() or Graph.add_modules(). Some of its fields are from ir_module_module (setted by Graph.update_from_db()). """ def __new__(cls, name, graph, info): if name in graph: inst = graph[name] else: inst = object.__new__(cls) graph[name] = inst return inst def __init__(self, name, graph, info): self.name = name self.graph = graph self.info = info or getattr(self, 'info', {}) if not hasattr(self, 'children'): self.children = [] if not hasattr(self, 'depth'): self.depth = 0 @property def data(self): return self.info def add_child(self, name, info): node = Node(name, self.graph, info) node.depth = self.depth + 1 if node not in self.children: self.children.append(node) for attr in ('init', 'update', 'demo'): if hasattr(self, attr): setattr(node, attr, True) self.children.sort(lambda x, y: cmp(x.name, y.name)) return node def __setattr__(self, name, value): super(Node, self).__setattr__(name, value) if name in ('init', 'update', 'demo'): tools.config[name][self.name] = 1 for child in self.children: setattr(child, name, value) if name == 'depth': for child in self.children: setattr(child, name, value + 1) def __iter__(self): return itertools.chain(iter(self.children), *map(iter, self.children)) def __str__(self): return self._pprint() def _pprint(self, depth=0): s = '%s\n' % self.name for c in self.children: s += '%s`-> %s' % (' ' * depth, c._pprint(depth+1)) return s # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
maxamillion/dnf
refs/heads/master
dnf/cli/aliases.py
2
# aliases.py # Resolving aliases in CLI arguments. # # Copyright (C) 2018 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from dnf.i18n import _ import collections import dnf.cli from dnf.conf.config import PRIO_DEFAULT import dnf.exceptions import libdnf.conf import logging import os import os.path logger = logging.getLogger('dnf') ALIASES_DROPIN_DIR = '/etc/dnf/aliases.d/' ALIASES_CONF_PATH = os.path.join(ALIASES_DROPIN_DIR, 'ALIASES.conf') ALIASES_USER_PATH = os.path.join(ALIASES_DROPIN_DIR, 'USER.conf') class AliasesConfig(object): def __init__(self, path): self._path = path self._parser = libdnf.conf.ConfigParser() self._parser.read(self._path) @property def enabled(self): option = libdnf.conf.OptionBool(True) try: option.set(PRIO_DEFAULT, self._parser.getData()["main"]["enabled"]) except IndexError: pass return option.getValue() @property def aliases(self): result = collections.OrderedDict() section = "aliases" if not self._parser.hasSection(section): return result for key in self._parser.options(section): value = self._parser.getValue(section, key) if not value: continue result[key] = value.split() return result class Aliases(object): def __init__(self): self.aliases = collections.OrderedDict() self.conf = None self.enabled = True if self._disabled_by_environ(): self.enabled = False return self._load_main() if not self.enabled: return self._load_aliases() def _disabled_by_environ(self): option = libdnf.conf.OptionBool(True) try: option.set(PRIO_DEFAULT, os.environ['DNF_DISABLE_ALIASES']) return option.getValue() except KeyError: return False except RuntimeError: logger.warning( _('Unexpected value of environment variable: ' 'DNF_DISABLE_ALIASES=%s'), os.environ['DNF_DISABLE_ALIASES']) return True def _load_conf(self, path): try: return AliasesConfig(path) except RuntimeError as e: raise dnf.exceptions.ConfigError( _('Parsing file "%s" failed: %s') % (path, e)) except IOError as e: raise dnf.exceptions.ConfigError( _('Cannot read file "%s": %s') % (path, e)) def _load_main(self): try: self.conf = self._load_conf(ALIASES_CONF_PATH) self.enabled = self.conf.enabled except dnf.exceptions.ConfigError as e: logger.debug(_('Config error: %s'), e) def _load_aliases(self, filenames=None): if filenames is None: try: filenames = self._dropin_dir_filenames() except dnf.exceptions.ConfigError: return for filename in filenames: try: conf = self._load_conf(filename) self.aliases.update(conf.aliases) except dnf.exceptions.ConfigError as e: logger.warning(_('Config error: %s'), e) def _dropin_dir_filenames(self): # Get default aliases config filenames: # all files from ALIASES_DROPIN_DIR, # and ALIASES_USER_PATH as the last one (-> override all others) ignored_filenames = [os.path.basename(ALIASES_CONF_PATH), os.path.basename(ALIASES_USER_PATH)] def _ignore_filename(filename): return filename in ignored_filenames or\ filename.startswith('.') or\ not filename.endswith(('.conf', '.CONF')) filenames = [] try: if not os.path.exists(ALIASES_DROPIN_DIR): os.mkdir(ALIASES_DROPIN_DIR) for fn in os.listdir(ALIASES_DROPIN_DIR): if _ignore_filename(fn): continue filenames.append(os.path.join(ALIASES_DROPIN_DIR, fn)) except (IOError, OSError) as e: raise dnf.exceptions.ConfigError(e) if os.path.exists(ALIASES_USER_PATH): filenames.append(ALIASES_USER_PATH) return filenames def _resolve(self, args): stack = [] self.prefix_options = [] def store_prefix(args): num = 0 for arg in args: if arg and arg[0] != '-': break num += 1 self.prefix_options += args[:num] return args[num:] def subresolve(args): suffix = store_prefix(args) if (not suffix or # Current alias on stack is resolved suffix[0] not in self.aliases or # End resolving suffix[0].startswith('\\')): # End resolving try: stack.pop() except IndexError: pass return suffix if suffix[0] in stack: # Infinite recursion detected raise dnf.exceptions.Error( _('Aliases contain infinite recursion')) # Next word must be an alias stack.append(suffix[0]) current_alias_result = subresolve(self.aliases[suffix[0]]) if current_alias_result: # We reached non-alias or '\' return current_alias_result + suffix[1:] else: # Need to resolve aliases in the rest return subresolve(suffix[1:]) suffix = subresolve(args) return self.prefix_options + suffix def resolve(self, args): if self.enabled: try: args = self._resolve(args) except dnf.exceptions.Error as e: logger.error(_('%s, using original arguments.'), e) return args
Ryezhang/scrapy
refs/heads/master
scrapy/item.py
16
""" Scrapy Item See documentation in docs/topics/item.rst """ from pprint import pformat from collections import MutableMapping from abc import ABCMeta import six from scrapy.utils.trackref import object_ref class BaseItem(object_ref): """Base class for all scraped items.""" pass class Field(dict): """Container of field metadata""" class ItemMeta(ABCMeta): def __new__(mcs, class_name, bases, attrs): classcell = attrs.pop('__classcell__', None) new_bases = tuple(base._class for base in bases if hasattr(base, '_class')) _class = super(ItemMeta, mcs).__new__(mcs, 'x_' + class_name, new_bases, attrs) fields = getattr(_class, 'fields', {}) new_attrs = {} for n in dir(_class): v = getattr(_class, n) if isinstance(v, Field): fields[n] = v elif n in attrs: new_attrs[n] = attrs[n] new_attrs['fields'] = fields new_attrs['_class'] = _class if classcell is not None: new_attrs['__classcell__'] = classcell return super(ItemMeta, mcs).__new__(mcs, class_name, bases, new_attrs) class DictItem(MutableMapping, BaseItem): fields = {} def __init__(self, *args, **kwargs): self._values = {} if args or kwargs: # avoid creating dict for most common case for k, v in six.iteritems(dict(*args, **kwargs)): self[k] = v def __getitem__(self, key): return self._values[key] def __setitem__(self, key, value): if key in self.fields: self._values[key] = value else: raise KeyError("%s does not support field: %s" % (self.__class__.__name__, key)) def __delitem__(self, key): del self._values[key] def __getattr__(self, name): if name in self.fields: raise AttributeError("Use item[%r] to get field value" % name) raise AttributeError(name) def __setattr__(self, name, value): if not name.startswith('_'): raise AttributeError("Use item[%r] = %r to set field value" % (name, value)) super(DictItem, self).__setattr__(name, value) def __len__(self): return len(self._values) def __iter__(self): return iter(self._values) __hash__ = BaseItem.__hash__ def keys(self): return self._values.keys() def __repr__(self): return pformat(dict(self)) def copy(self): return self.__class__(self) @six.add_metaclass(ItemMeta) class Item(DictItem): pass
foodszhang/kbengine
refs/heads/master
kbe/src/lib/python/Lib/test/test_getpass.py
97
import getpass import os import unittest from io import BytesIO, StringIO, TextIOWrapper from unittest import mock from test import support try: import termios except ImportError: termios = None try: import pwd except ImportError: pwd = None @mock.patch('os.environ') class GetpassGetuserTest(unittest.TestCase): def test_username_takes_username_from_env(self, environ): expected_name = 'some_name' environ.get.return_value = expected_name self.assertEqual(expected_name, getpass.getuser()) def test_username_priorities_of_env_values(self, environ): environ.get.return_value = None try: getpass.getuser() except ImportError: # in case there's no pwd module pass self.assertEqual( environ.get.call_args_list, [mock.call(x) for x in ('LOGNAME', 'USER', 'LNAME', 'USERNAME')]) def test_username_falls_back_to_pwd(self, environ): expected_name = 'some_name' environ.get.return_value = None if pwd: with mock.patch('os.getuid') as uid, \ mock.patch('pwd.getpwuid') as getpw: uid.return_value = 42 getpw.return_value = [expected_name] self.assertEqual(expected_name, getpass.getuser()) getpw.assert_called_once_with(42) else: self.assertRaises(ImportError, getpass.getuser) class GetpassRawinputTest(unittest.TestCase): def test_flushes_stream_after_prompt(self): # see issue 1703 stream = mock.Mock(spec=StringIO) input = StringIO('input_string') getpass._raw_input('some_prompt', stream, input=input) stream.flush.assert_called_once_with() def test_uses_stderr_as_default(self): input = StringIO('input_string') prompt = 'some_prompt' with mock.patch('sys.stderr') as stderr: getpass._raw_input(prompt, input=input) stderr.write.assert_called_once_with(prompt) @mock.patch('sys.stdin') def test_uses_stdin_as_default_input(self, mock_input): mock_input.readline.return_value = 'input_string' getpass._raw_input(stream=StringIO()) mock_input.readline.assert_called_once_with() @mock.patch('sys.stdin') def test_uses_stdin_as_different_locale(self, mock_input): stream = TextIOWrapper(BytesIO(), encoding="ascii") mock_input.readline.return_value = "Hasło: " getpass._raw_input(prompt="Hasło: ",stream=stream) mock_input.readline.assert_called_once_with() def test_raises_on_empty_input(self): input = StringIO('') self.assertRaises(EOFError, getpass._raw_input, input=input) def test_trims_trailing_newline(self): input = StringIO('test\n') self.assertEqual('test', getpass._raw_input(input=input)) # Some of these tests are a bit white-box. The functional requirement is that # the password input be taken directly from the tty, and that it not be echoed # on the screen, unless we are falling back to stderr/stdin. # Some of these might run on platforms without termios, but play it safe. @unittest.skipUnless(termios, 'tests require system with termios') class UnixGetpassTest(unittest.TestCase): def test_uses_tty_directly(self): with mock.patch('os.open') as open, \ mock.patch('io.FileIO') as fileio, \ mock.patch('io.TextIOWrapper') as textio: # By setting open's return value to None the implementation will # skip code we don't care about in this test. We can mock this out # fully if an alternate implementation works differently. open.return_value = None getpass.unix_getpass() open.assert_called_once_with('/dev/tty', os.O_RDWR | os.O_NOCTTY) fileio.assert_called_once_with(open.return_value, 'w+') textio.assert_called_once_with(fileio.return_value) def test_resets_termios(self): with mock.patch('os.open') as open, \ mock.patch('io.FileIO'), \ mock.patch('io.TextIOWrapper'), \ mock.patch('termios.tcgetattr') as tcgetattr, \ mock.patch('termios.tcsetattr') as tcsetattr: open.return_value = 3 fake_attrs = [255, 255, 255, 255, 255] tcgetattr.return_value = list(fake_attrs) getpass.unix_getpass() tcsetattr.assert_called_with(3, mock.ANY, fake_attrs) def test_falls_back_to_fallback_if_termios_raises(self): with mock.patch('os.open') as open, \ mock.patch('io.FileIO') as fileio, \ mock.patch('io.TextIOWrapper') as textio, \ mock.patch('termios.tcgetattr'), \ mock.patch('termios.tcsetattr') as tcsetattr, \ mock.patch('getpass.fallback_getpass') as fallback: open.return_value = 3 fileio.return_value = BytesIO() tcsetattr.side_effect = termios.error getpass.unix_getpass() fallback.assert_called_once_with('Password: ', textio.return_value) def test_flushes_stream_after_input(self): # issue 7208 with mock.patch('os.open') as open, \ mock.patch('io.FileIO'), \ mock.patch('io.TextIOWrapper'), \ mock.patch('termios.tcgetattr'), \ mock.patch('termios.tcsetattr'): open.return_value = 3 mock_stream = mock.Mock(spec=StringIO) getpass.unix_getpass(stream=mock_stream) mock_stream.flush.assert_called_with() def test_falls_back_to_stdin(self): with mock.patch('os.open') as os_open, \ mock.patch('sys.stdin', spec=StringIO) as stdin: os_open.side_effect = IOError stdin.fileno.side_effect = AttributeError with support.captured_stderr() as stderr: with self.assertWarns(getpass.GetPassWarning): getpass.unix_getpass() stdin.readline.assert_called_once_with() self.assertIn('Warning', stderr.getvalue()) self.assertIn('Password:', stderr.getvalue()) if __name__ == "__main__": unittest.main()
devsaurus/nodemcu-firmware
refs/heads/dev
tools/make_server_cert.py
13
import os import argparse import base64 import re import sys class Cert(object): def __init__(self, name, buff): self.name = name self.len = len(buff) self.buff = buff pass def __str__(self): out_str = ['\0']*32 for i in range(len(self.name)): out_str[i] = self.name[i] out_str = "".join(out_str) out_str += str(chr(self.len & 0xFF)) out_str += str(chr((self.len & 0xFF00) >> 8)) out_str += self.buff return out_str def main(): parser = argparse.ArgumentParser(description='Convert PEM file(s) into C source file.') parser.add_argument('--section', default='.servercert.flash', help='specify the section for the data (default is .servercert.flash)') parser.add_argument('--name', default='tls_server_cert_area', help='specify the variable name for the data (default is tls_server_cert_area)') parser.add_argument('file', nargs='+', help='One or more PEM files') args = parser.parse_args() cert_list = [] cert_file_list = [] for cert_file in args.file: with open(cert_file, 'r') as f: buff = f.read() m = re.search(r"-----BEGIN ([A-Z ]+)-----([^-]+?)-----END \1-----", buff, flags=re.DOTALL) if not m: sys.exit("Input file was not in PEM format") if "----BEGIN" in buff[m.end(0):]: sys.exit("Input file contains more than one PEM object") cert_list.append(Cert(m.group(1), base64.b64decode(''.join(m.group(2).split())))) print '__attribute__((section("%s"))) unsigned char %s[INTERNAL_FLASH_SECTOR_SIZE] = {' % (args.section, args.name) for _cert in cert_list: col = 0 for ch in str(_cert): print ("0x%02x," % ord(ch)), if col & 15 == 15: print col = col + 1 print '\n0xff};\n' if __name__ == '__main__': main()
thusoy/paramiko
refs/heads/master
paramiko/pkey.py
33
# Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at your option) # any later version. # # Paramiko 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 Paramiko; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. """ Common API for all public keys. """ import base64 from binascii import hexlify, unhexlify import os from hashlib import md5 from Crypto.Cipher import DES3, AES from paramiko import util from paramiko.common import o600, zero_byte from paramiko.py3compat import u, encodebytes, decodebytes, b from paramiko.ssh_exception import SSHException, PasswordRequiredException class PKey (object): """ Base class for public keys. """ # known encryption types for private key files: _CIPHER_TABLE = { 'AES-128-CBC': {'cipher': AES, 'keysize': 16, 'blocksize': 16, 'mode': AES.MODE_CBC}, 'DES-EDE3-CBC': {'cipher': DES3, 'keysize': 24, 'blocksize': 8, 'mode': DES3.MODE_CBC}, } def __init__(self, msg=None, data=None): """ Create a new instance of this public key type. If ``msg`` is given, the key's public part(s) will be filled in from the message. If ``data`` is given, the key's public part(s) will be filled in from the string. :param .Message msg: an optional SSH `.Message` containing a public key of this type. :param str data: an optional string containing a public key of this type :raises SSHException: if a key cannot be created from the ``data`` or ``msg`` given, or no key was passed in. """ pass def asbytes(self): """ Return a string of an SSH `.Message` made up of the public part(s) of this key. This string is suitable for passing to `__init__` to re-create the key object later. """ return bytes() def __str__(self): return self.asbytes() # noinspection PyUnresolvedReferences def __cmp__(self, other): """ Compare this key to another. Returns 0 if this key is equivalent to the given key, or non-0 if they are different. Only the public parts of the key are compared, so a public key will compare equal to its corresponding private key. :param .Pkey other: key to compare to. """ hs = hash(self) ho = hash(other) if hs != ho: return cmp(hs, ho) return cmp(self.asbytes(), other.asbytes()) def __eq__(self, other): return hash(self) == hash(other) def get_name(self): """ Return the name of this private key implementation. :return: name of this private key type, in SSH terminology, as a `str` (for example, ``"ssh-rsa"``). """ return '' def get_bits(self): """ Return the number of significant bits in this key. This is useful for judging the relative security of a key. :return: bits in the key (as an `int`) """ return 0 def can_sign(self): """ Return ``True`` if this key has the private part necessary for signing data. """ return False def get_fingerprint(self): """ Return an MD5 fingerprint of the public part of this key. Nothing secret is revealed. :return: a 16-byte `string <str>` (binary) of the MD5 fingerprint, in SSH format. """ return md5(self.asbytes()).digest() def get_base64(self): """ Return a base64 string containing the public part of this key. Nothing secret is revealed. This format is compatible with that used to store public key files or recognized host keys. :return: a base64 `string <str>` containing the public part of the key. """ return u(encodebytes(self.asbytes())).replace('\n', '') def sign_ssh_data(self, data): """ Sign a blob of data with this private key, and return a `.Message` representing an SSH signature message. :param str data: the data to sign. :return: an SSH signature `message <.Message>`. """ return bytes() def verify_ssh_sig(self, data, msg): """ Given a blob of data, and an SSH message representing a signature of that data, verify that it was signed with this key. :param str data: the data that was signed. :param .Message msg: an SSH signature message :return: ``True`` if the signature verifies correctly; ``False`` otherwise. """ return False @classmethod def from_private_key_file(cls, filename, password=None): """ Create a key object by reading a private key file. If the private key is encrypted and ``password`` is not ``None``, the given password will be used to decrypt the key (otherwise `.PasswordRequiredException` is thrown). Through the magic of Python, this factory method will exist in all subclasses of PKey (such as `.RSAKey` or `.DSSKey`), but is useless on the abstract PKey class. :param str filename: name of the file to read :param str password: an optional password to use to decrypt the key file, if it's encrypted :return: a new `.PKey` based on the given private key :raises IOError: if there was an error reading the file :raises PasswordRequiredException: if the private key file is encrypted, and ``password`` is ``None`` :raises SSHException: if the key file is invalid """ key = cls(filename=filename, password=password) return key @classmethod def from_private_key(cls, file_obj, password=None): """ Create a key object by reading a private key from a file (or file-like) object. If the private key is encrypted and ``password`` is not ``None``, the given password will be used to decrypt the key (otherwise `.PasswordRequiredException` is thrown). :param file file_obj: the file to read from :param str password: an optional password to use to decrypt the key, if it's encrypted :return: a new `.PKey` based on the given private key :raises IOError: if there was an error reading the key :raises PasswordRequiredException: if the private key file is encrypted, and ``password`` is ``None`` :raises SSHException: if the key file is invalid """ key = cls(file_obj=file_obj, password=password) return key def write_private_key_file(self, filename, password=None): """ Write private key contents into a file. If the password is not ``None``, the key is encrypted before writing. :param str filename: name of the file to write :param str password: an optional password to use to encrypt the key file :raises IOError: if there was an error writing the file :raises SSHException: if the key is invalid """ raise Exception('Not implemented in PKey') def write_private_key(self, file_obj, password=None): """ Write private key contents into a file (or file-like) object. If the password is not ``None``, the key is encrypted before writing. :param file file_obj: the file object to write into :param str password: an optional password to use to encrypt the key :raises IOError: if there was an error writing to the file :raises SSHException: if the key is invalid """ raise Exception('Not implemented in PKey') def _read_private_key_file(self, tag, filename, password=None): """ Read an SSH2-format private key file, looking for a string of the type ``"BEGIN xxx PRIVATE KEY"`` for some ``xxx``, base64-decode the text we find, and return it as a string. If the private key is encrypted and ``password`` is not ``None``, the given password will be used to decrypt the key (otherwise `.PasswordRequiredException` is thrown). :param str tag: ``"RSA"`` or ``"DSA"``, the tag used to mark the data block. :param str filename: name of the file to read. :param str password: an optional password to use to decrypt the key file, if it's encrypted. :return: data blob (`str`) that makes up the private key. :raises IOError: if there was an error reading the file. :raises PasswordRequiredException: if the private key file is encrypted, and ``password`` is ``None``. :raises SSHException: if the key file is invalid. """ with open(filename, 'r') as f: data = self._read_private_key(tag, f, password) return data def _read_private_key(self, tag, f, password=None): lines = f.readlines() start = 0 while (start < len(lines)) and (lines[start].strip() != '-----BEGIN ' + tag + ' PRIVATE KEY-----'): start += 1 if start >= len(lines): raise SSHException('not a valid ' + tag + ' private key file') # parse any headers first headers = {} start += 1 while start < len(lines): l = lines[start].split(': ') if len(l) == 1: break headers[l[0].lower()] = l[1].strip() start += 1 # find end end = start while (lines[end].strip() != '-----END ' + tag + ' PRIVATE KEY-----') and (end < len(lines)): end += 1 # if we trudged to the end of the file, just try to cope. try: data = decodebytes(b(''.join(lines[start:end]))) except base64.binascii.Error as e: raise SSHException('base64 decoding error: ' + str(e)) if 'proc-type' not in headers: # unencryped: done return data # encrypted keyfile: will need a password if headers['proc-type'] != '4,ENCRYPTED': raise SSHException('Unknown private key structure "%s"' % headers['proc-type']) try: encryption_type, saltstr = headers['dek-info'].split(',') except: raise SSHException("Can't parse DEK-info in private key file") if encryption_type not in self._CIPHER_TABLE: raise SSHException('Unknown private key cipher "%s"' % encryption_type) # if no password was passed in, raise an exception pointing out that we need one if password is None: raise PasswordRequiredException('Private key file is encrypted') cipher = self._CIPHER_TABLE[encryption_type]['cipher'] keysize = self._CIPHER_TABLE[encryption_type]['keysize'] mode = self._CIPHER_TABLE[encryption_type]['mode'] salt = unhexlify(b(saltstr)) key = util.generate_key_bytes(md5, salt, password, keysize) return cipher.new(key, mode, salt).decrypt(data) def _write_private_key_file(self, tag, filename, data, password=None): """ Write an SSH2-format private key file in a form that can be read by paramiko or openssh. If no password is given, the key is written in a trivially-encoded format (base64) which is completely insecure. If a password is given, DES-EDE3-CBC is used. :param str tag: ``"RSA"`` or ``"DSA"``, the tag used to mark the data block. :param file filename: name of the file to write. :param str data: data blob that makes up the private key. :param str password: an optional password to use to encrypt the file. :raises IOError: if there was an error writing the file. """ with open(filename, 'w', o600) as f: # grrr... the mode doesn't always take hold os.chmod(filename, o600) self._write_private_key(tag, f, data, password) def _write_private_key(self, tag, f, data, password=None): f.write('-----BEGIN %s PRIVATE KEY-----\n' % tag) if password is not None: cipher_name = list(self._CIPHER_TABLE.keys())[0] cipher = self._CIPHER_TABLE[cipher_name]['cipher'] keysize = self._CIPHER_TABLE[cipher_name]['keysize'] blocksize = self._CIPHER_TABLE[cipher_name]['blocksize'] mode = self._CIPHER_TABLE[cipher_name]['mode'] salt = os.urandom(blocksize) key = util.generate_key_bytes(md5, salt, password, keysize) if len(data) % blocksize != 0: n = blocksize - len(data) % blocksize #data += os.urandom(n) # that would make more sense ^, but it confuses openssh. data += zero_byte * n data = cipher.new(key, mode, salt).encrypt(data) f.write('Proc-Type: 4,ENCRYPTED\n') f.write('DEK-Info: %s,%s\n' % (cipher_name, u(hexlify(salt)).upper())) f.write('\n') s = u(encodebytes(data)) # re-wrap to 64-char lines s = ''.join(s.split('\n')) s = '\n'.join([s[i: i + 64] for i in range(0, len(s), 64)]) f.write(s) f.write('\n') f.write('-----END %s PRIVATE KEY-----\n' % tag)
rvraghav93/scikit-learn
refs/heads/master
sklearn/metrics/__init__.py
8
""" The :mod:`sklearn.metrics` module includes score functions, performance metrics and pairwise metrics and distance computations. """ from .ranking import auc from .ranking import average_precision_score from .ranking import coverage_error from .ranking import label_ranking_average_precision_score from .ranking import label_ranking_loss from .ranking import precision_recall_curve from .ranking import roc_auc_score from .ranking import roc_curve from .ranking import dcg_score from .ranking import ndcg_score from .classification import accuracy_score from .classification import classification_report from .classification import cohen_kappa_score from .classification import confusion_matrix from .classification import f1_score from .classification import fbeta_score from .classification import hamming_loss from .classification import hinge_loss from .classification import jaccard_similarity_score from .classification import log_loss from .classification import matthews_corrcoef from .classification import precision_recall_fscore_support from .classification import precision_score from .classification import recall_score from .classification import zero_one_loss from .classification import brier_score_loss from . import cluster from .cluster import adjusted_mutual_info_score from .cluster import adjusted_rand_score from .cluster import completeness_score from .cluster import consensus_score from .cluster import homogeneity_completeness_v_measure from .cluster import homogeneity_score from .cluster import mutual_info_score from .cluster import normalized_mutual_info_score from .cluster import fowlkes_mallows_score from .cluster import silhouette_samples from .cluster import silhouette_score from .cluster import calinski_harabaz_score from .cluster import v_measure_score from .pairwise import euclidean_distances from .pairwise import pairwise_distances from .pairwise import pairwise_distances_argmin from .pairwise import pairwise_distances_argmin_min from .pairwise import pairwise_kernels from .regression import explained_variance_score from .regression import mean_absolute_error from .regression import mean_squared_error from .regression import mean_squared_log_error from .regression import median_absolute_error from .regression import r2_score from .scorer import make_scorer from .scorer import SCORERS from .scorer import get_scorer __all__ = [ 'accuracy_score', 'adjusted_mutual_info_score', 'adjusted_rand_score', 'auc', 'average_precision_score', 'classification_report', 'cluster', 'completeness_score', 'confusion_matrix', 'consensus_score', 'coverage_error', 'euclidean_distances', 'explained_variance_score', 'f1_score', 'fbeta_score', 'get_scorer', 'hamming_loss', 'hinge_loss', 'homogeneity_completeness_v_measure', 'homogeneity_score', 'jaccard_similarity_score', 'label_ranking_average_precision_score', 'label_ranking_loss', 'log_loss', 'make_scorer', 'matthews_corrcoef', 'mean_absolute_error', 'mean_squared_error', 'mean_squared_log_error', 'median_absolute_error', 'mutual_info_score', 'normalized_mutual_info_score', 'pairwise_distances', 'pairwise_distances_argmin', 'pairwise_distances_argmin_min', 'pairwise_distances_argmin_min', 'pairwise_kernels', 'precision_recall_curve', 'precision_recall_fscore_support', 'precision_score', 'r2_score', 'recall_score', 'roc_auc_score', 'roc_curve', 'SCORERS', 'silhouette_samples', 'silhouette_score', 'v_measure_score', 'zero_one_loss', 'brier_score_loss', 'dcg_score', 'ndcg_score' ]
lombritz/odoo
refs/heads/8.0
addons/hr_payroll/wizard/__init__.py
442
#-*- coding:utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # d$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import hr_payroll_payslips_by_employees import hr_payroll_contribution_register_report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
bhansa/fireball
refs/heads/master
pyvenv/Lib/site-packages/pip/_vendor/packaging/specifiers.py
1107
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import abc import functools import itertools import re from ._compat import string_types, with_metaclass from .version import Version, LegacyVersion, parse class InvalidSpecifier(ValueError): """ An invalid specifier was found, users should refer to PEP 440. """ class BaseSpecifier(with_metaclass(abc.ABCMeta, object)): @abc.abstractmethod def __str__(self): """ Returns the str representation of this Specifier like object. This should be representative of the Specifier itself. """ @abc.abstractmethod def __hash__(self): """ Returns a hash value for this Specifier like object. """ @abc.abstractmethod def __eq__(self, other): """ Returns a boolean representing whether or not the two Specifier like objects are equal. """ @abc.abstractmethod def __ne__(self, other): """ Returns a boolean representing whether or not the two Specifier like objects are not equal. """ @abc.abstractproperty def prereleases(self): """ Returns whether or not pre-releases as a whole are allowed by this specifier. """ @prereleases.setter def prereleases(self, value): """ Sets whether or not pre-releases as a whole are allowed by this specifier. """ @abc.abstractmethod def contains(self, item, prereleases=None): """ Determines if the given item is contained within this specifier. """ @abc.abstractmethod def filter(self, iterable, prereleases=None): """ Takes an iterable of items and filters them so that only items which are contained within this specifier are allowed in it. """ class _IndividualSpecifier(BaseSpecifier): _operators = {} def __init__(self, spec="", prereleases=None): match = self._regex.search(spec) if not match: raise InvalidSpecifier("Invalid specifier: '{0}'".format(spec)) self._spec = ( match.group("operator").strip(), match.group("version").strip(), ) # Store whether or not this Specifier should accept prereleases self._prereleases = prereleases def __repr__(self): pre = ( ", prereleases={0!r}".format(self.prereleases) if self._prereleases is not None else "" ) return "<{0}({1!r}{2})>".format( self.__class__.__name__, str(self), pre, ) def __str__(self): return "{0}{1}".format(*self._spec) def __hash__(self): return hash(self._spec) def __eq__(self, other): if isinstance(other, string_types): try: other = self.__class__(other) except InvalidSpecifier: return NotImplemented elif not isinstance(other, self.__class__): return NotImplemented return self._spec == other._spec def __ne__(self, other): if isinstance(other, string_types): try: other = self.__class__(other) except InvalidSpecifier: return NotImplemented elif not isinstance(other, self.__class__): return NotImplemented return self._spec != other._spec def _get_operator(self, op): return getattr(self, "_compare_{0}".format(self._operators[op])) def _coerce_version(self, version): if not isinstance(version, (LegacyVersion, Version)): version = parse(version) return version @property def operator(self): return self._spec[0] @property def version(self): return self._spec[1] @property def prereleases(self): return self._prereleases @prereleases.setter def prereleases(self, value): self._prereleases = value def __contains__(self, item): return self.contains(item) def contains(self, item, prereleases=None): # Determine if prereleases are to be allowed or not. if prereleases is None: prereleases = self.prereleases # Normalize item to a Version or LegacyVersion, this allows us to have # a shortcut for ``"2.0" in Specifier(">=2") item = self._coerce_version(item) # Determine if we should be supporting prereleases in this specifier # or not, if we do not support prereleases than we can short circuit # logic if this version is a prereleases. if item.is_prerelease and not prereleases: return False # Actually do the comparison to determine if this item is contained # within this Specifier or not. return self._get_operator(self.operator)(item, self.version) def filter(self, iterable, prereleases=None): yielded = False found_prereleases = [] kw = {"prereleases": prereleases if prereleases is not None else True} # Attempt to iterate over all the values in the iterable and if any of # them match, yield them. for version in iterable: parsed_version = self._coerce_version(version) if self.contains(parsed_version, **kw): # If our version is a prerelease, and we were not set to allow # prereleases, then we'll store it for later incase nothing # else matches this specifier. if (parsed_version.is_prerelease and not (prereleases or self.prereleases)): found_prereleases.append(version) # Either this is not a prerelease, or we should have been # accepting prereleases from the begining. else: yielded = True yield version # Now that we've iterated over everything, determine if we've yielded # any values, and if we have not and we have any prereleases stored up # then we will go ahead and yield the prereleases. if not yielded and found_prereleases: for version in found_prereleases: yield version class LegacySpecifier(_IndividualSpecifier): _regex_str = ( r""" (?P<operator>(==|!=|<=|>=|<|>)) \s* (?P<version> [^,;\s)]* # Since this is a "legacy" specifier, and the version # string can be just about anything, we match everything # except for whitespace, a semi-colon for marker support, # a closing paren since versions can be enclosed in # them, and a comma since it's a version separator. ) """ ) _regex = re.compile( r"^\s*" + _regex_str + r"\s*$", re.VERBOSE | re.IGNORECASE) _operators = { "==": "equal", "!=": "not_equal", "<=": "less_than_equal", ">=": "greater_than_equal", "<": "less_than", ">": "greater_than", } def _coerce_version(self, version): if not isinstance(version, LegacyVersion): version = LegacyVersion(str(version)) return version def _compare_equal(self, prospective, spec): return prospective == self._coerce_version(spec) def _compare_not_equal(self, prospective, spec): return prospective != self._coerce_version(spec) def _compare_less_than_equal(self, prospective, spec): return prospective <= self._coerce_version(spec) def _compare_greater_than_equal(self, prospective, spec): return prospective >= self._coerce_version(spec) def _compare_less_than(self, prospective, spec): return prospective < self._coerce_version(spec) def _compare_greater_than(self, prospective, spec): return prospective > self._coerce_version(spec) def _require_version_compare(fn): @functools.wraps(fn) def wrapped(self, prospective, spec): if not isinstance(prospective, Version): return False return fn(self, prospective, spec) return wrapped class Specifier(_IndividualSpecifier): _regex_str = ( r""" (?P<operator>(~=|==|!=|<=|>=|<|>|===)) (?P<version> (?: # The identity operators allow for an escape hatch that will # do an exact string match of the version you wish to install. # This will not be parsed by PEP 440 and we cannot determine # any semantic meaning from it. This operator is discouraged # but included entirely as an escape hatch. (?<====) # Only match for the identity operator \s* [^\s]* # We just match everything, except for whitespace # since we are only testing for strict identity. ) | (?: # The (non)equality operators allow for wild card and local # versions to be specified so we have to define these two # operators separately to enable that. (?<===|!=) # Only match for equals and not equals \s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)* # release (?: # pre release [-_\.]? (a|b|c|rc|alpha|beta|pre|preview) [-_\.]? [0-9]* )? (?: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? # You cannot use a wild card and a dev or local version # together so group them with a | and make them optional. (?: (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release (?:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local | \.\* # Wild card syntax of .* )? ) | (?: # The compatible operator requires at least two digits in the # release segment. (?<=~=) # Only match for the compatible operator \s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) (?: # pre release [-_\.]? (a|b|c|rc|alpha|beta|pre|preview) [-_\.]? [0-9]* )? (?: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release ) | (?: # All other operators only allow a sub set of what the # (non)equality operators do. Specifically they do not allow # local versions to be specified nor do they allow the prefix # matching wild cards. (?<!==|!=|~=) # We have special cases for these # operators so we want to make sure they # don't match here. \s* v? (?:[0-9]+!)? # epoch [0-9]+(?:\.[0-9]+)* # release (?: # pre release [-_\.]? (a|b|c|rc|alpha|beta|pre|preview) [-_\.]? [0-9]* )? (?: # post release (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) )? (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release ) ) """ ) _regex = re.compile( r"^\s*" + _regex_str + r"\s*$", re.VERBOSE | re.IGNORECASE) _operators = { "~=": "compatible", "==": "equal", "!=": "not_equal", "<=": "less_than_equal", ">=": "greater_than_equal", "<": "less_than", ">": "greater_than", "===": "arbitrary", } @_require_version_compare def _compare_compatible(self, prospective, spec): # Compatible releases have an equivalent combination of >= and ==. That # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to # implement this in terms of the other specifiers instead of # implementing it ourselves. The only thing we need to do is construct # the other specifiers. # We want everything but the last item in the version, but we want to # ignore post and dev releases and we want to treat the pre-release as # it's own separate segment. prefix = ".".join( list( itertools.takewhile( lambda x: (not x.startswith("post") and not x.startswith("dev")), _version_split(spec), ) )[:-1] ) # Add the prefix notation to the end of our string prefix += ".*" return (self._get_operator(">=")(prospective, spec) and self._get_operator("==")(prospective, prefix)) @_require_version_compare def _compare_equal(self, prospective, spec): # We need special logic to handle prefix matching if spec.endswith(".*"): # In the case of prefix matching we want to ignore local segment. prospective = Version(prospective.public) # Split the spec out by dots, and pretend that there is an implicit # dot in between a release segment and a pre-release segment. spec = _version_split(spec[:-2]) # Remove the trailing .* # Split the prospective version out by dots, and pretend that there # is an implicit dot in between a release segment and a pre-release # segment. prospective = _version_split(str(prospective)) # Shorten the prospective version to be the same length as the spec # so that we can determine if the specifier is a prefix of the # prospective version or not. prospective = prospective[:len(spec)] # Pad out our two sides with zeros so that they both equal the same # length. spec, prospective = _pad_version(spec, prospective) else: # Convert our spec string into a Version spec = Version(spec) # If the specifier does not have a local segment, then we want to # act as if the prospective version also does not have a local # segment. if not spec.local: prospective = Version(prospective.public) return prospective == spec @_require_version_compare def _compare_not_equal(self, prospective, spec): return not self._compare_equal(prospective, spec) @_require_version_compare def _compare_less_than_equal(self, prospective, spec): return prospective <= Version(spec) @_require_version_compare def _compare_greater_than_equal(self, prospective, spec): return prospective >= Version(spec) @_require_version_compare def _compare_less_than(self, prospective, spec): # Convert our spec to a Version instance, since we'll want to work with # it as a version. spec = Version(spec) # Check to see if the prospective version is less than the spec # version. If it's not we can short circuit and just return False now # instead of doing extra unneeded work. if not prospective < spec: return False # This special case is here so that, unless the specifier itself # includes is a pre-release version, that we do not accept pre-release # versions for the version mentioned in the specifier (e.g. <3.1 should # not match 3.1.dev0, but should match 3.0.dev0). if not spec.is_prerelease and prospective.is_prerelease: if Version(prospective.base_version) == Version(spec.base_version): return False # If we've gotten to here, it means that prospective version is both # less than the spec version *and* it's not a pre-release of the same # version in the spec. return True @_require_version_compare def _compare_greater_than(self, prospective, spec): # Convert our spec to a Version instance, since we'll want to work with # it as a version. spec = Version(spec) # Check to see if the prospective version is greater than the spec # version. If it's not we can short circuit and just return False now # instead of doing extra unneeded work. if not prospective > spec: return False # This special case is here so that, unless the specifier itself # includes is a post-release version, that we do not accept # post-release versions for the version mentioned in the specifier # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0). if not spec.is_postrelease and prospective.is_postrelease: if Version(prospective.base_version) == Version(spec.base_version): return False # Ensure that we do not allow a local version of the version mentioned # in the specifier, which is techincally greater than, to match. if prospective.local is not None: if Version(prospective.base_version) == Version(spec.base_version): return False # If we've gotten to here, it means that prospective version is both # greater than the spec version *and* it's not a pre-release of the # same version in the spec. return True def _compare_arbitrary(self, prospective, spec): return str(prospective).lower() == str(spec).lower() @property def prereleases(self): # If there is an explicit prereleases set for this, then we'll just # blindly use that. if self._prereleases is not None: return self._prereleases # Look at all of our specifiers and determine if they are inclusive # operators, and if they are if they are including an explicit # prerelease. operator, version = self._spec if operator in ["==", ">=", "<=", "~=", "==="]: # The == specifier can include a trailing .*, if it does we # want to remove before parsing. if operator == "==" and version.endswith(".*"): version = version[:-2] # Parse the version, and if it is a pre-release than this # specifier allows pre-releases. if parse(version).is_prerelease: return True return False @prereleases.setter def prereleases(self, value): self._prereleases = value _prefix_regex = re.compile(r"^([0-9]+)((?:a|b|c|rc)[0-9]+)$") def _version_split(version): result = [] for item in version.split("."): match = _prefix_regex.search(item) if match: result.extend(match.groups()) else: result.append(item) return result def _pad_version(left, right): left_split, right_split = [], [] # Get the release segment of our versions left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left))) right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right))) # Get the rest of our versions left_split.append(left[len(left_split[0]):]) right_split.append(right[len(right_split[0]):]) # Insert our padding left_split.insert( 1, ["0"] * max(0, len(right_split[0]) - len(left_split[0])), ) right_split.insert( 1, ["0"] * max(0, len(left_split[0]) - len(right_split[0])), ) return ( list(itertools.chain(*left_split)), list(itertools.chain(*right_split)), ) class SpecifierSet(BaseSpecifier): def __init__(self, specifiers="", prereleases=None): # Split on , to break each indidivual specifier into it's own item, and # strip each item to remove leading/trailing whitespace. specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] # Parsed each individual specifier, attempting first to make it a # Specifier and falling back to a LegacySpecifier. parsed = set() for specifier in specifiers: try: parsed.add(Specifier(specifier)) except InvalidSpecifier: parsed.add(LegacySpecifier(specifier)) # Turn our parsed specifiers into a frozen set and save them for later. self._specs = frozenset(parsed) # Store our prereleases value so we can use it later to determine if # we accept prereleases or not. self._prereleases = prereleases def __repr__(self): pre = ( ", prereleases={0!r}".format(self.prereleases) if self._prereleases is not None else "" ) return "<SpecifierSet({0!r}{1})>".format(str(self), pre) def __str__(self): return ",".join(sorted(str(s) for s in self._specs)) def __hash__(self): return hash(self._specs) def __and__(self, other): if isinstance(other, string_types): other = SpecifierSet(other) elif not isinstance(other, SpecifierSet): return NotImplemented specifier = SpecifierSet() specifier._specs = frozenset(self._specs | other._specs) if self._prereleases is None and other._prereleases is not None: specifier._prereleases = other._prereleases elif self._prereleases is not None and other._prereleases is None: specifier._prereleases = self._prereleases elif self._prereleases == other._prereleases: specifier._prereleases = self._prereleases else: raise ValueError( "Cannot combine SpecifierSets with True and False prerelease " "overrides." ) return specifier def __eq__(self, other): if isinstance(other, string_types): other = SpecifierSet(other) elif isinstance(other, _IndividualSpecifier): other = SpecifierSet(str(other)) elif not isinstance(other, SpecifierSet): return NotImplemented return self._specs == other._specs def __ne__(self, other): if isinstance(other, string_types): other = SpecifierSet(other) elif isinstance(other, _IndividualSpecifier): other = SpecifierSet(str(other)) elif not isinstance(other, SpecifierSet): return NotImplemented return self._specs != other._specs def __len__(self): return len(self._specs) def __iter__(self): return iter(self._specs) @property def prereleases(self): # If we have been given an explicit prerelease modifier, then we'll # pass that through here. if self._prereleases is not None: return self._prereleases # If we don't have any specifiers, and we don't have a forced value, # then we'll just return None since we don't know if this should have # pre-releases or not. if not self._specs: return None # Otherwise we'll see if any of the given specifiers accept # prereleases, if any of them do we'll return True, otherwise False. return any(s.prereleases for s in self._specs) @prereleases.setter def prereleases(self, value): self._prereleases = value def __contains__(self, item): return self.contains(item) def contains(self, item, prereleases=None): # Ensure that our item is a Version or LegacyVersion instance. if not isinstance(item, (LegacyVersion, Version)): item = parse(item) # Determine if we're forcing a prerelease or not, if we're not forcing # one for this particular filter call, then we'll use whatever the # SpecifierSet thinks for whether or not we should support prereleases. if prereleases is None: prereleases = self.prereleases # We can determine if we're going to allow pre-releases by looking to # see if any of the underlying items supports them. If none of them do # and this item is a pre-release then we do not allow it and we can # short circuit that here. # Note: This means that 1.0.dev1 would not be contained in something # like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0 if not prereleases and item.is_prerelease: return False # We simply dispatch to the underlying specs here to make sure that the # given version is contained within all of them. # Note: This use of all() here means that an empty set of specifiers # will always return True, this is an explicit design decision. return all( s.contains(item, prereleases=prereleases) for s in self._specs ) def filter(self, iterable, prereleases=None): # Determine if we're forcing a prerelease or not, if we're not forcing # one for this particular filter call, then we'll use whatever the # SpecifierSet thinks for whether or not we should support prereleases. if prereleases is None: prereleases = self.prereleases # If we have any specifiers, then we want to wrap our iterable in the # filter method for each one, this will act as a logical AND amongst # each specifier. if self._specs: for spec in self._specs: iterable = spec.filter(iterable, prereleases=bool(prereleases)) return iterable # If we do not have any specifiers, then we need to have a rough filter # which will filter out any pre-releases, unless there are no final # releases, and which will filter out LegacyVersion in general. else: filtered = [] found_prereleases = [] for item in iterable: # Ensure that we some kind of Version class for this item. if not isinstance(item, (LegacyVersion, Version)): parsed_version = parse(item) else: parsed_version = item # Filter out any item which is parsed as a LegacyVersion if isinstance(parsed_version, LegacyVersion): continue # Store any item which is a pre-release for later unless we've # already found a final version or we are accepting prereleases if parsed_version.is_prerelease and not prereleases: if not filtered: found_prereleases.append(item) else: filtered.append(item) # If we've found no items except for pre-releases, then we'll go # ahead and use the pre-releases if not filtered and found_prereleases and prereleases is None: return found_prereleases return filtered
ThinkOpen-Solutions/odoo
refs/heads/stable
addons/resource/faces/observer.py
433
#@+leo-ver=4 #@+node:@file observer.py #@@language python #@<< Copyright >> #@+node:<< Copyright >> ############################################################################ # Copyright (C) 2005, 2006, 2007, 2008 by Reithinger GmbH # mreithinger@web.de # # This file is part of faces. # # faces 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. # # faces is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ############################################################################ #@-node:<< Copyright >> #@nl """ This module contains the base class for all observer objects """ #@<< Imports >> #@+node:<< Imports >> #@-node:<< Imports >> #@nl _is_source_ = True #@+others #@+node:class Observer class Observer(object): """ Base Class for all charts and reports. @var visible: Specifies if the observer is visible at the navigation bar inside the gui. @var link_view: syncronizes the marked objects in all views. """ #@ << declarations >> #@+node:<< declarations >> __type_name__ = None __type_image__ = None visible = True link_view = True __attrib_completions__ = { "visible" : 'visible = False', "link_view" : "link_view = False" } #@-node:<< declarations >> #@nl #@ @+others #@+node:register_editors def register_editors(cls, registry): pass register_editors = classmethod(register_editors) #@-node:register_editors #@-others #@-node:class Observer #@-others factories = { } clear_cache_funcs = {} #@-node:@file observer.py #@-leo # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
newswangerd/ansible
refs/heads/devel
lib/ansible/playbook/playbook_include.py
6
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import ansible.constants as C from ansible.errors import AnsibleParserError, AnsibleAssertionError from ansible.module_utils._text import to_bytes from ansible.module_utils.six import iteritems, string_types from ansible.parsing.splitter import split_args, parse_kv from ansible.parsing.yaml.objects import AnsibleBaseYAMLObject, AnsibleMapping from ansible.playbook.attribute import FieldAttribute from ansible.playbook.base import Base from ansible.playbook.conditional import Conditional from ansible.playbook.taggable import Taggable from ansible.utils.collection_loader import AnsibleCollectionConfig from ansible.utils.collection_loader._collection_finder import _get_collection_name_from_path, _get_collection_playbook_path from ansible.template import Templar from ansible.utils.display import Display display = Display() class PlaybookInclude(Base, Conditional, Taggable): _import_playbook = FieldAttribute(isa='string') _vars = FieldAttribute(isa='dict', default=dict) @staticmethod def load(data, basedir, variable_manager=None, loader=None): return PlaybookInclude().load_data(ds=data, basedir=basedir, variable_manager=variable_manager, loader=loader) def load_data(self, ds, basedir, variable_manager=None, loader=None): ''' Overrides the base load_data(), as we're actually going to return a new Playbook() object rather than a PlaybookInclude object ''' # import here to avoid a dependency loop from ansible.playbook import Playbook from ansible.playbook.play import Play # first, we use the original parent method to correctly load the object # via the load_data/preprocess_data system we normally use for other # playbook objects new_obj = super(PlaybookInclude, self).load_data(ds, variable_manager, loader) all_vars = self.vars.copy() if variable_manager: all_vars.update(variable_manager.get_vars()) templar = Templar(loader=loader, variables=all_vars) # then we use the object to load a Playbook pb = Playbook(loader=loader) file_name = templar.template(new_obj.import_playbook) # check for FQCN resource = _get_collection_playbook_path(file_name) if resource is not None: playbook = resource[1] playbook_collection = resource[2] else: # not FQCN try path playbook = file_name if not os.path.isabs(playbook): playbook = os.path.join(basedir, playbook) # might still be collection playbook playbook_collection = _get_collection_name_from_path(playbook) if playbook_collection: # it is a collection playbook, setup default collections AnsibleCollectionConfig.default_collection = playbook_collection else: # it is NOT a collection playbook, setup adjecent paths AnsibleCollectionConfig.playbook_paths.append(os.path.dirname(os.path.abspath(to_bytes(playbook, errors='surrogate_or_strict')))) pb._load_playbook_data(file_name=playbook, variable_manager=variable_manager, vars=self.vars.copy()) # finally, update each loaded playbook entry with any variables specified # on the included playbook and/or any tags which may have been set for entry in pb._entries: # conditional includes on a playbook need a marker to skip gathering if new_obj.when and isinstance(entry, Play): entry._included_conditional = new_obj.when[:] temp_vars = entry.vars.copy() temp_vars.update(new_obj.vars) param_tags = temp_vars.pop('tags', None) if param_tags is not None: entry.tags.extend(param_tags.split(',')) entry.vars = temp_vars entry.tags = list(set(entry.tags).union(new_obj.tags)) if entry._included_path is None: entry._included_path = os.path.dirname(playbook) # Check to see if we need to forward the conditionals on to the included # plays. If so, we can take a shortcut here and simply prepend them to # those attached to each block (if any) if new_obj.when: for task_block in (entry.pre_tasks + entry.roles + entry.tasks + entry.post_tasks): task_block._attributes['when'] = new_obj.when[:] + task_block.when[:] return pb def preprocess_data(self, ds): ''' Regorganizes the data for a PlaybookInclude datastructure to line up with what we expect the proper attributes to be ''' if not isinstance(ds, dict): raise AnsibleAssertionError('ds (%s) should be a dict but was a %s' % (ds, type(ds))) # the new, cleaned datastructure, which will have legacy # items reduced to a standard structure new_ds = AnsibleMapping() if isinstance(ds, AnsibleBaseYAMLObject): new_ds.ansible_pos = ds.ansible_pos for (k, v) in iteritems(ds): if k in C._ACTION_ALL_IMPORT_PLAYBOOKS: self._preprocess_import(ds, new_ds, k, v) else: # some basic error checking, to make sure vars are properly # formatted and do not conflict with k=v parameters if k == 'vars': if 'vars' in new_ds: raise AnsibleParserError("import_playbook parameters cannot be mixed with 'vars' entries for import statements", obj=ds) elif not isinstance(v, dict): raise AnsibleParserError("vars for import_playbook statements must be specified as a dictionary", obj=ds) new_ds[k] = v return super(PlaybookInclude, self).preprocess_data(new_ds) def _preprocess_import(self, ds, new_ds, k, v): ''' Splits the playbook import line up into filename and parameters ''' if v is None: raise AnsibleParserError("playbook import parameter is missing", obj=ds) elif not isinstance(v, string_types): raise AnsibleParserError("playbook import parameter must be a string indicating a file path, got %s instead" % type(v), obj=ds) # The import_playbook line must include at least one item, which is the filename # to import. Anything after that should be regarded as a parameter to the import items = split_args(v) if len(items) == 0: raise AnsibleParserError("import_playbook statements must specify the file name to import", obj=ds) else: new_ds['import_playbook'] = items[0].strip() if len(items) > 1: display.warning('Additional parameters in import_playbook statements are not supported. This will be an error in version 2.14') # rejoin the parameter portion of the arguments and # then use parse_kv() to get a dict of params back params = parse_kv(" ".join(items[1:])) if 'tags' in params: new_ds['tags'] = params.pop('tags') if 'vars' in new_ds: raise AnsibleParserError("import_playbook parameters cannot be mixed with 'vars' entries for import statements", obj=ds) new_ds['vars'] = params
sfcl/severcart
refs/heads/master
reports/tests.py
24123
from django.test import TestCase # Create your tests here.
rogerscristo/BotFWD
refs/heads/master
env/lib/python3.6/site-packages/pytests/test_callbackquery.py
1
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2017 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. import json import pytest from telegram import CallbackQuery, User, Message, Chat @pytest.fixture(scope='class', params=['message', 'inline']) def callback_query(bot, request): cb = CallbackQuery(id=TestCallbackQuery.id, from_user=TestCallbackQuery.from_user, chat_instance=TestCallbackQuery.chat_instance, data=TestCallbackQuery.data, game_short_name=TestCallbackQuery.game_short_name, bot=bot) if request.param == 'message': cb.message = TestCallbackQuery.message else: cb.inline_message_id = TestCallbackQuery.inline_message_id return cb class TestCallbackQuery: id = 'id' from_user = User(1, 'test_user') chat_instance = 'chat_instance' message = Message(3, User(5, 'bot'), None, Chat(4, 'private')) data = 'data' inline_message_id = 'inline_message_id' game_short_name = 'the_game' def test_de_json(self, bot): json_dict = {'id': self.id, 'from': self.from_user.to_dict(), 'chat_instance': self.chat_instance, 'message': self.message.to_dict(), 'data': self.data, 'inline_message_id': self.inline_message_id, 'game_short_name': self.game_short_name} callbackquery = CallbackQuery.de_json(json_dict, bot) assert callbackquery.id == self.id assert callbackquery.from_user == self.from_user assert callbackquery.chat_instance == self.chat_instance assert callbackquery.message == self.message assert callbackquery.data == self.data assert callbackquery.inline_message_id == self.inline_message_id assert callbackquery.game_short_name == self.game_short_name def test_to_json(self, callback_query): json.loads(callback_query.to_json()) def test_to_dict(self, callback_query): callback_query_dict = callback_query.to_dict() assert isinstance(callback_query_dict, dict) assert callback_query_dict['id'] == callback_query.id assert callback_query_dict['from'] == callback_query.from_user.to_dict() assert callback_query_dict['chat_instance'] == callback_query.chat_instance if callback_query.message: assert callback_query_dict['message'] == callback_query.message.to_dict() else: assert callback_query_dict['inline_message_id'] == callback_query.inline_message_id assert callback_query_dict['data'] == callback_query.data assert callback_query_dict['game_short_name'] == callback_query.game_short_name def test_answer(self, monkeypatch, callback_query): def test(*args, **kwargs): return args[1] == callback_query.id monkeypatch.setattr('telegram.Bot.answerCallbackQuery', test) # TODO: PEP8 assert callback_query.answer() def test_edit_message_text(self, monkeypatch, callback_query): def test(*args, **kwargs): try: id = kwargs['inline_message_id'] == callback_query.inline_message_id text = kwargs['text'] == 'test' return id and text except KeyError: chat_id = kwargs['chat_id'] == callback_query.message.chat_id message_id = kwargs['message_id'] == callback_query.message.message_id text = kwargs['text'] == 'test' return chat_id and message_id and text monkeypatch.setattr('telegram.Bot.edit_message_text', test) assert callback_query.edit_message_text(text="test") def test_edit_message_caption(self, monkeypatch, callback_query): def test(*args, **kwargs): try: id = kwargs['inline_message_id'] == callback_query.inline_message_id caption = kwargs['caption'] == 'new caption' return id and caption except KeyError: id = kwargs['chat_id'] == callback_query.message.chat_id message = kwargs['message_id'] == callback_query.message.message_id caption = kwargs['caption'] == 'new caption' return id and message and caption monkeypatch.setattr('telegram.Bot.edit_message_caption', test) assert callback_query.edit_message_caption(caption='new caption') def test_edit_message_reply_markup(self, monkeypatch, callback_query): def test(*args, **kwargs): try: id = kwargs['inline_message_id'] == callback_query.inline_message_id reply_markup = kwargs['reply_markup'] == [["1", "2"]] return id and reply_markup except KeyError: id = kwargs['chat_id'] == callback_query.message.chat_id message = kwargs['message_id'] == callback_query.message.message_id reply_markup = kwargs['reply_markup'] == [["1", "2"]] return id and message and reply_markup monkeypatch.setattr('telegram.Bot.edit_message_reply_markup', test) assert callback_query.edit_message_reply_markup(reply_markup=[["1", "2"]])
aYukiSekiguchi/ACCESS-Chromium
refs/heads/master
tools/python/google/platform_utils_mac.py
10
# Copyright (c) 2011 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. """Platform-specific utility methods shared by several scripts.""" import os import subprocess import google.path_utils class PlatformUtility(object): def __init__(self, base_dir): """Args: base_dir: the base dir for running tests. """ self._base_dir = base_dir self._httpd_cmd_string = None # used for starting/stopping httpd self._bash = "/bin/bash" def _UnixRoot(self): """Returns the path to root.""" return "/" def GetFilesystemRoot(self): """Returns the root directory of the file system.""" return self._UnixRoot() def GetTempDirectory(self): """Returns the file system temp directory Note that this does not use a random subdirectory, so it's not intrinsically secure. If you need a secure subdir, use the tempfile package. """ return os.getenv("TMPDIR", "/tmp") def FilenameToUri(self, path, use_http=False, use_ssl=False, port=8000): """Convert a filesystem path to a URI. Args: path: For an http URI, the path relative to the httpd server's DocumentRoot; for a file URI, the full path to the file. use_http: if True, returns a URI of the form http://127.0.0.1:8000/. If False, returns a file:/// URI. use_ssl: if True, returns HTTPS URL (https://127.0.0.1:8000/). This parameter is ignored if use_http=False. port: The port number to append when returning an HTTP URI """ if use_http: protocol = 'http' if use_ssl: protocol = 'https' return "%s://127.0.0.1:%d/%s" % (protocol, port, path) return "file://" + path def GetStartHttpdCommand(self, output_dir, httpd_conf_path, mime_types_path, document_root=None, apache2=False): """Prepares the config file and output directory to start an httpd server. Returns a list of strings containing the server's command line+args. Args: output_dir: the path to the server's output directory, for log files. It will be created if necessary. httpd_conf_path: full path to the httpd.conf file to be used. mime_types_path: full path to the mime.types file to be used. document_root: full path to the DocumentRoot. If None, the DocumentRoot from the httpd.conf file will be used. Note that the httpd.conf file alongside this script does not specify any DocumentRoot, so if you're using that one, be sure to specify a document_root here. apache2: boolean if true will cause this function to return start command for Apache 2.x as opposed to Apache 1.3.x. This flag is ignored on Mac (but preserved here for compatibility in function signature with win), where httpd2 is used always """ exe_name = "httpd" cert_file = google.path_utils.FindUpward(self._base_dir, 'tools', 'python', 'google', 'httpd_config', 'httpd2.pem') ssl_enabled = os.path.exists('/etc/apache2/mods-enabled/ssl.conf') httpd_vars = { "httpd_executable_path": os.path.join(self._UnixRoot(), "usr", "sbin", exe_name), "httpd_conf_path": httpd_conf_path, "ssl_certificate_file": cert_file, "document_root" : document_root, "server_root": os.path.join(self._UnixRoot(), "usr"), "mime_types_path": mime_types_path, "output_dir": output_dir, "ssl_mutex": "file:"+os.path.join(output_dir, "ssl_mutex"), "user": os.environ.get("USER", "#%d" % os.geteuid()), "lock_file": os.path.join(output_dir, "accept.lock"), } google.path_utils.MaybeMakeDirectory(output_dir) # We have to wrap the command in bash # -C: process directive before reading config files # -c: process directive after reading config files # Apache wouldn't run CGIs with permissions==700 unless we add # -c User "<username>" httpd_cmd_string = ( '%(httpd_executable_path)s' ' -f %(httpd_conf_path)s' ' -c \'TypesConfig "%(mime_types_path)s"\'' ' -c \'CustomLog "%(output_dir)s/access_log.txt" common\'' ' -c \'ErrorLog "%(output_dir)s/error_log.txt"\'' ' -c \'PidFile "%(output_dir)s/httpd.pid"\'' ' -C \'User "%(user)s"\'' ' -C \'ServerRoot "%(server_root)s"\'' ' -c \'LockFile "%(lock_file)s"\'' ) if document_root: httpd_cmd_string += ' -C \'DocumentRoot "%(document_root)s"\'' if ssl_enabled: httpd_cmd_string += ( ' -c \'SSLCertificateFile "%(ssl_certificate_file)s"\'' ' -c \'SSLMutex "%(ssl_mutex)s"\'' ) # Save a copy of httpd_cmd_string to use for stopping httpd self._httpd_cmd_string = httpd_cmd_string % httpd_vars httpd_cmd = [self._bash, "-c", self._httpd_cmd_string] return httpd_cmd def GetStopHttpdCommand(self): """Returns a list of strings that contains the command line+args needed to stop the http server used in the http tests. This tries to fetch the pid of httpd (if available) and returns the command to kill it. If pid is not available, kill all httpd processes """ if not self._httpd_cmd_string: return ["true"] # Haven't been asked for the start cmd yet. Just pass. return [self._bash, "-c", self._httpd_cmd_string + ' -k stop']
swinter2011/login-page-update
refs/heads/master
wtforms/csrf/session.py
193
""" A provided CSRF implementation which puts CSRF data in a session. This can be used fairly comfortably with many `request.session` type objects, including the Werkzeug/Flask session store, Django sessions, and potentially other similar objects which use a dict-like API for storing session keys. The basic concept is a randomly generated value is stored in the user's session, and an hmac-sha1 of it (along with an optional expiration time, for extra security) is used as the value of the csrf_token. If this token validates with the hmac of the random value + expiration time, and the expiration time is not passed, the CSRF validation will pass. """ from __future__ import unicode_literals import hmac import os from hashlib import sha1 from datetime import datetime, timedelta from ..validators import ValidationError from .core import CSRF __all__ = ('SessionCSRF', ) class SessionCSRF(CSRF): TIME_FORMAT = '%Y%m%d%H%M%S' def setup_form(self, form): self.form_meta = form.meta return super(SessionCSRF, self).setup_form(form) def generate_csrf_token(self, csrf_token_field): meta = self.form_meta if meta.csrf_secret is None: raise Exception('must set `csrf_secret` on class Meta for SessionCSRF to work') if meta.csrf_context is None: raise TypeError('Must provide a session-like object as csrf context') session = self.session if 'csrf' not in session: session['csrf'] = sha1(os.urandom(64)).hexdigest() if self.time_limit: expires = (self.now() + self.time_limit).strftime(self.TIME_FORMAT) csrf_build = '%s%s' % (session['csrf'], expires) else: expires = '' csrf_build = session['csrf'] hmac_csrf = hmac.new(meta.csrf_secret, csrf_build.encode('utf8'), digestmod=sha1) return '%s##%s' % (expires, hmac_csrf.hexdigest()) def validate_csrf_token(self, form, field): meta = self.form_meta if not field.data or '##' not in field.data: raise ValidationError(field.gettext('CSRF token missing')) expires, hmac_csrf = field.data.split('##', 1) check_val = (self.session['csrf'] + expires).encode('utf8') hmac_compare = hmac.new(meta.csrf_secret, check_val, digestmod=sha1) if hmac_compare.hexdigest() != hmac_csrf: raise ValidationError(field.gettext('CSRF failed')) if self.time_limit: now_formatted = self.now().strftime(self.TIME_FORMAT) if now_formatted > expires: raise ValidationError(field.gettext('CSRF token expired')) def now(self): """ Get the current time. Used for test mocking/overriding mainly. """ return datetime.now() @property def time_limit(self): return getattr(self.form_meta, 'csrf_time_limit', timedelta(minutes=30)) @property def session(self): return getattr(self.form_meta.csrf_context, 'session', self.form_meta.csrf_context)
mancoast/CPythonPyc_test
refs/heads/master
cpython/265_test_class.py
56
"Test the functionality of Python classes implementing operators." import unittest from test import test_support testmeths = [ # Binary operations "add", "radd", "sub", "rsub", "mul", "rmul", "div", "rdiv", "mod", "rmod", "divmod", "rdivmod", "pow", "rpow", "rshift", "rrshift", "lshift", "rlshift", "and", "rand", "or", "ror", "xor", "rxor", # List/dict operations "contains", "getitem", "getslice", "setitem", "setslice", "delitem", "delslice", # Unary operations "neg", "pos", "abs", # generic operations "init", ] # These need to return something other than None # "coerce", # "hash", # "str", # "repr", # "int", # "long", # "float", # "oct", # "hex", # These are separate because they can influence the test of other methods. # "getattr", # "setattr", # "delattr", callLst = [] def trackCall(f): def track(*args, **kwargs): callLst.append((f.__name__, args)) return f(*args, **kwargs) return track class AllTests: trackCall = trackCall @trackCall def __coerce__(self, *args): return (self,) + args @trackCall def __hash__(self, *args): return hash(id(self)) @trackCall def __str__(self, *args): return "AllTests" @trackCall def __repr__(self, *args): return "AllTests" @trackCall def __int__(self, *args): return 1 @trackCall def __float__(self, *args): return 1.0 @trackCall def __long__(self, *args): return 1L @trackCall def __oct__(self, *args): return '01' @trackCall def __hex__(self, *args): return '0x1' @trackCall def __cmp__(self, *args): return 0 # Synthesize all the other AllTests methods from the names in testmeths. method_template = """\ @trackCall def __%(method)s__(self, *args): pass """ for method in testmeths: exec method_template % locals() in AllTests.__dict__ del method, method_template class ClassTests(unittest.TestCase): def setUp(self): callLst[:] = [] def assertCallStack(self, expected_calls): actualCallList = callLst[:] # need to copy because the comparison below will add # additional calls to callLst if expected_calls != actualCallList: self.fail("Expected call list:\n %s\ndoes not match actual call list\n %s" % (expected_calls, actualCallList)) def testInit(self): foo = AllTests() self.assertCallStack([("__init__", (foo,))]) def testBinaryOps(self): testme = AllTests() # Binary operations callLst[:] = [] testme + 1 self.assertCallStack([("__coerce__", (testme, 1)), ("__add__", (testme, 1))]) callLst[:] = [] 1 + testme self.assertCallStack([("__coerce__", (testme, 1)), ("__radd__", (testme, 1))]) callLst[:] = [] testme - 1 self.assertCallStack([("__coerce__", (testme, 1)), ("__sub__", (testme, 1))]) callLst[:] = [] 1 - testme self.assertCallStack([("__coerce__", (testme, 1)), ("__rsub__", (testme, 1))]) callLst[:] = [] testme * 1 self.assertCallStack([("__coerce__", (testme, 1)), ("__mul__", (testme, 1))]) callLst[:] = [] 1 * testme self.assertCallStack([("__coerce__", (testme, 1)), ("__rmul__", (testme, 1))]) if 1/2 == 0: callLst[:] = [] testme / 1 self.assertCallStack([("__coerce__", (testme, 1)), ("__div__", (testme, 1))]) callLst[:] = [] 1 / testme self.assertCallStack([("__coerce__", (testme, 1)), ("__rdiv__", (testme, 1))]) callLst[:] = [] testme % 1 self.assertCallStack([("__coerce__", (testme, 1)), ("__mod__", (testme, 1))]) callLst[:] = [] 1 % testme self.assertCallStack([("__coerce__", (testme, 1)), ("__rmod__", (testme, 1))]) callLst[:] = [] divmod(testme,1) self.assertCallStack([("__coerce__", (testme, 1)), ("__divmod__", (testme, 1))]) callLst[:] = [] divmod(1, testme) self.assertCallStack([("__coerce__", (testme, 1)), ("__rdivmod__", (testme, 1))]) callLst[:] = [] testme ** 1 self.assertCallStack([("__coerce__", (testme, 1)), ("__pow__", (testme, 1))]) callLst[:] = [] 1 ** testme self.assertCallStack([("__coerce__", (testme, 1)), ("__rpow__", (testme, 1))]) callLst[:] = [] testme >> 1 self.assertCallStack([("__coerce__", (testme, 1)), ("__rshift__", (testme, 1))]) callLst[:] = [] 1 >> testme self.assertCallStack([("__coerce__", (testme, 1)), ("__rrshift__", (testme, 1))]) callLst[:] = [] testme << 1 self.assertCallStack([("__coerce__", (testme, 1)), ("__lshift__", (testme, 1))]) callLst[:] = [] 1 << testme self.assertCallStack([("__coerce__", (testme, 1)), ("__rlshift__", (testme, 1))]) callLst[:] = [] testme & 1 self.assertCallStack([("__coerce__", (testme, 1)), ("__and__", (testme, 1))]) callLst[:] = [] 1 & testme self.assertCallStack([("__coerce__", (testme, 1)), ("__rand__", (testme, 1))]) callLst[:] = [] testme | 1 self.assertCallStack([("__coerce__", (testme, 1)), ("__or__", (testme, 1))]) callLst[:] = [] 1 | testme self.assertCallStack([("__coerce__", (testme, 1)), ("__ror__", (testme, 1))]) callLst[:] = [] testme ^ 1 self.assertCallStack([("__coerce__", (testme, 1)), ("__xor__", (testme, 1))]) callLst[:] = [] 1 ^ testme self.assertCallStack([("__coerce__", (testme, 1)), ("__rxor__", (testme, 1))]) def testListAndDictOps(self): testme = AllTests() # List/dict operations class Empty: pass try: 1 in Empty() self.fail('failed, should have raised TypeError') except TypeError: pass callLst[:] = [] 1 in testme self.assertCallStack([('__contains__', (testme, 1))]) callLst[:] = [] testme[1] self.assertCallStack([('__getitem__', (testme, 1))]) callLst[:] = [] testme[1] = 1 self.assertCallStack([('__setitem__', (testme, 1, 1))]) callLst[:] = [] del testme[1] self.assertCallStack([('__delitem__', (testme, 1))]) callLst[:] = [] testme[:42] self.assertCallStack([('__getslice__', (testme, 0, 42))]) callLst[:] = [] testme[:42] = "The Answer" self.assertCallStack([('__setslice__', (testme, 0, 42, "The Answer"))]) callLst[:] = [] del testme[:42] self.assertCallStack([('__delslice__', (testme, 0, 42))]) callLst[:] = [] testme[2:1024:10] self.assertCallStack([('__getitem__', (testme, slice(2, 1024, 10)))]) callLst[:] = [] testme[2:1024:10] = "A lot" self.assertCallStack([('__setitem__', (testme, slice(2, 1024, 10), "A lot"))]) callLst[:] = [] del testme[2:1024:10] self.assertCallStack([('__delitem__', (testme, slice(2, 1024, 10)))]) callLst[:] = [] testme[:42, ..., :24:, 24, 100] self.assertCallStack([('__getitem__', (testme, (slice(None, 42, None), Ellipsis, slice(None, 24, None), 24, 100)))]) callLst[:] = [] testme[:42, ..., :24:, 24, 100] = "Strange" self.assertCallStack([('__setitem__', (testme, (slice(None, 42, None), Ellipsis, slice(None, 24, None), 24, 100), "Strange"))]) callLst[:] = [] del testme[:42, ..., :24:, 24, 100] self.assertCallStack([('__delitem__', (testme, (slice(None, 42, None), Ellipsis, slice(None, 24, None), 24, 100)))]) # Now remove the slice hooks to see if converting normal slices to # slice object works. getslice = AllTests.__getslice__ del AllTests.__getslice__ setslice = AllTests.__setslice__ del AllTests.__setslice__ delslice = AllTests.__delslice__ del AllTests.__delslice__ # XXX when using new-style classes the slice testme[:42] produces # slice(None, 42, None) instead of slice(0, 42, None). py3k will have # to change this test. callLst[:] = [] testme[:42] self.assertCallStack([('__getitem__', (testme, slice(0, 42, None)))]) callLst[:] = [] testme[:42] = "The Answer" self.assertCallStack([('__setitem__', (testme, slice(0, 42, None), "The Answer"))]) callLst[:] = [] del testme[:42] self.assertCallStack([('__delitem__', (testme, slice(0, 42, None)))]) # Restore the slice methods, or the tests will fail with regrtest -R. AllTests.__getslice__ = getslice AllTests.__setslice__ = setslice AllTests.__delslice__ = delslice def testUnaryOps(self): testme = AllTests() callLst[:] = [] -testme self.assertCallStack([('__neg__', (testme,))]) callLst[:] = [] +testme self.assertCallStack([('__pos__', (testme,))]) callLst[:] = [] abs(testme) self.assertCallStack([('__abs__', (testme,))]) callLst[:] = [] int(testme) self.assertCallStack([('__int__', (testme,))]) callLst[:] = [] long(testme) self.assertCallStack([('__long__', (testme,))]) callLst[:] = [] float(testme) self.assertCallStack([('__float__', (testme,))]) callLst[:] = [] oct(testme) self.assertCallStack([('__oct__', (testme,))]) callLst[:] = [] hex(testme) self.assertCallStack([('__hex__', (testme,))]) def testMisc(self): testme = AllTests() callLst[:] = [] hash(testme) self.assertCallStack([('__hash__', (testme,))]) callLst[:] = [] repr(testme) self.assertCallStack([('__repr__', (testme,))]) callLst[:] = [] str(testme) self.assertCallStack([('__str__', (testme,))]) callLst[:] = [] testme == 1 self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (testme, 1))]) callLst[:] = [] testme < 1 self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (testme, 1))]) callLst[:] = [] testme > 1 self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (testme, 1))]) callLst[:] = [] testme <> 1 # XXX kill this in py3k self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (testme, 1))]) callLst[:] = [] testme != 1 self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (testme, 1))]) callLst[:] = [] 1 == testme self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (1, testme))]) callLst[:] = [] 1 < testme self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (1, testme))]) callLst[:] = [] 1 > testme self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (1, testme))]) callLst[:] = [] 1 <> testme self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (1, testme))]) callLst[:] = [] 1 != testme self.assertCallStack([("__coerce__", (testme, 1)), ('__cmp__', (1, testme))]) def testGetSetAndDel(self): # Interfering tests class ExtraTests(AllTests): @trackCall def __getattr__(self, *args): return "SomeVal" @trackCall def __setattr__(self, *args): pass @trackCall def __delattr__(self, *args): pass testme = ExtraTests() callLst[:] = [] testme.spam self.assertCallStack([('__getattr__', (testme, "spam"))]) callLst[:] = [] testme.eggs = "spam, spam, spam and ham" self.assertCallStack([('__setattr__', (testme, "eggs", "spam, spam, spam and ham"))]) callLst[:] = [] del testme.cardinal self.assertCallStack([('__delattr__', (testme, "cardinal"))]) def testDel(self): x = [] class DelTest: def __del__(self): x.append("crab people, crab people") testme = DelTest() del testme import gc gc.collect() self.assertEquals(["crab people, crab people"], x) def testBadTypeReturned(self): # return values of some method are type-checked class BadTypeClass: def __int__(self): return None __float__ = __int__ __long__ = __int__ __str__ = __int__ __repr__ = __int__ __oct__ = __int__ __hex__ = __int__ for f in [int, float, long, str, repr, oct, hex]: self.assertRaises(TypeError, f, BadTypeClass()) def testMixIntsAndLongs(self): # mixing up ints and longs is okay class IntLongMixClass: @trackCall def __int__(self): return 42L @trackCall def __long__(self): return 64 mixIntAndLong = IntLongMixClass() callLst[:] = [] as_int = int(mixIntAndLong) self.assertEquals(type(as_int), long) self.assertEquals(as_int, 42L) self.assertCallStack([('__int__', (mixIntAndLong,))]) callLst[:] = [] as_long = long(mixIntAndLong) self.assertEquals(type(as_long), int) self.assertEquals(as_long, 64) self.assertCallStack([('__long__', (mixIntAndLong,))]) def testHashStuff(self): # Test correct errors from hash() on objects with comparisons but # no __hash__ class C0: pass hash(C0()) # This should work; the next two should raise TypeError class C1: def __cmp__(self, other): return 0 self.assertRaises(TypeError, hash, C1()) class C2: def __eq__(self, other): return 1 self.assertRaises(TypeError, hash, C2()) def testSFBug532646(self): # Test for SF bug 532646 class A: pass A.__call__ = A() a = A() try: a() # This should not segfault except RuntimeError: pass else: self.fail("Failed to raise RuntimeError") def testForExceptionsRaisedInInstanceGetattr2(self): # Tests for exceptions raised in instance_getattr2(). def booh(self): raise AttributeError("booh") class A: a = property(booh) try: A().a # Raised AttributeError: A instance has no attribute 'a' except AttributeError, x: if str(x) != "booh": self.fail("attribute error for A().a got masked: %s" % x) class E: __eq__ = property(booh) E() == E() # In debug mode, caused a C-level assert() to fail class I: __init__ = property(booh) try: # In debug mode, printed XXX undetected error and # raises AttributeError I() except AttributeError, x: pass else: self.fail("attribute error for I.__init__ got masked") def testHashComparisonOfMethods(self): # Test comparison and hash of methods class A: def __init__(self, x): self.x = x def f(self): pass def g(self): pass def __eq__(self, other): return self.x == other.x def __hash__(self): return self.x class B(A): pass a1 = A(1) a2 = A(2) self.assertEquals(a1.f, a1.f) self.assertNotEquals(a1.f, a2.f) self.assertNotEquals(a1.f, a1.g) self.assertEquals(a1.f, A(1).f) self.assertEquals(hash(a1.f), hash(a1.f)) self.assertEquals(hash(a1.f), hash(A(1).f)) self.assertNotEquals(A.f, a1.f) self.assertNotEquals(A.f, A.g) self.assertEquals(B.f, A.f) self.assertEquals(hash(B.f), hash(A.f)) # the following triggers a SystemError in 2.4 a = A(hash(A.f.im_func)^(-1)) hash(a.f) def test_main(): test_support.run_unittest(ClassTests) if __name__=='__main__': test_main()
strogo/bigcouch
refs/heads/master
couchjs/scons/scons-local-2.0.1/SCons/cpp.py
61
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/cpp.py 5134 2010/08/16 23:02:40 bdeegan" __doc__ = """ SCons C Pre-Processor module """ #TODO 2.3 and before has no sorted() import SCons.compat import os import re # # First "subsystem" of regular expressions that we set up: # # Stuff to turn the C preprocessor directives in a file's contents into # a list of tuples that we can process easily. # # A table of regular expressions that fetch the arguments from the rest of # a C preprocessor line. Different directives have different arguments # that we want to fetch, using the regular expressions to which the lists # of preprocessor directives map. cpp_lines_dict = { # Fetch the rest of a #if/#elif/#ifdef/#ifndef as one argument, # separated from the keyword by white space. ('if', 'elif', 'ifdef', 'ifndef',) : '\s+(.+)', # Fetch the rest of a #import/#include/#include_next line as one # argument, with white space optional. ('import', 'include', 'include_next',) : '\s*(.+)', # We don't care what comes after a #else or #endif line. ('else', 'endif',) : '', # Fetch three arguments from a #define line: # 1) The #defined keyword. # 2) The optional parentheses and arguments (if it's a function-like # macro, '' if it's not). # 3) The expansion value. ('define',) : '\s+([_A-Za-z][_A-Za-z0-9_]*)(\([^)]*\))?\s*(.*)', # Fetch the #undefed keyword from a #undef line. ('undef',) : '\s+([_A-Za-z][A-Za-z0-9_]*)', } # Create a table that maps each individual C preprocessor directive to # the corresponding compiled regular expression that fetches the arguments # we care about. Table = {} for op_list, expr in cpp_lines_dict.items(): e = re.compile(expr) for op in op_list: Table[op] = e del e del op del op_list # Create a list of the expressions we'll use to match all of the # preprocessor directives. These are the same as the directives # themselves *except* that we must use a negative lookahead assertion # when matching "if" so it doesn't match the "if" in "ifdef." override = { 'if' : 'if(?!def)', } l = [override.get(x, x) for x in Table.keys()] # Turn the list of expressions into one big honkin' regular expression # that will match all the preprocessor lines at once. This will return # a list of tuples, one for each preprocessor line. The preprocessor # directive will be the first element in each tuple, and the rest of # the line will be the second element. e = '^\s*#\s*(' + '|'.join(l) + ')(.*)$' # And last but not least, compile the expression. CPP_Expression = re.compile(e, re.M) # # Second "subsystem" of regular expressions that we set up: # # Stuff to translate a C preprocessor expression (as found on a #if or # #elif line) into an equivalent Python expression that we can eval(). # # A dictionary that maps the C representation of Boolean operators # to their Python equivalents. CPP_to_Python_Ops_Dict = { '!' : ' not ', '!=' : ' != ', '&&' : ' and ', '||' : ' or ', '?' : ' and ', ':' : ' or ', '\r' : '', } CPP_to_Python_Ops_Sub = lambda m: CPP_to_Python_Ops_Dict[m.group(0)] # We have to sort the keys by length so that longer expressions # come *before* shorter expressions--in particular, "!=" must # come before "!" in the alternation. Without this, the Python # re module, as late as version 2.2.2, empirically matches the # "!" in "!=" first, instead of finding the longest match. # What's up with that? l = sorted(CPP_to_Python_Ops_Dict.keys(), key=lambda a: len(a), reverse=True) # Turn the list of keys into one regular expression that will allow us # to substitute all of the operators at once. expr = '|'.join(map(re.escape, l)) # ...and compile the expression. CPP_to_Python_Ops_Expression = re.compile(expr) # A separate list of expressions to be evaluated and substituted # sequentially, not all at once. CPP_to_Python_Eval_List = [ ['defined\s+(\w+)', '"\\1" in __dict__'], ['defined\s*\((\w+)\)', '"\\1" in __dict__'], ['/\*.*\*/', ''], ['/\*.*', ''], ['//.*', ''], ['(0x[0-9A-Fa-f]*)[UL]+', '\\1'], ] # Replace the string representations of the regular expressions in the # list with compiled versions. for l in CPP_to_Python_Eval_List: l[0] = re.compile(l[0]) # Wrap up all of the above into a handy function. def CPP_to_Python(s): """ Converts a C pre-processor expression into an equivalent Python expression that can be evaluated. """ s = CPP_to_Python_Ops_Expression.sub(CPP_to_Python_Ops_Sub, s) for expr, repl in CPP_to_Python_Eval_List: s = expr.sub(repl, s) return s del expr del l del override class FunctionEvaluator(object): """ Handles delayed evaluation of a #define function call. """ def __init__(self, name, args, expansion): """ Squirrels away the arguments and expansion value of a #define macro function for later evaluation when we must actually expand a value that uses it. """ self.name = name self.args = function_arg_separator.split(args) try: expansion = expansion.split('##') except AttributeError: pass self.expansion = expansion def __call__(self, *values): """ Evaluates the expansion of a #define macro function called with the specified values. """ if len(self.args) != len(values): raise ValueError("Incorrect number of arguments to `%s'" % self.name) # Create a dictionary that maps the macro arguments to the # corresponding values in this "call." We'll use this when we # eval() the expansion so that arguments will get expanded to # the right values. locals = {} for k, v in zip(self.args, values): locals[k] = v parts = [] for s in self.expansion: if not s in self.args: s = repr(s) parts.append(s) statement = ' + '.join(parts) return eval(statement, globals(), locals) # Find line continuations. line_continuations = re.compile('\\\\\r?\n') # Search for a "function call" macro on an expansion. Returns the # two-tuple of the "function" name itself, and a string containing the # arguments within the call parentheses. function_name = re.compile('(\S+)\(([^)]*)\)') # Split a string containing comma-separated function call arguments into # the separate arguments. function_arg_separator = re.compile(',\s*') class PreProcessor(object): """ The main workhorse class for handling C pre-processing. """ def __init__(self, current=os.curdir, cpppath=(), dict={}, all=0): global Table cpppath = tuple(cpppath) self.searchpath = { '"' : (current,) + cpppath, '<' : cpppath + (current,), } # Initialize our C preprocessor namespace for tracking the # values of #defined keywords. We use this namespace to look # for keywords on #ifdef/#ifndef lines, and to eval() the # expressions on #if/#elif lines (after massaging them from C to # Python). self.cpp_namespace = dict.copy() self.cpp_namespace['__dict__'] = self.cpp_namespace if all: self.do_include = self.all_include # For efficiency, a dispatch table maps each C preprocessor # directive (#if, #define, etc.) to the method that should be # called when we see it. We accomodate state changes (#if, # #ifdef, #ifndef) by pushing the current dispatch table on a # stack and changing what method gets called for each relevant # directive we might see next at this level (#else, #elif). # #endif will simply pop the stack. d = { 'scons_current_file' : self.scons_current_file } for op in Table.keys(): d[op] = getattr(self, 'do_' + op) self.default_table = d # Controlling methods. def tupleize(self, contents): """ Turns the contents of a file into a list of easily-processed tuples describing the CPP lines in the file. The first element of each tuple is the line's preprocessor directive (#if, #include, #define, etc., minus the initial '#'). The remaining elements are specific to the type of directive, as pulled apart by the regular expression. """ global CPP_Expression, Table contents = line_continuations.sub('', contents) cpp_tuples = CPP_Expression.findall(contents) return [(m[0],) + Table[m[0]].match(m[1]).groups() for m in cpp_tuples] def __call__(self, file): """ Pre-processes a file. This is the main public entry point. """ self.current_file = file return self.process_contents(self.read_file(file), file) def process_contents(self, contents, fname=None): """ Pre-processes a file contents. This is the main internal entry point. """ self.stack = [] self.dispatch_table = self.default_table.copy() self.current_file = fname self.tuples = self.tupleize(contents) self.initialize_result(fname) while self.tuples: t = self.tuples.pop(0) # Uncomment to see the list of tuples being processed (e.g., # to validate the CPP lines are being translated correctly). #print t self.dispatch_table[t[0]](t) return self.finalize_result(fname) # Dispatch table stack manipulation methods. def save(self): """ Pushes the current dispatch table on the stack and re-initializes the current dispatch table to the default. """ self.stack.append(self.dispatch_table) self.dispatch_table = self.default_table.copy() def restore(self): """ Pops the previous dispatch table off the stack and makes it the current one. """ try: self.dispatch_table = self.stack.pop() except IndexError: pass # Utility methods. def do_nothing(self, t): """ Null method for when we explicitly want the action for a specific preprocessor directive to do nothing. """ pass def scons_current_file(self, t): self.current_file = t[1] def eval_expression(self, t): """ Evaluates a C preprocessor expression. This is done by converting it to a Python equivalent and eval()ing it in the C preprocessor namespace we use to track #define values. """ t = CPP_to_Python(' '.join(t[1:])) try: return eval(t, self.cpp_namespace) except (NameError, TypeError): return 0 def initialize_result(self, fname): self.result = [fname] def finalize_result(self, fname): return self.result[1:] def find_include_file(self, t): """ Finds the #include file for a given preprocessor tuple. """ fname = t[2] for d in self.searchpath[t[1]]: if d == os.curdir: f = fname else: f = os.path.join(d, fname) if os.path.isfile(f): return f return None def read_file(self, file): return open(file).read() # Start and stop processing include lines. def start_handling_includes(self, t=None): """ Causes the PreProcessor object to start processing #import, #include and #include_next lines. This method will be called when a #if, #ifdef, #ifndef or #elif evaluates True, or when we reach the #else in a #if, #ifdef, #ifndef or #elif block where a condition already evaluated False. """ d = self.dispatch_table d['import'] = self.do_import d['include'] = self.do_include d['include_next'] = self.do_include def stop_handling_includes(self, t=None): """ Causes the PreProcessor object to stop processing #import, #include and #include_next lines. This method will be called when a #if, #ifdef, #ifndef or #elif evaluates False, or when we reach the #else in a #if, #ifdef, #ifndef or #elif block where a condition already evaluated True. """ d = self.dispatch_table d['import'] = self.do_nothing d['include'] = self.do_nothing d['include_next'] = self.do_nothing # Default methods for handling all of the preprocessor directives. # (Note that what actually gets called for a given directive at any # point in time is really controlled by the dispatch_table.) def _do_if_else_condition(self, condition): """ Common logic for evaluating the conditions on #if, #ifdef and #ifndef lines. """ self.save() d = self.dispatch_table if condition: self.start_handling_includes() d['elif'] = self.stop_handling_includes d['else'] = self.stop_handling_includes else: self.stop_handling_includes() d['elif'] = self.do_elif d['else'] = self.start_handling_includes def do_ifdef(self, t): """ Default handling of a #ifdef line. """ self._do_if_else_condition(t[1] in self.cpp_namespace) def do_ifndef(self, t): """ Default handling of a #ifndef line. """ self._do_if_else_condition(t[1] not in self.cpp_namespace) def do_if(self, t): """ Default handling of a #if line. """ self._do_if_else_condition(self.eval_expression(t)) def do_elif(self, t): """ Default handling of a #elif line. """ d = self.dispatch_table if self.eval_expression(t): self.start_handling_includes() d['elif'] = self.stop_handling_includes d['else'] = self.stop_handling_includes def do_else(self, t): """ Default handling of a #else line. """ pass def do_endif(self, t): """ Default handling of a #endif line. """ self.restore() def do_define(self, t): """ Default handling of a #define line. """ _, name, args, expansion = t try: expansion = int(expansion) except (TypeError, ValueError): pass if args: evaluator = FunctionEvaluator(name, args[1:-1], expansion) self.cpp_namespace[name] = evaluator else: self.cpp_namespace[name] = expansion def do_undef(self, t): """ Default handling of a #undef line. """ try: del self.cpp_namespace[t[1]] except KeyError: pass def do_import(self, t): """ Default handling of a #import line. """ # XXX finish this -- maybe borrow/share logic from do_include()...? pass def do_include(self, t): """ Default handling of a #include line. """ t = self.resolve_include(t) include_file = self.find_include_file(t) if include_file: #print "include_file =", include_file self.result.append(include_file) contents = self.read_file(include_file) new_tuples = [('scons_current_file', include_file)] + \ self.tupleize(contents) + \ [('scons_current_file', self.current_file)] self.tuples[:] = new_tuples + self.tuples # Date: Tue, 22 Nov 2005 20:26:09 -0500 # From: Stefan Seefeld <seefeld@sympatico.ca> # # By the way, #include_next is not the same as #include. The difference # being that #include_next starts its search in the path following the # path that let to the including file. In other words, if your system # include paths are ['/foo', '/bar'], and you are looking at a header # '/foo/baz.h', it might issue an '#include_next <baz.h>' which would # correctly resolve to '/bar/baz.h' (if that exists), but *not* see # '/foo/baz.h' again. See http://www.delorie.com/gnu/docs/gcc/cpp_11.html # for more reasoning. # # I have no idea in what context 'import' might be used. # XXX is #include_next really the same as #include ? do_include_next = do_include # Utility methods for handling resolution of include files. def resolve_include(self, t): """Resolve a tuple-ized #include line. This handles recursive expansion of values without "" or <> surrounding the name until an initial " or < is found, to handle #include FILE where FILE is a #define somewhere else. """ s = t[1] while not s[0] in '<"': #print "s =", s try: s = self.cpp_namespace[s] except KeyError: m = function_name.search(s) s = self.cpp_namespace[m.group(1)] if callable(s): args = function_arg_separator.split(m.group(2)) s = s(*args) if not s: return None return (t[0], s[0], s[1:-1]) def all_include(self, t): """ """ self.result.append(self.resolve_include(t)) class DumbPreProcessor(PreProcessor): """A preprocessor that ignores all #if/#elif/#else/#endif directives and just reports back *all* of the #include files (like the classic SCons scanner did). This is functionally equivalent to using a regular expression to find all of the #include lines, only slower. It exists mainly as an example of how the main PreProcessor class can be sub-classed to tailor its behavior. """ def __init__(self, *args, **kw): PreProcessor.__init__(self, *args, **kw) d = self.default_table for func in ['if', 'elif', 'else', 'endif', 'ifdef', 'ifndef']: d[func] = d[func] = self.do_nothing del __revision__ # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
bretlowery/snakr
refs/heads/master
lib/django/conf/locale/ro/formats.py
619
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j F Y, H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y, H:i' # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # DATE_INPUT_FORMATS = # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' # NUMBER_GROUPING =
Venturi/cms
refs/heads/master
env/lib/python2.7/site-packages/django/core/checks/__init__.py
36
# -*- coding: utf-8 -*- from __future__ import unicode_literals from .messages import (CheckMessage, Debug, Info, Warning, Error, Critical, DEBUG, INFO, WARNING, ERROR, CRITICAL) from .registry import register, run_checks, tag_exists, Tags # Import these to force registration of checks import django.core.checks.compatibility.django_1_7_0 # NOQA import django.core.checks.compatibility.django_1_8_0 # NOQA import django.core.checks.model_checks # NOQA import django.core.checks.security.base # NOQA import django.core.checks.security.csrf # NOQA import django.core.checks.security.sessions # NOQA __all__ = [ 'CheckMessage', 'Debug', 'Info', 'Warning', 'Error', 'Critical', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'register', 'run_checks', 'tag_exists', 'Tags', ]
albertoferna/compmech
refs/heads/master
compmech/aero/__init__.py
1
r""" ============================================ Aeroelasticity Module (:mod:`compmech.aero`) ============================================ .. currentmodule:: compmech.aero This module contains semi-analytical models for aeroelastic analyses such as: - Piston Theory applied to Composite Plates (:mod:`compmech.aero.pistonplate`) """ from pistonplate import AeroPistonPlate from pistonstiffpanel import AeroPistonStiffPanel
rawdlite/mopidy
refs/heads/develop
tests/backend/__init__.py
190
from __future__ import absolute_import, unicode_literals
WinterNis/sqlalchemy
refs/heads/master
lib/sqlalchemy/sql/schema.py
42
# sql/schema.py # Copyright (C) 2005-2015 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 """The schema module provides the building blocks for database metadata. Each element within this module describes a database entity which can be created and dropped, or is otherwise part of such an entity. Examples include tables, columns, sequences, and indexes. All entities are subclasses of :class:`~sqlalchemy.schema.SchemaItem`, and as defined in this module they are intended to be agnostic of any vendor-specific constructs. A collection of entities are grouped into a unit called :class:`~sqlalchemy.schema.MetaData`. MetaData serves as a logical grouping of schema elements, and can also be associated with an actual database connection such that operations involving the contained elements can contact the database as needed. Two of the elements here also build upon their "syntactic" counterparts, which are defined in :class:`~sqlalchemy.sql.expression.`, specifically :class:`~sqlalchemy.schema.Table` and :class:`~sqlalchemy.schema.Column`. Since these objects are part of the SQL expression language, they are usable as components in SQL expressions. """ from __future__ import absolute_import import inspect from .. import exc, util, event, inspection from .base import SchemaEventTarget, DialectKWArgs from . import visitors from . import type_api from .base import _bind_or_error, ColumnCollection from .elements import ClauseElement, ColumnClause, _truncated_label, \ _as_truncated, TextClause, _literal_as_text,\ ColumnElement, _find_columns, quoted_name from .selectable import TableClause import collections import sqlalchemy from . import ddl import types RETAIN_SCHEMA = util.symbol('retain_schema') def _get_table_key(name, schema): if schema is None: return name else: return schema + "." + name @inspection._self_inspects class SchemaItem(SchemaEventTarget, visitors.Visitable): """Base class for items that define a database schema.""" __visit_name__ = 'schema_item' def _execute_on_connection(self, connection, multiparams, params): return connection._execute_default(self, multiparams, params) def _init_items(self, *args): """Initialize the list of child items for this SchemaItem.""" for item in args: if item is not None: item._set_parent_with_dispatch(self) def get_children(self, **kwargs): """used to allow SchemaVisitor access""" return [] def __repr__(self): return util.generic_repr(self, omit_kwarg=['info']) @property @util.deprecated('0.9', 'Use ``<obj>.name.quote``') def quote(self): """Return the value of the ``quote`` flag passed to this schema object, for those schema items which have a ``name`` field. """ return self.name.quote @util.memoized_property def info(self): """Info dictionary associated with the object, allowing user-defined data to be associated with this :class:`.SchemaItem`. The dictionary is automatically generated when first accessed. It can also be specified in the constructor of some objects, such as :class:`.Table` and :class:`.Column`. """ return {} def _schema_item_copy(self, schema_item): if 'info' in self.__dict__: schema_item.info = self.info.copy() schema_item.dispatch._update(self.dispatch) return schema_item class Table(DialectKWArgs, SchemaItem, TableClause): """Represent a table in a database. e.g.:: mytable = Table("mytable", metadata, Column('mytable_id', Integer, primary_key=True), Column('value', String(50)) ) The :class:`.Table` object constructs a unique instance of itself based on its name and optional schema name within the given :class:`.MetaData` object. Calling the :class:`.Table` constructor with the same name and same :class:`.MetaData` argument a second time will return the *same* :class:`.Table` object - in this way the :class:`.Table` constructor acts as a registry function. .. seealso:: :ref:`metadata_describing` - Introduction to database metadata Constructor arguments are as follows: :param name: The name of this table as represented in the database. The table name, along with the value of the ``schema`` parameter, forms a key which uniquely identifies this :class:`.Table` within the owning :class:`.MetaData` collection. Additional calls to :class:`.Table` with the same name, metadata, and schema name will return the same :class:`.Table` object. Names which contain no upper case characters will be treated as case insensitive names, and will not be quoted unless they are a reserved word or contain special characters. A name with any number of upper case characters is considered to be case sensitive, and will be sent as quoted. To enable unconditional quoting for the table name, specify the flag ``quote=True`` to the constructor, or use the :class:`.quoted_name` construct to specify the name. :param metadata: a :class:`.MetaData` object which will contain this table. The metadata is used as a point of association of this table with other tables which are referenced via foreign key. It also may be used to associate this table with a particular :class:`.Connectable`. :param \*args: Additional positional arguments are used primarily to add the list of :class:`.Column` objects contained within this table. Similar to the style of a CREATE TABLE statement, other :class:`.SchemaItem` constructs may be added here, including :class:`.PrimaryKeyConstraint`, and :class:`.ForeignKeyConstraint`. :param autoload: Defaults to False, unless :paramref:`.Table.autoload_with` is set in which case it defaults to True; :class:`.Column` objects for this table should be reflected from the database, possibly augmenting or replacing existing :class:`.Column` objects that were expicitly specified. .. versionchanged:: 1.0.0 setting the :paramref:`.Table.autoload_with` parameter implies that :paramref:`.Table.autoload` will default to True. .. seealso:: :ref:`metadata_reflection_toplevel` :param autoload_replace: Defaults to ``True``; when using :paramref:`.Table.autoload` in conjunction with :paramref:`.Table.extend_existing`, indicates that :class:`.Column` objects present in the already-existing :class:`.Table` object should be replaced with columns of the same name retrieved from the autoload process. When ``False``, columns already present under existing names will be omitted from the reflection process. Note that this setting does not impact :class:`.Column` objects specified programmatically within the call to :class:`.Table` that also is autoloading; those :class:`.Column` objects will always replace existing columns of the same name when :paramref:`.Table.extend_existing` is ``True``. .. versionadded:: 0.7.5 .. seealso:: :paramref:`.Table.autoload` :paramref:`.Table.extend_existing` :param autoload_with: An :class:`.Engine` or :class:`.Connection` object with which this :class:`.Table` object will be reflected; when set to a non-None value, it implies that :paramref:`.Table.autoload` is ``True``. If left unset, but :paramref:`.Table.autoload` is explicitly set to ``True``, an autoload operation will attempt to proceed by locating an :class:`.Engine` or :class:`.Connection` bound to the underlying :class:`.MetaData` object. .. seealso:: :paramref:`.Table.autoload` :param extend_existing: When ``True``, indicates that if this :class:`.Table` is already present in the given :class:`.MetaData`, apply further arguments within the constructor to the existing :class:`.Table`. If :paramref:`.Table.extend_existing` or :paramref:`.Table.keep_existing` are not set, and the given name of the new :class:`.Table` refers to a :class:`.Table` that is already present in the target :class:`.MetaData` collection, and this :class:`.Table` specifies additional columns or other constructs or flags that modify the table's state, an error is raised. The purpose of these two mutually-exclusive flags is to specify what action should be taken when a :class:`.Table` is specified that matches an existing :class:`.Table`, yet specifies additional constructs. :paramref:`.Table.extend_existing` will also work in conjunction with :paramref:`.Table.autoload` to run a new reflection operation against the database, even if a :class:`.Table` of the same name is already present in the target :class:`.MetaData`; newly reflected :class:`.Column` objects and other options will be added into the state of the :class:`.Table`, potentially overwriting existing columns and options of the same name. .. versionchanged:: 0.7.4 :paramref:`.Table.extend_existing` will invoke a new reflection operation when combined with :paramref:`.Table.autoload` set to True. As is always the case with :paramref:`.Table.autoload`, :class:`.Column` objects can be specified in the same :class:`.Table` constructor, which will take precedence. Below, the existing table ``mytable`` will be augmented with :class:`.Column` objects both reflected from the database, as well as the given :class:`.Column` named "y":: Table("mytable", metadata, Column('y', Integer), extend_existing=True, autoload=True, autoload_with=engine ) .. seealso:: :paramref:`.Table.autoload` :paramref:`.Table.autoload_replace` :paramref:`.Table.keep_existing` :param implicit_returning: True by default - indicates that RETURNING can be used by default to fetch newly inserted primary key values, for backends which support this. Note that create_engine() also provides an implicit_returning flag. :param include_columns: A list of strings indicating a subset of columns to be loaded via the ``autoload`` operation; table columns who aren't present in this list will not be represented on the resulting ``Table`` object. Defaults to ``None`` which indicates all columns should be reflected. :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. :param keep_existing: When ``True``, indicates that if this Table is already present in the given :class:`.MetaData`, ignore further arguments within the constructor to the existing :class:`.Table`, and return the :class:`.Table` object as originally created. This is to allow a function that wishes to define a new :class:`.Table` on first call, but on subsequent calls will return the same :class:`.Table`, without any of the declarations (particularly constraints) being applied a second time. If :paramref:`.Table.extend_existing` or :paramref:`.Table.keep_existing` are not set, and the given name of the new :class:`.Table` refers to a :class:`.Table` that is already present in the target :class:`.MetaData` collection, and this :class:`.Table` specifies additional columns or other constructs or flags that modify the table's state, an error is raised. The purpose of these two mutually-exclusive flags is to specify what action should be taken when a :class:`.Table` is specified that matches an existing :class:`.Table`, yet specifies additional constructs. .. seealso:: :paramref:`.Table.extend_existing` :param listeners: A list of tuples of the form ``(<eventname>, <fn>)`` which will be passed to :func:`.event.listen` upon construction. This alternate hook to :func:`.event.listen` allows the establishment of a listener function specific to this :class:`.Table` before the "autoload" process begins. Particularly useful for the :meth:`.DDLEvents.column_reflect` event:: def listen_for_reflect(table, column_info): "handle the column reflection event" # ... t = Table( 'sometable', autoload=True, listeners=[ ('column_reflect', listen_for_reflect) ]) :param mustexist: When ``True``, indicates that this Table must already be present in the given :class:`.MetaData` collection, else an exception is raised. :param prefixes: A list of strings to insert after CREATE in the CREATE TABLE statement. They will be separated by spaces. :param quote: Force quoting of this table's name on or off, corresponding to ``True`` or ``False``. When left at its default of ``None``, the column identifier will be quoted according to whether the name is case sensitive (identifiers with at least one upper case character are treated as case sensitive), or if it's a reserved word. This flag is only needed to force quoting of a reserved word which is not known by the SQLAlchemy dialect. :param quote_schema: same as 'quote' but applies to the schema identifier. :param schema: The schema name for this table, which is required if the table resides in a schema other than the default selected schema for the engine's database connection. Defaults to ``None``. The quoting rules for the schema name are the same as those for the ``name`` parameter, in that quoting is applied for reserved words or case-sensitive names; to enable unconditional quoting for the schema name, specify the flag ``quote_schema=True`` to the constructor, or use the :class:`.quoted_name` construct to specify the name. :param useexisting: Deprecated. Use :paramref:`.Table.extend_existing`. :param \**kw: Additional keyword arguments not mentioned above are dialect specific, and passed in the form ``<dialectname>_<argname>``. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. """ __visit_name__ = 'table' def __new__(cls, *args, **kw): if not args: # python3k pickle seems to call this return object.__new__(cls) try: name, metadata, args = args[0], args[1], args[2:] except IndexError: raise TypeError("Table() takes at least two arguments") schema = kw.get('schema', None) if schema is None: schema = metadata.schema keep_existing = kw.pop('keep_existing', False) extend_existing = kw.pop('extend_existing', False) if 'useexisting' in kw: msg = "useexisting is deprecated. Use extend_existing." util.warn_deprecated(msg) if extend_existing: msg = "useexisting is synonymous with extend_existing." raise exc.ArgumentError(msg) extend_existing = kw.pop('useexisting', False) if keep_existing and extend_existing: msg = "keep_existing and extend_existing are mutually exclusive." raise exc.ArgumentError(msg) mustexist = kw.pop('mustexist', False) key = _get_table_key(name, schema) if key in metadata.tables: if not keep_existing and not extend_existing and bool(args): raise exc.InvalidRequestError( "Table '%s' is already defined for this MetaData " "instance. Specify 'extend_existing=True' " "to redefine " "options and columns on an " "existing Table object." % key) table = metadata.tables[key] if extend_existing: table._init_existing(*args, **kw) return table else: if mustexist: raise exc.InvalidRequestError( "Table '%s' not defined" % (key)) table = object.__new__(cls) table.dispatch.before_parent_attach(table, metadata) metadata._add_table(name, schema, table) try: table._init(name, metadata, *args, **kw) table.dispatch.after_parent_attach(table, metadata) return table except: with util.safe_reraise(): metadata._remove_table(name, schema) @property @util.deprecated('0.9', 'Use ``table.schema.quote``') def quote_schema(self): """Return the value of the ``quote_schema`` flag passed to this :class:`.Table`. """ return self.schema.quote def __init__(self, *args, **kw): """Constructor for :class:`~.schema.Table`. This method is a no-op. See the top-level documentation for :class:`~.schema.Table` for constructor arguments. """ # __init__ is overridden to prevent __new__ from # calling the superclass constructor. def _init(self, name, metadata, *args, **kwargs): super(Table, self).__init__( quoted_name(name, kwargs.pop('quote', None))) self.metadata = metadata self.schema = kwargs.pop('schema', None) if self.schema is None: self.schema = metadata.schema else: quote_schema = kwargs.pop('quote_schema', None) self.schema = quoted_name(self.schema, quote_schema) self.indexes = set() self.constraints = set() self._columns = ColumnCollection() PrimaryKeyConstraint()._set_parent_with_dispatch(self) self.foreign_keys = set() self._extra_dependencies = set() if self.schema is not None: self.fullname = "%s.%s" % (self.schema, self.name) else: self.fullname = self.name autoload_with = kwargs.pop('autoload_with', None) autoload = kwargs.pop('autoload', autoload_with is not None) # this argument is only used with _init_existing() kwargs.pop('autoload_replace', True) include_columns = kwargs.pop('include_columns', None) self.implicit_returning = kwargs.pop('implicit_returning', True) if 'info' in kwargs: self.info = kwargs.pop('info') if 'listeners' in kwargs: listeners = kwargs.pop('listeners') for evt, fn in listeners: event.listen(self, evt, fn) self._prefixes = kwargs.pop('prefixes', []) self._extra_kwargs(**kwargs) # load column definitions from the database if 'autoload' is defined # we do it after the table is in the singleton dictionary to support # circular foreign keys if autoload: self._autoload(metadata, autoload_with, include_columns) # initialize all the column, etc. objects. done after reflection to # allow user-overrides self._init_items(*args) def _autoload(self, metadata, autoload_with, include_columns, exclude_columns=()): if autoload_with: autoload_with.run_callable( autoload_with.dialect.reflecttable, self, include_columns, exclude_columns ) else: bind = _bind_or_error( metadata, msg="No engine is bound to this Table's MetaData. " "Pass an engine to the Table via " "autoload_with=<someengine>, " "or associate the MetaData with an engine via " "metadata.bind=<someengine>") bind.run_callable( bind.dialect.reflecttable, self, include_columns, exclude_columns ) @property def _sorted_constraints(self): """Return the set of constraints as a list, sorted by creation order. """ return sorted(self.constraints, key=lambda c: c._creation_order) @property def foreign_key_constraints(self): """:class:`.ForeignKeyConstraint` objects referred to by this :class:`.Table`. This list is produced from the collection of :class:`.ForeignKey` objects currently associated. .. versionadded:: 1.0.0 """ return set(fkc.constraint for fkc in self.foreign_keys) def _init_existing(self, *args, **kwargs): autoload_with = kwargs.pop('autoload_with', None) autoload = kwargs.pop('autoload', autoload_with is not None) autoload_replace = kwargs.pop('autoload_replace', True) schema = kwargs.pop('schema', None) if schema and schema != self.schema: raise exc.ArgumentError( "Can't change schema of existing table from '%s' to '%s'", (self.schema, schema)) include_columns = kwargs.pop('include_columns', None) if include_columns is not None: for c in self.c: if c.name not in include_columns: self._columns.remove(c) for key in ('quote', 'quote_schema'): if key in kwargs: raise exc.ArgumentError( "Can't redefine 'quote' or 'quote_schema' arguments") if 'info' in kwargs: self.info = kwargs.pop('info') if autoload: if not autoload_replace: exclude_columns = [c.name for c in self.c] else: exclude_columns = () self._autoload( self.metadata, autoload_with, include_columns, exclude_columns) self._extra_kwargs(**kwargs) self._init_items(*args) def _extra_kwargs(self, **kwargs): self._validate_dialect_kwargs(kwargs) def _init_collections(self): pass @util.memoized_property def _autoincrement_column(self): for col in self.primary_key: if (col.autoincrement and col.type._type_affinity is not None and issubclass(col.type._type_affinity, type_api.INTEGERTYPE._type_affinity) and (not col.foreign_keys or col.autoincrement == 'ignore_fk') and isinstance(col.default, (type(None), Sequence)) and (col.server_default is None or col.server_default.reflected)): return col @property def key(self): """Return the 'key' for this :class:`.Table`. This value is used as the dictionary key within the :attr:`.MetaData.tables` collection. It is typically the same as that of :attr:`.Table.name` for a table with no :attr:`.Table.schema` set; otherwise it is typically of the form ``schemaname.tablename``. """ return _get_table_key(self.name, self.schema) def __repr__(self): return "Table(%s)" % ', '.join( [repr(self.name)] + [repr(self.metadata)] + [repr(x) for x in self.columns] + ["%s=%s" % (k, repr(getattr(self, k))) for k in ['schema']]) def __str__(self): return _get_table_key(self.description, self.schema) @property def bind(self): """Return the connectable associated with this Table.""" return self.metadata and self.metadata.bind or None def add_is_dependent_on(self, table): """Add a 'dependency' for this Table. This is another Table object which must be created first before this one can, or dropped after this one. Usually, dependencies between tables are determined via ForeignKey objects. However, for other situations that create dependencies outside of foreign keys (rules, inheriting), this method can manually establish such a link. """ self._extra_dependencies.add(table) def append_column(self, column): """Append a :class:`~.schema.Column` to this :class:`~.schema.Table`. The "key" of the newly added :class:`~.schema.Column`, i.e. the value of its ``.key`` attribute, will then be available in the ``.c`` collection of this :class:`~.schema.Table`, and the column definition will be included in any CREATE TABLE, SELECT, UPDATE, etc. statements generated from this :class:`~.schema.Table` construct. Note that this does **not** change the definition of the table as it exists within any underlying database, assuming that table has already been created in the database. Relational databases support the addition of columns to existing tables using the SQL ALTER command, which would need to be emitted for an already-existing table that doesn't contain the newly added column. """ column._set_parent_with_dispatch(self) def append_constraint(self, constraint): """Append a :class:`~.schema.Constraint` to this :class:`~.schema.Table`. This has the effect of the constraint being included in any future CREATE TABLE statement, assuming specific DDL creation events have not been associated with the given :class:`~.schema.Constraint` object. Note that this does **not** produce the constraint within the relational database automatically, for a table that already exists in the database. To add a constraint to an existing relational database table, the SQL ALTER command must be used. SQLAlchemy also provides the :class:`.AddConstraint` construct which can produce this SQL when invoked as an executable clause. """ constraint._set_parent_with_dispatch(self) def append_ddl_listener(self, event_name, listener): """Append a DDL event listener to this ``Table``. .. deprecated:: 0.7 See :class:`.DDLEvents`. """ def adapt_listener(target, connection, **kw): listener(event_name, target, connection) event.listen(self, "" + event_name.replace('-', '_'), adapt_listener) def _set_parent(self, metadata): metadata._add_table(self.name, self.schema, self) self.metadata = metadata def get_children(self, column_collections=True, schema_visitor=False, **kw): if not schema_visitor: return TableClause.get_children( self, column_collections=column_collections, **kw) else: if column_collections: return list(self.columns) else: return [] def exists(self, bind=None): """Return True if this table exists.""" if bind is None: bind = _bind_or_error(self) return bind.run_callable(bind.dialect.has_table, self.name, schema=self.schema) def create(self, bind=None, checkfirst=False): """Issue a ``CREATE`` statement for this :class:`.Table`, using the given :class:`.Connectable` for connectivity. .. seealso:: :meth:`.MetaData.create_all`. """ if bind is None: bind = _bind_or_error(self) bind._run_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst) def drop(self, bind=None, checkfirst=False): """Issue a ``DROP`` statement for this :class:`.Table`, using the given :class:`.Connectable` for connectivity. .. seealso:: :meth:`.MetaData.drop_all`. """ if bind is None: bind = _bind_or_error(self) bind._run_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst) def tometadata(self, metadata, schema=RETAIN_SCHEMA, referred_schema_fn=None, name=None): """Return a copy of this :class:`.Table` associated with a different :class:`.MetaData`. E.g.:: m1 = MetaData() user = Table('user', m1, Column('id', Integer, priamry_key=True)) m2 = MetaData() user_copy = user.tometadata(m2) :param metadata: Target :class:`.MetaData` object, into which the new :class:`.Table` object will be created. :param schema: optional string name indicating the target schema. Defaults to the special symbol :attr:`.RETAIN_SCHEMA` which indicates that no change to the schema name should be made in the new :class:`.Table`. If set to a string name, the new :class:`.Table` will have this new name as the ``.schema``. If set to ``None``, the schema will be set to that of the schema set on the target :class:`.MetaData`, which is typically ``None`` as well, unless set explicitly:: m2 = MetaData(schema='newschema') # user_copy_one will have "newschema" as the schema name user_copy_one = user.tometadata(m2, schema=None) m3 = MetaData() # schema defaults to None # user_copy_two will have None as the schema name user_copy_two = user.tometadata(m3, schema=None) :param referred_schema_fn: optional callable which can be supplied in order to provide for the schema name that should be assigned to the referenced table of a :class:`.ForeignKeyConstraint`. The callable accepts this parent :class:`.Table`, the target schema that we are changing to, the :class:`.ForeignKeyConstraint` object, and the existing "target schema" of that constraint. The function should return the string schema name that should be applied. E.g.:: def referred_schema_fn(table, to_schema, constraint, referred_schema): if referred_schema == 'base_tables': return referred_schema else: return to_schema new_table = table.tometadata(m2, schema="alt_schema", referred_schema_fn=referred_schema_fn) .. versionadded:: 0.9.2 :param name: optional string name indicating the target table name. If not specified or None, the table name is retained. This allows a :class:`.Table` to be copied to the same :class:`.MetaData` target with a new name. .. versionadded:: 1.0.0 """ if name is None: name = self.name if schema is RETAIN_SCHEMA: schema = self.schema elif schema is None: schema = metadata.schema key = _get_table_key(name, schema) if key in metadata.tables: util.warn("Table '%s' already exists within the given " "MetaData - not copying." % self.description) return metadata.tables[key] args = [] for c in self.columns: args.append(c.copy(schema=schema)) table = Table( name, metadata, schema=schema, *args, **self.kwargs ) for c in self.constraints: if isinstance(c, ForeignKeyConstraint): referred_schema = c._referred_schema if referred_schema_fn: fk_constraint_schema = referred_schema_fn( self, schema, c, referred_schema) else: fk_constraint_schema = ( schema if referred_schema == self.schema else None) table.append_constraint( c.copy(schema=fk_constraint_schema, target_table=table)) elif not c._type_bound: table.append_constraint( c.copy(schema=schema, target_table=table)) for index in self.indexes: # skip indexes that would be generated # by the 'index' flag on Column if len(index.columns) == 1 and \ list(index.columns)[0].index: continue Index(index.name, unique=index.unique, *[table.c[col] for col in index.columns.keys()], **index.kwargs) return self._schema_item_copy(table) class Column(SchemaItem, ColumnClause): """Represents a column in a database table.""" __visit_name__ = 'column' def __init__(self, *args, **kwargs): """ Construct a new ``Column`` object. :param name: The name of this column as represented in the database. This argument may be the first positional argument, or specified via keyword. Names which contain no upper case characters will be treated as case insensitive names, and will not be quoted unless they are a reserved word. Names with any number of upper case characters will be quoted and sent exactly. Note that this behavior applies even for databases which standardize upper case names as case insensitive such as Oracle. The name field may be omitted at construction time and applied later, at any time before the Column is associated with a :class:`.Table`. This is to support convenient usage within the :mod:`~sqlalchemy.ext.declarative` extension. :param type\_: The column's type, indicated using an instance which subclasses :class:`~sqlalchemy.types.TypeEngine`. If no arguments are required for the type, the class of the type can be sent as well, e.g.:: # use a type with arguments Column('data', String(50)) # use no arguments Column('level', Integer) The ``type`` argument may be the second positional argument or specified by keyword. If the ``type`` is ``None`` or is omitted, it will first default to the special type :class:`.NullType`. If and when this :class:`.Column` is made to refer to another column using :class:`.ForeignKey` and/or :class:`.ForeignKeyConstraint`, the type of the remote-referenced column will be copied to this column as well, at the moment that the foreign key is resolved against that remote :class:`.Column` object. .. versionchanged:: 0.9.0 Support for propagation of type to a :class:`.Column` from its :class:`.ForeignKey` object has been improved and should be more reliable and timely. :param \*args: Additional positional arguments include various :class:`.SchemaItem` derived constructs which will be applied as options to the column. These include instances of :class:`.Constraint`, :class:`.ForeignKey`, :class:`.ColumnDefault`, and :class:`.Sequence`. In some cases an equivalent keyword argument is available such as ``server_default``, ``default`` and ``unique``. :param autoincrement: This flag may be set to ``False`` to indicate an integer primary key column that should not be considered to be the "autoincrement" column, that is the integer primary key column which generates values implicitly upon INSERT and whose value is usually returned via the DBAPI cursor.lastrowid attribute. It defaults to ``True`` to satisfy the common use case of a table with a single integer primary key column. If the table has a composite primary key consisting of more than one integer column, set this flag to True only on the column that should be considered "autoincrement". The setting *only* has an effect for columns which are: * Integer derived (i.e. INT, SMALLINT, BIGINT). * Part of the primary key * Not refering to another column via :class:`.ForeignKey`, unless the value is specified as ``'ignore_fk'``:: # turn on autoincrement for this column despite # the ForeignKey() Column('id', ForeignKey('other.id'), primary_key=True, autoincrement='ignore_fk') It is typically not desirable to have "autoincrement" enabled on such a column as its value intends to mirror that of a primary key column elsewhere. * have no server side or client side defaults (with the exception of Postgresql SERIAL). The setting has these two effects on columns that meet the above criteria: * DDL issued for the column will include database-specific keywords intended to signify this column as an "autoincrement" column, such as AUTO INCREMENT on MySQL, SERIAL on Postgresql, and IDENTITY on MS-SQL. It does *not* issue AUTOINCREMENT for SQLite since this is a special SQLite flag that is not required for autoincrementing behavior. .. seealso:: :ref:`sqlite_autoincrement` * The column will be considered to be available as cursor.lastrowid or equivalent, for those dialects which "post fetch" newly inserted identifiers after a row has been inserted (SQLite, MySQL, MS-SQL). It does not have any effect in this regard for databases that use sequences to generate primary key identifiers (i.e. Firebird, Postgresql, Oracle). .. versionchanged:: 0.7.4 ``autoincrement`` accepts a special value ``'ignore_fk'`` to indicate that autoincrementing status regardless of foreign key references. This applies to certain composite foreign key setups, such as the one demonstrated in the ORM documentation at :ref:`post_update`. :param default: A scalar, Python callable, or :class:`.ColumnElement` expression representing the *default value* for this column, which will be invoked upon insert if this column is otherwise not specified in the VALUES clause of the insert. This is a shortcut to using :class:`.ColumnDefault` as a positional argument; see that class for full detail on the structure of the argument. Contrast this argument to ``server_default`` which creates a default generator on the database side. :param doc: optional String that can be used by the ORM or similar to document attributes. This attribute does not render SQL comments (a future attribute 'comment' will achieve that). :param key: An optional string identifier which will identify this ``Column`` object on the :class:`.Table`. When a key is provided, this is the only identifier referencing the ``Column`` within the application, including ORM attribute mapping; the ``name`` field is used only when rendering SQL. :param index: When ``True``, indicates that the column is indexed. This is a shortcut for using a :class:`.Index` construct on the table. To specify indexes with explicit names or indexes that contain multiple columns, use the :class:`.Index` construct instead. :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. :param nullable: If set to the default of ``True``, indicates the column will be rendered as allowing NULL, else it's rendered as NOT NULL. This parameter is only used when issuing CREATE TABLE statements. :param onupdate: A scalar, Python callable, or :class:`~sqlalchemy.sql.expression.ClauseElement` representing a default value to be applied to the column within UPDATE statements, which wil be invoked upon update if this column is not present in the SET clause of the update. This is a shortcut to using :class:`.ColumnDefault` as a positional argument with ``for_update=True``. :param primary_key: If ``True``, marks this column as a primary key column. Multiple columns can have this flag set to specify composite primary keys. As an alternative, the primary key of a :class:`.Table` can be specified via an explicit :class:`.PrimaryKeyConstraint` object. :param server_default: A :class:`.FetchedValue` instance, str, Unicode or :func:`~sqlalchemy.sql.expression.text` construct representing the DDL DEFAULT value for the column. String types will be emitted as-is, surrounded by single quotes:: Column('x', Text, server_default="val") x TEXT DEFAULT 'val' A :func:`~sqlalchemy.sql.expression.text` expression will be rendered as-is, without quotes:: Column('y', DateTime, server_default=text('NOW()')) y DATETIME DEFAULT NOW() Strings and text() will be converted into a :class:`.DefaultClause` object upon initialization. Use :class:`.FetchedValue` to indicate that an already-existing column will generate a default value on the database side which will be available to SQLAlchemy for post-fetch after inserts. This construct does not specify any DDL and the implementation is left to the database, such as via a trigger. :param server_onupdate: A :class:`.FetchedValue` instance representing a database-side default generation function. This indicates to SQLAlchemy that a newly generated value will be available after updates. This construct does not specify any DDL and the implementation is left to the database, such as via a trigger. :param quote: Force quoting of this column's name on or off, corresponding to ``True`` or ``False``. When left at its default of ``None``, the column identifier will be quoted according to whether the name is case sensitive (identifiers with at least one upper case character are treated as case sensitive), or if it's a reserved word. This flag is only needed to force quoting of a reserved word which is not known by the SQLAlchemy dialect. :param unique: When ``True``, indicates that this column contains a unique constraint, or if ``index`` is ``True`` as well, indicates that the :class:`.Index` should be created with the unique flag. To specify multiple columns in the constraint/index or to specify an explicit name, use the :class:`.UniqueConstraint` or :class:`.Index` constructs explicitly. :param system: When ``True``, indicates this is a "system" column, that is a column which is automatically made available by the database, and should not be included in the columns list for a ``CREATE TABLE`` statement. For more elaborate scenarios where columns should be conditionally rendered differently on different backends, consider custom compilation rules for :class:`.CreateColumn`. .. versionadded:: 0.8.3 Added the ``system=True`` parameter to :class:`.Column`. """ name = kwargs.pop('name', None) type_ = kwargs.pop('type_', None) args = list(args) if args: if isinstance(args[0], util.string_types): if name is not None: raise exc.ArgumentError( "May not pass name positionally and as a keyword.") name = args.pop(0) if args: coltype = args[0] if hasattr(coltype, "_sqla_type"): if type_ is not None: raise exc.ArgumentError( "May not pass type_ positionally and as a keyword.") type_ = args.pop(0) if name is not None: name = quoted_name(name, kwargs.pop('quote', None)) elif "quote" in kwargs: raise exc.ArgumentError("Explicit 'name' is required when " "sending 'quote' argument") super(Column, self).__init__(name, type_) self.key = kwargs.pop('key', name) self.primary_key = kwargs.pop('primary_key', False) self.nullable = kwargs.pop('nullable', not self.primary_key) self.default = kwargs.pop('default', None) self.server_default = kwargs.pop('server_default', None) self.server_onupdate = kwargs.pop('server_onupdate', None) # these default to None because .index and .unique is *not* # an informational flag about Column - there can still be an # Index or UniqueConstraint referring to this Column. self.index = kwargs.pop('index', None) self.unique = kwargs.pop('unique', None) self.system = kwargs.pop('system', False) self.doc = kwargs.pop('doc', None) self.onupdate = kwargs.pop('onupdate', None) self.autoincrement = kwargs.pop('autoincrement', True) self.constraints = set() self.foreign_keys = set() # check if this Column is proxying another column if '_proxies' in kwargs: self._proxies = kwargs.pop('_proxies') # otherwise, add DDL-related events elif isinstance(self.type, SchemaEventTarget): self.type._set_parent_with_dispatch(self) if self.default is not None: if isinstance(self.default, (ColumnDefault, Sequence)): args.append(self.default) else: if getattr(self.type, '_warn_on_bytestring', False): if isinstance(self.default, util.binary_type): util.warn( "Unicode column '%s' has non-unicode " "default value %r specified." % ( self.key, self.default )) args.append(ColumnDefault(self.default)) if self.server_default is not None: if isinstance(self.server_default, FetchedValue): args.append(self.server_default._as_for_update(False)) else: args.append(DefaultClause(self.server_default)) if self.onupdate is not None: if isinstance(self.onupdate, (ColumnDefault, Sequence)): args.append(self.onupdate) else: args.append(ColumnDefault(self.onupdate, for_update=True)) if self.server_onupdate is not None: if isinstance(self.server_onupdate, FetchedValue): args.append(self.server_onupdate._as_for_update(True)) else: args.append(DefaultClause(self.server_onupdate, for_update=True)) self._init_items(*args) util.set_creation_order(self) if 'info' in kwargs: self.info = kwargs.pop('info') if kwargs: raise exc.ArgumentError( "Unknown arguments passed to Column: " + repr(list(kwargs))) # @property # def quote(self): # return getattr(self.name, "quote", None) def __str__(self): if self.name is None: return "(no name)" elif self.table is not None: if self.table.named_with_column: return (self.table.description + "." + self.description) else: return self.description else: return self.description def references(self, column): """Return True if this Column references the given column via foreign key.""" for fk in self.foreign_keys: if fk.column.proxy_set.intersection(column.proxy_set): return True else: return False def append_foreign_key(self, fk): fk._set_parent_with_dispatch(self) def __repr__(self): kwarg = [] if self.key != self.name: kwarg.append('key') if self.primary_key: kwarg.append('primary_key') if not self.nullable: kwarg.append('nullable') if self.onupdate: kwarg.append('onupdate') if self.default: kwarg.append('default') if self.server_default: kwarg.append('server_default') return "Column(%s)" % ', '.join( [repr(self.name)] + [repr(self.type)] + [repr(x) for x in self.foreign_keys if x is not None] + [repr(x) for x in self.constraints] + [(self.table is not None and "table=<%s>" % self.table.description or "table=None")] + ["%s=%s" % (k, repr(getattr(self, k))) for k in kwarg]) def _set_parent(self, table): if not self.name: raise exc.ArgumentError( "Column must be constructed with a non-blank name or " "assign a non-blank .name before adding to a Table.") if self.key is None: self.key = self.name existing = getattr(self, 'table', None) if existing is not None and existing is not table: raise exc.ArgumentError( "Column object '%s' already assigned to Table '%s'" % ( self.key, existing.description )) if self.key in table._columns: col = table._columns.get(self.key) if col is not self: for fk in col.foreign_keys: table.foreign_keys.remove(fk) if fk.constraint in table.constraints: # this might have been removed # already, if it's a composite constraint # and more than one col being replaced table.constraints.remove(fk.constraint) table._columns.replace(self) if self.primary_key: table.primary_key._replace(self) Table._autoincrement_column._reset(table) elif self.key in table.primary_key: raise exc.ArgumentError( "Trying to redefine primary-key column '%s' as a " "non-primary-key column on table '%s'" % ( self.key, table.fullname)) self.table = table if self.index: if isinstance(self.index, util.string_types): raise exc.ArgumentError( "The 'index' keyword argument on Column is boolean only. " "To create indexes with a specific name, create an " "explicit Index object external to the Table.") Index(None, self, unique=bool(self.unique)) elif self.unique: if isinstance(self.unique, util.string_types): raise exc.ArgumentError( "The 'unique' keyword argument on Column is boolean " "only. To create unique constraints or indexes with a " "specific name, append an explicit UniqueConstraint to " "the Table's list of elements, or create an explicit " "Index object external to the Table.") table.append_constraint(UniqueConstraint(self.key)) self._setup_on_memoized_fks(lambda fk: fk._set_remote_table(table)) def _setup_on_memoized_fks(self, fn): fk_keys = [ ((self.table.key, self.key), False), ((self.table.key, self.name), True), ] for fk_key, link_to_name in fk_keys: if fk_key in self.table.metadata._fk_memos: for fk in self.table.metadata._fk_memos[fk_key]: if fk.link_to_name is link_to_name: fn(fk) def _on_table_attach(self, fn): if self.table is not None: fn(self, self.table) else: event.listen(self, 'after_parent_attach', fn) def copy(self, **kw): """Create a copy of this ``Column``, unitialized. This is used in ``Table.tometadata``. """ # Constraint objects plus non-constraint-bound ForeignKey objects args = \ [c.copy(**kw) for c in self.constraints if not c._type_bound] + \ [c.copy(**kw) for c in self.foreign_keys if not c.constraint] type_ = self.type if isinstance(type_, SchemaEventTarget): type_ = type_.copy(**kw) c = self._constructor( name=self.name, type_=type_, key=self.key, primary_key=self.primary_key, nullable=self.nullable, unique=self.unique, system=self.system, # quote=self.quote, index=self.index, autoincrement=self.autoincrement, default=self.default, server_default=self.server_default, onupdate=self.onupdate, server_onupdate=self.server_onupdate, doc=self.doc, *args ) return self._schema_item_copy(c) def _make_proxy(self, selectable, name=None, key=None, name_is_truncatable=False, **kw): """Create a *proxy* for this column. This is a copy of this ``Column`` referenced by a different parent (such as an alias or select statement). The column should be used only in select scenarios, as its full DDL/default information is not transferred. """ fk = [ForeignKey(f.column, _constraint=f.constraint) for f in self.foreign_keys] if name is None and self.name is None: raise exc.InvalidRequestError( "Cannot initialize a sub-selectable" " with this Column object until its 'name' has " "been assigned.") try: c = self._constructor( _as_truncated(name or self.name) if name_is_truncatable else (name or self.name), self.type, key=key if key else name if name else self.key, primary_key=self.primary_key, nullable=self.nullable, _proxies=[self], *fk) except TypeError: util.raise_from_cause( TypeError( "Could not create a copy of this %r object. " "Ensure the class includes a _constructor() " "attribute or method which accepts the " "standard Column constructor arguments, or " "references the Column class itself." % self.__class__) ) c.table = selectable selectable._columns.add(c) if selectable._is_clone_of is not None: c._is_clone_of = selectable._is_clone_of.columns[c.key] if self.primary_key: selectable.primary_key.add(c) c.dispatch.after_parent_attach(c, selectable) return c def get_children(self, schema_visitor=False, **kwargs): if schema_visitor: return [x for x in (self.default, self.onupdate) if x is not None] + \ list(self.foreign_keys) + list(self.constraints) else: return ColumnClause.get_children(self, **kwargs) class ForeignKey(DialectKWArgs, SchemaItem): """Defines a dependency between two columns. ``ForeignKey`` is specified as an argument to a :class:`.Column` object, e.g.:: t = Table("remote_table", metadata, Column("remote_id", ForeignKey("main_table.id")) ) Note that ``ForeignKey`` is only a marker object that defines a dependency between two columns. The actual constraint is in all cases represented by the :class:`.ForeignKeyConstraint` object. This object will be generated automatically when a ``ForeignKey`` is associated with a :class:`.Column` which in turn is associated with a :class:`.Table`. Conversely, when :class:`.ForeignKeyConstraint` is applied to a :class:`.Table`, ``ForeignKey`` markers are automatically generated to be present on each associated :class:`.Column`, which are also associated with the constraint object. Note that you cannot define a "composite" foreign key constraint, that is a constraint between a grouping of multiple parent/child columns, using ``ForeignKey`` objects. To define this grouping, the :class:`.ForeignKeyConstraint` object must be used, and applied to the :class:`.Table`. The associated ``ForeignKey`` objects are created automatically. The ``ForeignKey`` objects associated with an individual :class:`.Column` object are available in the `foreign_keys` collection of that column. Further examples of foreign key configuration are in :ref:`metadata_foreignkeys`. """ __visit_name__ = 'foreign_key' def __init__(self, column, _constraint=None, use_alter=False, name=None, onupdate=None, ondelete=None, deferrable=None, initially=None, link_to_name=False, match=None, info=None, **dialect_kw): """ Construct a column-level FOREIGN KEY. The :class:`.ForeignKey` object when constructed generates a :class:`.ForeignKeyConstraint` which is associated with the parent :class:`.Table` object's collection of constraints. :param column: A single target column for the key relationship. A :class:`.Column` object or a column name as a string: ``tablename.columnkey`` or ``schema.tablename.columnkey``. ``columnkey`` is the ``key`` which has been assigned to the column (defaults to the column name itself), unless ``link_to_name`` is ``True`` in which case the rendered name of the column is used. .. versionadded:: 0.7.4 Note that if the schema name is not included, and the underlying :class:`.MetaData` has a "schema", that value will be used. :param name: Optional string. An in-database name for the key if `constraint` is not provided. :param onupdate: Optional string. If set, emit ON UPDATE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT. :param ondelete: Optional string. If set, emit ON DELETE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint. :param link_to_name: if True, the string name given in ``column`` is the rendered name of the referenced column, not its locally assigned ``key``. :param use_alter: passed to the underlying :class:`.ForeignKeyConstraint` to indicate the constraint should be generated/dropped externally from the CREATE TABLE/ DROP TABLE statement. See :paramref:`.ForeignKeyConstraint.use_alter` for further description. .. seealso:: :paramref:`.ForeignKeyConstraint.use_alter` :ref:`use_alter` :param match: Optional string. If set, emit MATCH <value> when issuing DDL for this constraint. Typical values include SIMPLE, PARTIAL and FULL. :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. .. versionadded:: 1.0.0 :param \**dialect_kw: Additional keyword arguments are dialect specific, and passed in the form ``<dialectname>_<argname>``. The arguments are ultimately handled by a corresponding :class:`.ForeignKeyConstraint`. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. .. versionadded:: 0.9.2 """ self._colspec = column if isinstance(self._colspec, util.string_types): self._table_column = None else: if hasattr(self._colspec, '__clause_element__'): self._table_column = self._colspec.__clause_element__() else: self._table_column = self._colspec if not isinstance(self._table_column, ColumnClause): raise exc.ArgumentError( "String, Column, or Column-bound argument " "expected, got %r" % self._table_column) elif not isinstance( self._table_column.table, (util.NoneType, TableClause)): raise exc.ArgumentError( "ForeignKey received Column not bound " "to a Table, got: %r" % self._table_column.table ) # the linked ForeignKeyConstraint. # ForeignKey will create this when parent Column # is attached to a Table, *or* ForeignKeyConstraint # object passes itself in when creating ForeignKey # markers. self.constraint = _constraint self.parent = None self.use_alter = use_alter self.name = name self.onupdate = onupdate self.ondelete = ondelete self.deferrable = deferrable self.initially = initially self.link_to_name = link_to_name self.match = match if info: self.info = info self._unvalidated_dialect_kw = dialect_kw def __repr__(self): return "ForeignKey(%r)" % self._get_colspec() def copy(self, schema=None): """Produce a copy of this :class:`.ForeignKey` object. The new :class:`.ForeignKey` will not be bound to any :class:`.Column`. This method is usually used by the internal copy procedures of :class:`.Column`, :class:`.Table`, and :class:`.MetaData`. :param schema: The returned :class:`.ForeignKey` will reference the original table and column name, qualified by the given string schema name. """ fk = ForeignKey( self._get_colspec(schema=schema), use_alter=self.use_alter, name=self.name, onupdate=self.onupdate, ondelete=self.ondelete, deferrable=self.deferrable, initially=self.initially, link_to_name=self.link_to_name, match=self.match, **self._unvalidated_dialect_kw ) return self._schema_item_copy(fk) def _get_colspec(self, schema=None, table_name=None): """Return a string based 'column specification' for this :class:`.ForeignKey`. This is usually the equivalent of the string-based "tablename.colname" argument first passed to the object's constructor. """ if schema: _schema, tname, colname = self._column_tokens if table_name is not None: tname = table_name return "%s.%s.%s" % (schema, tname, colname) elif table_name: schema, tname, colname = self._column_tokens if schema: return "%s.%s.%s" % (schema, table_name, colname) else: return "%s.%s" % (table_name, colname) elif self._table_column is not None: return "%s.%s" % ( self._table_column.table.fullname, self._table_column.key) else: return self._colspec @property def _referred_schema(self): return self._column_tokens[0] def _table_key(self): if self._table_column is not None: if self._table_column.table is None: return None else: return self._table_column.table.key else: schema, tname, colname = self._column_tokens return _get_table_key(tname, schema) target_fullname = property(_get_colspec) def references(self, table): """Return True if the given :class:`.Table` is referenced by this :class:`.ForeignKey`.""" return table.corresponding_column(self.column) is not None def get_referent(self, table): """Return the :class:`.Column` in the given :class:`.Table` referenced by this :class:`.ForeignKey`. Returns None if this :class:`.ForeignKey` does not reference the given :class:`.Table`. """ return table.corresponding_column(self.column) @util.memoized_property def _column_tokens(self): """parse a string-based _colspec into its component parts.""" m = self._get_colspec().split('.') if m is None: raise exc.ArgumentError( "Invalid foreign key column specification: %s" % self._colspec) if (len(m) == 1): tname = m.pop() colname = None else: colname = m.pop() tname = m.pop() # A FK between column 'bar' and table 'foo' can be # specified as 'foo', 'foo.bar', 'dbo.foo.bar', # 'otherdb.dbo.foo.bar'. Once we have the column name and # the table name, treat everything else as the schema # name. Some databases (e.g. Sybase) support # inter-database foreign keys. See tickets#1341 and -- # indirectly related -- Ticket #594. This assumes that '.' # will never appear *within* any component of the FK. if (len(m) > 0): schema = '.'.join(m) else: schema = None return schema, tname, colname def _resolve_col_tokens(self): if self.parent is None: raise exc.InvalidRequestError( "this ForeignKey object does not yet have a " "parent Column associated with it.") elif self.parent.table is None: raise exc.InvalidRequestError( "this ForeignKey's parent column is not yet associated " "with a Table.") parenttable = self.parent.table # assertion, can be commented out. # basically Column._make_proxy() sends the actual # target Column to the ForeignKey object, so the # string resolution here is never called. for c in self.parent.base_columns: if isinstance(c, Column): assert c.table is parenttable break else: assert False ###################### schema, tname, colname = self._column_tokens if schema is None and parenttable.metadata.schema is not None: schema = parenttable.metadata.schema tablekey = _get_table_key(tname, schema) return parenttable, tablekey, colname def _link_to_col_by_colstring(self, parenttable, table, colname): if not hasattr(self.constraint, '_referred_table'): self.constraint._referred_table = table else: assert self.constraint._referred_table is table _column = None if colname is None: # colname is None in the case that ForeignKey argument # was specified as table name only, in which case we # match the column name to the same column on the # parent. key = self.parent _column = table.c.get(self.parent.key, None) elif self.link_to_name: key = colname for c in table.c: if c.name == colname: _column = c else: key = colname _column = table.c.get(colname, None) if _column is None: raise exc.NoReferencedColumnError( "Could not initialize target column " "for ForeignKey '%s' on table '%s': " "table '%s' has no column named '%s'" % (self._colspec, parenttable.name, table.name, key), table.name, key) self._set_target_column(_column) def _set_target_column(self, column): # propagate TypeEngine to parent if it didn't have one if self.parent.type._isnull: self.parent.type = column.type # super-edgy case, if other FKs point to our column, # they'd get the type propagated out also. if isinstance(self.parent.table, Table): def set_type(fk): if fk.parent.type._isnull: fk.parent.type = column.type self.parent._setup_on_memoized_fks(set_type) self.column = column @util.memoized_property def column(self): """Return the target :class:`.Column` referenced by this :class:`.ForeignKey`. If no target column has been established, an exception is raised. .. versionchanged:: 0.9.0 Foreign key target column resolution now occurs as soon as both the ForeignKey object and the remote Column to which it refers are both associated with the same MetaData object. """ if isinstance(self._colspec, util.string_types): parenttable, tablekey, colname = self._resolve_col_tokens() if tablekey not in parenttable.metadata: raise exc.NoReferencedTableError( "Foreign key associated with column '%s' could not find " "table '%s' with which to generate a " "foreign key to target column '%s'" % (self.parent, tablekey, colname), tablekey) elif parenttable.key not in parenttable.metadata: raise exc.InvalidRequestError( "Table %s is no longer associated with its " "parent MetaData" % parenttable) else: raise exc.NoReferencedColumnError( "Could not initialize target column for " "ForeignKey '%s' on table '%s': " "table '%s' has no column named '%s'" % ( self._colspec, parenttable.name, tablekey, colname), tablekey, colname) elif hasattr(self._colspec, '__clause_element__'): _column = self._colspec.__clause_element__() return _column else: _column = self._colspec return _column def _set_parent(self, column): if self.parent is not None and self.parent is not column: raise exc.InvalidRequestError( "This ForeignKey already has a parent !") self.parent = column self.parent.foreign_keys.add(self) self.parent._on_table_attach(self._set_table) def _set_remote_table(self, table): parenttable, tablekey, colname = self._resolve_col_tokens() self._link_to_col_by_colstring(parenttable, table, colname) self.constraint._validate_dest_table(table) def _remove_from_metadata(self, metadata): parenttable, table_key, colname = self._resolve_col_tokens() fk_key = (table_key, colname) if self in metadata._fk_memos[fk_key]: # TODO: no test coverage for self not in memos metadata._fk_memos[fk_key].remove(self) def _set_table(self, column, table): # standalone ForeignKey - create ForeignKeyConstraint # on the hosting Table when attached to the Table. if self.constraint is None and isinstance(table, Table): self.constraint = ForeignKeyConstraint( [], [], use_alter=self.use_alter, name=self.name, onupdate=self.onupdate, ondelete=self.ondelete, deferrable=self.deferrable, initially=self.initially, match=self.match, **self._unvalidated_dialect_kw ) self.constraint._append_element(column, self) self.constraint._set_parent_with_dispatch(table) table.foreign_keys.add(self) # set up remote ".column" attribute, or a note to pick it # up when the other Table/Column shows up if isinstance(self._colspec, util.string_types): parenttable, table_key, colname = self._resolve_col_tokens() fk_key = (table_key, colname) if table_key in parenttable.metadata.tables: table = parenttable.metadata.tables[table_key] try: self._link_to_col_by_colstring( parenttable, table, colname) except exc.NoReferencedColumnError: # this is OK, we'll try later pass parenttable.metadata._fk_memos[fk_key].append(self) elif hasattr(self._colspec, '__clause_element__'): _column = self._colspec.__clause_element__() self._set_target_column(_column) else: _column = self._colspec self._set_target_column(_column) class _NotAColumnExpr(object): def _not_a_column_expr(self): raise exc.InvalidRequestError( "This %s cannot be used directly " "as a column expression." % self.__class__.__name__) __clause_element__ = self_group = lambda self: self._not_a_column_expr() _from_objects = property(lambda self: self._not_a_column_expr()) class DefaultGenerator(_NotAColumnExpr, SchemaItem): """Base class for column *default* values.""" __visit_name__ = 'default_generator' is_sequence = False is_server_default = False column = None def __init__(self, for_update=False): self.for_update = for_update def _set_parent(self, column): self.column = column if self.for_update: self.column.onupdate = self else: self.column.default = self def execute(self, bind=None, **kwargs): if bind is None: bind = _bind_or_error(self) return bind._execute_default(self, **kwargs) @property def bind(self): """Return the connectable associated with this default.""" if getattr(self, 'column', None) is not None: return self.column.table.bind else: return None class ColumnDefault(DefaultGenerator): """A plain default value on a column. This could correspond to a constant, a callable function, or a SQL clause. :class:`.ColumnDefault` is generated automatically whenever the ``default``, ``onupdate`` arguments of :class:`.Column` are used. A :class:`.ColumnDefault` can be passed positionally as well. For example, the following:: Column('foo', Integer, default=50) Is equivalent to:: Column('foo', Integer, ColumnDefault(50)) """ def __init__(self, arg, **kwargs): """"Construct a new :class:`.ColumnDefault`. :param arg: argument representing the default value. May be one of the following: * a plain non-callable Python value, such as a string, integer, boolean, or other simple type. The default value will be used as is each time. * a SQL expression, that is one which derives from :class:`.ColumnElement`. The SQL expression will be rendered into the INSERT or UPDATE statement, or in the case of a primary key column when RETURNING is not used may be pre-executed before an INSERT within a SELECT. * A Python callable. The function will be invoked for each new row subject to an INSERT or UPDATE. The callable must accept exactly zero or one positional arguments. The one-argument form will receive an instance of the :class:`.ExecutionContext`, which provides contextual information as to the current :class:`.Connection` in use as well as the current statement and parameters. """ super(ColumnDefault, self).__init__(**kwargs) if isinstance(arg, FetchedValue): raise exc.ArgumentError( "ColumnDefault may not be a server-side default type.") if util.callable(arg): arg = self._maybe_wrap_callable(arg) self.arg = arg @util.memoized_property def is_callable(self): return util.callable(self.arg) @util.memoized_property def is_clause_element(self): return isinstance(self.arg, ClauseElement) @util.memoized_property def is_scalar(self): return not self.is_callable and \ not self.is_clause_element and \ not self.is_sequence def _maybe_wrap_callable(self, fn): """Wrap callables that don't accept a context. This is to allow easy compatibility with default callables that aren't specific to accepting of a context. """ try: argspec = util.get_callable_argspec(fn, no_self=True) except TypeError: return lambda ctx: fn() defaulted = argspec[3] is not None and len(argspec[3]) or 0 positionals = len(argspec[0]) - defaulted if positionals == 0: return lambda ctx: fn() elif positionals == 1: return fn else: raise exc.ArgumentError( "ColumnDefault Python function takes zero or one " "positional arguments") def _visit_name(self): if self.for_update: return "column_onupdate" else: return "column_default" __visit_name__ = property(_visit_name) def __repr__(self): return "ColumnDefault(%r)" % self.arg class Sequence(DefaultGenerator): """Represents a named database sequence. The :class:`.Sequence` object represents the name and configurational parameters of a database sequence. It also represents a construct that can be "executed" by a SQLAlchemy :class:`.Engine` or :class:`.Connection`, rendering the appropriate "next value" function for the target database and returning a result. The :class:`.Sequence` is typically associated with a primary key column:: some_table = Table( 'some_table', metadata, Column('id', Integer, Sequence('some_table_seq'), primary_key=True) ) When CREATE TABLE is emitted for the above :class:`.Table`, if the target platform supports sequences, a CREATE SEQUENCE statement will be emitted as well. For platforms that don't support sequences, the :class:`.Sequence` construct is ignored. .. seealso:: :class:`.CreateSequence` :class:`.DropSequence` """ __visit_name__ = 'sequence' is_sequence = True def __init__(self, name, start=None, increment=None, minvalue=None, maxvalue=None, nominvalue=None, nomaxvalue=None, cycle=None, schema=None, optional=False, quote=None, metadata=None, quote_schema=None, for_update=False): """Construct a :class:`.Sequence` object. :param name: The name of the sequence. :param start: the starting index of the sequence. This value is used when the CREATE SEQUENCE command is emitted to the database as the value of the "START WITH" clause. If ``None``, the clause is omitted, which on most platforms indicates a starting value of 1. :param increment: the increment value of the sequence. This value is used when the CREATE SEQUENCE command is emitted to the database as the value of the "INCREMENT BY" clause. If ``None``, the clause is omitted, which on most platforms indicates an increment of 1. :param minvalue: the minimum value of the sequence. This value is used when the CREATE SEQUENCE command is emitted to the database as the value of the "MINVALUE" clause. If ``None``, the clause is omitted, which on most platforms indicates a minvalue of 1 and -2^63-1 for ascending and descending sequences, respectively. .. versionadded:: 1.0.7 :param maxvalue: the maximum value of the sequence. This value is used when the CREATE SEQUENCE command is emitted to the database as the value of the "MAXVALUE" clause. If ``None``, the clause is omitted, which on most platforms indicates a maxvalue of 2^63-1 and -1 for ascending and descending sequences, respectively. .. versionadded:: 1.0.7 :param nominvalue: no minimum value of the sequence. This value is used when the CREATE SEQUENCE command is emitted to the database as the value of the "NO MINVALUE" clause. If ``None``, the clause is omitted, which on most platforms indicates a minvalue of 1 and -2^63-1 for ascending and descending sequences, respectively. .. versionadded:: 1.0.7 :param nomaxvalue: no maximum value of the sequence. This value is used when the CREATE SEQUENCE command is emitted to the database as the value of the "NO MAXVALUE" clause. If ``None``, the clause is omitted, which on most platforms indicates a maxvalue of 2^63-1 and -1 for ascending and descending sequences, respectively. .. versionadded:: 1.0.7 :param cycle: allows the sequence to wrap around when the maxvalue or minvalue has been reached by an ascending or descending sequence respectively. This value is used when the CREATE SEQUENCE command is emitted to the database as the "CYCLE" clause. If the limit is reached, the next number generated will be the minvalue or maxvalue, respectively. If cycle=False (the default) any calls to nextval after the sequence has reached its maximum value will return an error. .. versionadded:: 1.0.7 :param schema: Optional schema name for the sequence, if located in a schema other than the default. :param optional: boolean value, when ``True``, indicates that this :class:`.Sequence` object only needs to be explicitly generated on backends that don't provide another way to generate primary key identifiers. Currently, it essentially means, "don't create this sequence on the Postgresql backend, where the SERIAL keyword creates a sequence for us automatically". :param quote: boolean value, when ``True`` or ``False``, explicitly forces quoting of the schema name on or off. When left at its default of ``None``, normal quoting rules based on casing and reserved words take place. :param quote_schema: set the quoting preferences for the ``schema`` name. :param metadata: optional :class:`.MetaData` object which will be associated with this :class:`.Sequence`. A :class:`.Sequence` that is associated with a :class:`.MetaData` gains access to the ``bind`` of that :class:`.MetaData`, meaning the :meth:`.Sequence.create` and :meth:`.Sequence.drop` methods will make usage of that engine automatically. .. versionchanged:: 0.7 Additionally, the appropriate CREATE SEQUENCE/ DROP SEQUENCE DDL commands will be emitted corresponding to this :class:`.Sequence` when :meth:`.MetaData.create_all` and :meth:`.MetaData.drop_all` are invoked. Note that when a :class:`.Sequence` is applied to a :class:`.Column`, the :class:`.Sequence` is automatically associated with the :class:`.MetaData` object of that column's parent :class:`.Table`, when that association is made. The :class:`.Sequence` will then be subject to automatic CREATE SEQUENCE/DROP SEQUENCE corresponding to when the :class:`.Table` object itself is created or dropped, rather than that of the :class:`.MetaData` object overall. :param for_update: Indicates this :class:`.Sequence`, when associated with a :class:`.Column`, should be invoked for UPDATE statements on that column's table, rather than for INSERT statements, when no value is otherwise present for that column in the statement. """ super(Sequence, self).__init__(for_update=for_update) self.name = quoted_name(name, quote) self.start = start self.increment = increment self.minvalue = minvalue self.maxvalue = maxvalue self.nominvalue = nominvalue self.nomaxvalue = nomaxvalue self.cycle = cycle self.optional = optional if metadata is not None and schema is None and metadata.schema: self.schema = schema = metadata.schema else: self.schema = quoted_name(schema, quote_schema) self.metadata = metadata self._key = _get_table_key(name, schema) if metadata: self._set_metadata(metadata) @util.memoized_property def is_callable(self): return False @util.memoized_property def is_clause_element(self): return False @util.dependencies("sqlalchemy.sql.functions.func") def next_value(self, func): """Return a :class:`.next_value` function element which will render the appropriate increment function for this :class:`.Sequence` within any SQL expression. """ return func.next_value(self, bind=self.bind) def _set_parent(self, column): super(Sequence, self)._set_parent(column) column._on_table_attach(self._set_table) def _set_table(self, column, table): self._set_metadata(table.metadata) def _set_metadata(self, metadata): self.metadata = metadata self.metadata._sequences[self._key] = self @property def bind(self): if self.metadata: return self.metadata.bind else: return None def create(self, bind=None, checkfirst=True): """Creates this sequence in the database.""" if bind is None: bind = _bind_or_error(self) bind._run_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst) def drop(self, bind=None, checkfirst=True): """Drops this sequence from the database.""" if bind is None: bind = _bind_or_error(self) bind._run_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst) def _not_a_column_expr(self): raise exc.InvalidRequestError( "This %s cannot be used directly " "as a column expression. Use func.next_value(sequence) " "to produce a 'next value' function that's usable " "as a column element." % self.__class__.__name__) @inspection._self_inspects class FetchedValue(_NotAColumnExpr, SchemaEventTarget): """A marker for a transparent database-side default. Use :class:`.FetchedValue` when the database is configured to provide some automatic default for a column. E.g.:: Column('foo', Integer, FetchedValue()) Would indicate that some trigger or default generator will create a new value for the ``foo`` column during an INSERT. .. seealso:: :ref:`triggered_columns` """ is_server_default = True reflected = False has_argument = False def __init__(self, for_update=False): self.for_update = for_update def _as_for_update(self, for_update): if for_update == self.for_update: return self else: return self._clone(for_update) def _clone(self, for_update): n = self.__class__.__new__(self.__class__) n.__dict__.update(self.__dict__) n.__dict__.pop('column', None) n.for_update = for_update return n def _set_parent(self, column): self.column = column if self.for_update: self.column.server_onupdate = self else: self.column.server_default = self def __repr__(self): return util.generic_repr(self) class DefaultClause(FetchedValue): """A DDL-specified DEFAULT column value. :class:`.DefaultClause` is a :class:`.FetchedValue` that also generates a "DEFAULT" clause when "CREATE TABLE" is emitted. :class:`.DefaultClause` is generated automatically whenever the ``server_default``, ``server_onupdate`` arguments of :class:`.Column` are used. A :class:`.DefaultClause` can be passed positionally as well. For example, the following:: Column('foo', Integer, server_default="50") Is equivalent to:: Column('foo', Integer, DefaultClause("50")) """ has_argument = True def __init__(self, arg, for_update=False, _reflected=False): util.assert_arg_type(arg, (util.string_types[0], ClauseElement, TextClause), 'arg') super(DefaultClause, self).__init__(for_update) self.arg = arg self.reflected = _reflected def __repr__(self): return "DefaultClause(%r, for_update=%r)" % \ (self.arg, self.for_update) class PassiveDefault(DefaultClause): """A DDL-specified DEFAULT column value. .. deprecated:: 0.6 :class:`.PassiveDefault` is deprecated. Use :class:`.DefaultClause`. """ @util.deprecated("0.6", ":class:`.PassiveDefault` is deprecated. " "Use :class:`.DefaultClause`.", False) def __init__(self, *arg, **kw): DefaultClause.__init__(self, *arg, **kw) class Constraint(DialectKWArgs, SchemaItem): """A table-level SQL constraint.""" __visit_name__ = 'constraint' def __init__(self, name=None, deferrable=None, initially=None, _create_rule=None, info=None, _type_bound=False, **dialect_kw): """Create a SQL constraint. :param name: Optional, the in-database name of this ``Constraint``. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint. :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. .. versionadded:: 1.0.0 :param _create_rule: a callable which is passed the DDLCompiler object during compilation. Returns True or False to signal inline generation of this Constraint. The AddConstraint and DropConstraint DDL constructs provide DDLElement's more comprehensive "conditional DDL" approach that is passed a database connection when DDL is being issued. _create_rule is instead called during any CREATE TABLE compilation, where there may not be any transaction/connection in progress. However, it allows conditional compilation of the constraint even for backends which do not support addition of constraints through ALTER TABLE, which currently includes SQLite. _create_rule is used by some types to create constraints. Currently, its call signature is subject to change at any time. :param \**dialect_kw: Additional keyword arguments are dialect specific, and passed in the form ``<dialectname>_<argname>``. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. """ self.name = name self.deferrable = deferrable self.initially = initially if info: self.info = info self._create_rule = _create_rule self._type_bound = _type_bound util.set_creation_order(self) self._validate_dialect_kwargs(dialect_kw) @property def table(self): try: if isinstance(self.parent, Table): return self.parent except AttributeError: pass raise exc.InvalidRequestError( "This constraint is not bound to a table. Did you " "mean to call table.append_constraint(constraint) ?") def _set_parent(self, parent): self.parent = parent parent.constraints.add(self) def copy(self, **kw): raise NotImplementedError() def _to_schema_column(element): if hasattr(element, '__clause_element__'): element = element.__clause_element__() if not isinstance(element, Column): raise exc.ArgumentError("schema.Column object expected") return element def _to_schema_column_or_string(element): if hasattr(element, '__clause_element__'): element = element.__clause_element__() if not isinstance(element, util.string_types + (ColumnElement, )): msg = "Element %r is not a string name or column element" raise exc.ArgumentError(msg % element) return element class ColumnCollectionMixin(object): columns = None """A :class:`.ColumnCollection` of :class:`.Column` objects. This collection represents the columns which are referred to by this object. """ _allow_multiple_tables = False def __init__(self, *columns, **kw): _autoattach = kw.pop('_autoattach', True) self.columns = ColumnCollection() self._pending_colargs = [_to_schema_column_or_string(c) for c in columns] if _autoattach and self._pending_colargs: self._check_attach() @classmethod def _extract_col_expression_collection(cls, expressions): for expr in expressions: strname = None column = None if not isinstance(expr, ClauseElement): # this assumes a string strname = expr else: cols = [] visitors.traverse(expr, {}, {'column': cols.append}) if cols: column = cols[0] add_element = column if column is not None else strname yield expr, column, strname, add_element def _check_attach(self, evt=False): col_objs = [ c for c in self._pending_colargs if isinstance(c, Column) ] cols_w_table = [ c for c in col_objs if isinstance(c.table, Table) ] cols_wo_table = set(col_objs).difference(cols_w_table) if cols_wo_table: # feature #3341 - place event listeners for Column objects # such that when all those cols are attached, we autoattach. assert not evt, "Should not reach here on event call" # issue #3411 - don't do the per-column auto-attach if some of the # columns are specified as strings. has_string_cols = set(self._pending_colargs).difference(col_objs) if not has_string_cols: def _col_attached(column, table): cols_wo_table.discard(column) if not cols_wo_table: self._check_attach(evt=True) self._cols_wo_table = cols_wo_table for col in cols_wo_table: col._on_table_attach(_col_attached) return columns = cols_w_table tables = set([c.table for c in columns]) if len(tables) == 1: self._set_parent_with_dispatch(tables.pop()) elif len(tables) > 1 and not self._allow_multiple_tables: table = columns[0].table others = [c for c in columns[1:] if c.table is not table] if others: raise exc.ArgumentError( "Column(s) %s are not part of table '%s'." % (", ".join("'%s'" % c for c in others), table.description) ) def _set_parent(self, table): for col in self._pending_colargs: if isinstance(col, util.string_types): col = table.c[col] self.columns.add(col) class ColumnCollectionConstraint(ColumnCollectionMixin, Constraint): """A constraint that proxies a ColumnCollection.""" def __init__(self, *columns, **kw): """ :param \*columns: A sequence of column names or Column objects. :param name: Optional, the in-database name of this constraint. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint. :param \**kw: other keyword arguments including dialect-specific arguments are propagated to the :class:`.Constraint` superclass. """ _autoattach = kw.pop('_autoattach', True) Constraint.__init__(self, **kw) ColumnCollectionMixin.__init__(self, *columns, _autoattach=_autoattach) def _set_parent(self, table): Constraint._set_parent(self, table) ColumnCollectionMixin._set_parent(self, table) def __contains__(self, x): return x in self.columns def copy(self, **kw): c = self.__class__(name=self.name, deferrable=self.deferrable, initially=self.initially, *self.columns.keys()) return self._schema_item_copy(c) def contains_column(self, col): """Return True if this constraint contains the given column. Note that this object also contains an attribute ``.columns`` which is a :class:`.ColumnCollection` of :class:`.Column` objects. """ return self.columns.contains_column(col) def __iter__(self): # inlining of # return iter(self.columns) # ColumnCollection->OrderedProperties->OrderedDict ordered_dict = self.columns._data return (ordered_dict[key] for key in ordered_dict._list) def __len__(self): return len(self.columns._data) class CheckConstraint(ColumnCollectionConstraint): """A table- or column-level CHECK constraint. Can be included in the definition of a Table or Column. """ _allow_multiple_tables = True def __init__(self, sqltext, name=None, deferrable=None, initially=None, table=None, info=None, _create_rule=None, _autoattach=True, _type_bound=False): """Construct a CHECK constraint. :param sqltext: A string containing the constraint definition, which will be used verbatim, or a SQL expression construct. If given as a string, the object is converted to a :class:`.Text` object. If the textual string includes a colon character, escape this using a backslash:: CheckConstraint(r"foo ~ E'a(?\:b|c)d") :param name: Optional, the in-database name of the constraint. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint. :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. .. versionadded:: 1.0.0 """ self.sqltext = _literal_as_text(sqltext, warn=False) columns = [] visitors.traverse(self.sqltext, {}, {'column': columns.append}) super(CheckConstraint, self).\ __init__( name=name, deferrable=deferrable, initially=initially, _create_rule=_create_rule, info=info, _type_bound=_type_bound, _autoattach=_autoattach, *columns) if table is not None: self._set_parent_with_dispatch(table) def __visit_name__(self): if isinstance(self.parent, Table): return "check_constraint" else: return "column_check_constraint" __visit_name__ = property(__visit_name__) def copy(self, target_table=None, **kw): if target_table is not None: def replace(col): if self.table.c.contains_column(col): return target_table.c[col.key] else: return None sqltext = visitors.replacement_traverse(self.sqltext, {}, replace) else: sqltext = self.sqltext c = CheckConstraint(sqltext, name=self.name, initially=self.initially, deferrable=self.deferrable, _create_rule=self._create_rule, table=target_table, _autoattach=False, _type_bound=self._type_bound) return self._schema_item_copy(c) class ForeignKeyConstraint(ColumnCollectionConstraint): """A table-level FOREIGN KEY constraint. Defines a single column or composite FOREIGN KEY ... REFERENCES constraint. For a no-frills, single column foreign key, adding a :class:`.ForeignKey` to the definition of a :class:`.Column` is a shorthand equivalent for an unnamed, single column :class:`.ForeignKeyConstraint`. Examples of foreign key configuration are in :ref:`metadata_foreignkeys`. """ __visit_name__ = 'foreign_key_constraint' def __init__(self, columns, refcolumns, name=None, onupdate=None, ondelete=None, deferrable=None, initially=None, use_alter=False, link_to_name=False, match=None, table=None, info=None, **dialect_kw): """Construct a composite-capable FOREIGN KEY. :param columns: A sequence of local column names. The named columns must be defined and present in the parent Table. The names should match the ``key`` given to each column (defaults to the name) unless ``link_to_name`` is True. :param refcolumns: A sequence of foreign column names or Column objects. The columns must all be located within the same Table. :param name: Optional, the in-database name of the key. :param onupdate: Optional string. If set, emit ON UPDATE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT. :param ondelete: Optional string. If set, emit ON DELETE <value> when issuing DDL for this constraint. Typical values include CASCADE, DELETE and RESTRICT. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint. :param initially: Optional string. If set, emit INITIALLY <value> when issuing DDL for this constraint. :param link_to_name: if True, the string name given in ``column`` is the rendered name of the referenced column, not its locally assigned ``key``. :param use_alter: If True, do not emit the DDL for this constraint as part of the CREATE TABLE definition. Instead, generate it via an ALTER TABLE statement issued after the full collection of tables have been created, and drop it via an ALTER TABLE statement before the full collection of tables are dropped. The use of :paramref:`.ForeignKeyConstraint.use_alter` is particularly geared towards the case where two or more tables are established within a mutually-dependent foreign key constraint relationship; however, the :meth:`.MetaData.create_all` and :meth:`.MetaData.drop_all` methods will perform this resolution automatically, so the flag is normally not needed. .. versionchanged:: 1.0.0 Automatic resolution of foreign key cycles has been added, removing the need to use the :paramref:`.ForeignKeyConstraint.use_alter` in typical use cases. .. seealso:: :ref:`use_alter` :param match: Optional string. If set, emit MATCH <value> when issuing DDL for this constraint. Typical values include SIMPLE, PARTIAL and FULL. :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. .. versionadded:: 1.0.0 :param \**dialect_kw: Additional keyword arguments are dialect specific, and passed in the form ``<dialectname>_<argname>``. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. .. versionadded:: 0.9.2 """ Constraint.__init__( self, name=name, deferrable=deferrable, initially=initially, info=info, **dialect_kw) self.onupdate = onupdate self.ondelete = ondelete self.link_to_name = link_to_name self.use_alter = use_alter self.match = match # standalone ForeignKeyConstraint - create # associated ForeignKey objects which will be applied to hosted # Column objects (in col.foreign_keys), either now or when attached # to the Table for string-specified names self.elements = [ ForeignKey( refcol, _constraint=self, name=self.name, onupdate=self.onupdate, ondelete=self.ondelete, use_alter=self.use_alter, link_to_name=self.link_to_name, match=self.match, deferrable=self.deferrable, initially=self.initially, **self.dialect_kwargs ) for refcol in refcolumns ] ColumnCollectionMixin.__init__(self, *columns) if table is not None: if hasattr(self, "parent"): assert table is self.parent self._set_parent_with_dispatch(table) def _append_element(self, column, fk): self.columns.add(column) self.elements.append(fk) @property def _elements(self): # legacy - provide a dictionary view of (column_key, fk) return util.OrderedDict( zip(self.column_keys, self.elements) ) @property def _referred_schema(self): for elem in self.elements: return elem._referred_schema else: return None @property def referred_table(self): """The :class:`.Table` object to which this :class:`.ForeignKeyConstraint` references. This is a dynamically calculated attribute which may not be available if the constraint and/or parent table is not yet associated with a metadata collection that contains the referred table. .. versionadded:: 1.0.0 """ return self.elements[0].column.table def _validate_dest_table(self, table): table_keys = set([elem._table_key() for elem in self.elements]) if None not in table_keys and len(table_keys) > 1: elem0, elem1 = sorted(table_keys)[0:2] raise exc.ArgumentError( 'ForeignKeyConstraint on %s(%s) refers to ' 'multiple remote tables: %s and %s' % ( table.fullname, self._col_description, elem0, elem1 )) @property def column_keys(self): """Return a list of string keys representing the local columns in this :class:`.ForeignKeyConstraint`. This list is either the original string arguments sent to the constructor of the :class:`.ForeignKeyConstraint`, or if the constraint has been initialized with :class:`.Column` objects, is the string .key of each element. .. versionadded:: 1.0.0 """ if hasattr(self, "parent"): return self.columns.keys() else: return [ col.key if isinstance(col, ColumnElement) else str(col) for col in self._pending_colargs ] @property def _col_description(self): return ", ".join(self.column_keys) def _set_parent(self, table): Constraint._set_parent(self, table) try: ColumnCollectionConstraint._set_parent(self, table) except KeyError as ke: raise exc.ArgumentError( "Can't create ForeignKeyConstraint " "on table '%s': no column " "named '%s' is present." % (table.description, ke.args[0])) for col, fk in zip(self.columns, self.elements): if not hasattr(fk, 'parent') or \ fk.parent is not col: fk._set_parent_with_dispatch(col) self._validate_dest_table(table) def copy(self, schema=None, target_table=None, **kw): fkc = ForeignKeyConstraint( [x.parent.key for x in self.elements], [x._get_colspec( schema=schema, table_name=target_table.name if target_table is not None and x._table_key() == x.parent.table.key else None) for x in self.elements], name=self.name, onupdate=self.onupdate, ondelete=self.ondelete, use_alter=self.use_alter, deferrable=self.deferrable, initially=self.initially, link_to_name=self.link_to_name, match=self.match ) for self_fk, other_fk in zip( self.elements, fkc.elements): self_fk._schema_item_copy(other_fk) return self._schema_item_copy(fkc) class PrimaryKeyConstraint(ColumnCollectionConstraint): """A table-level PRIMARY KEY constraint. The :class:`.PrimaryKeyConstraint` object is present automatically on any :class:`.Table` object; it is assigned a set of :class:`.Column` objects corresponding to those marked with the :paramref:`.Column.primary_key` flag:: >>> my_table = Table('mytable', metadata, ... Column('id', Integer, primary_key=True), ... Column('version_id', Integer, primary_key=True), ... Column('data', String(50)) ... ) >>> my_table.primary_key PrimaryKeyConstraint( Column('id', Integer(), table=<mytable>, primary_key=True, nullable=False), Column('version_id', Integer(), table=<mytable>, primary_key=True, nullable=False) ) The primary key of a :class:`.Table` can also be specified by using a :class:`.PrimaryKeyConstraint` object explicitly; in this mode of usage, the "name" of the constraint can also be specified, as well as other options which may be recognized by dialects:: my_table = Table('mytable', metadata, Column('id', Integer), Column('version_id', Integer), Column('data', String(50)), PrimaryKeyConstraint('id', 'version_id', name='mytable_pk') ) The two styles of column-specification should generally not be mixed. An warning is emitted if the columns present in the :class:`.PrimaryKeyConstraint` don't match the columns that were marked as ``primary_key=True``, if both are present; in this case, the columns are taken strictly from the :class:`.PrimaryKeyConstraint` declaration, and those columns otherwise marked as ``primary_key=True`` are ignored. This behavior is intended to be backwards compatible with previous behavior. .. versionchanged:: 0.9.2 Using a mixture of columns within a :class:`.PrimaryKeyConstraint` in addition to columns marked as ``primary_key=True`` now emits a warning if the lists don't match. The ultimate behavior of ignoring those columns marked with the flag only is currently maintained for backwards compatibility; this warning may raise an exception in a future release. For the use case where specific options are to be specified on the :class:`.PrimaryKeyConstraint`, but the usual style of using ``primary_key=True`` flags is still desirable, an empty :class:`.PrimaryKeyConstraint` may be specified, which will take on the primary key column collection from the :class:`.Table` based on the flags:: my_table = Table('mytable', metadata, Column('id', Integer, primary_key=True), Column('version_id', Integer, primary_key=True), Column('data', String(50)), PrimaryKeyConstraint(name='mytable_pk', mssql_clustered=True) ) .. versionadded:: 0.9.2 an empty :class:`.PrimaryKeyConstraint` may now be specified for the purposes of establishing keyword arguments with the constraint, independently of the specification of "primary key" columns within the :class:`.Table` itself; columns marked as ``primary_key=True`` will be gathered into the empty constraint's column collection. """ __visit_name__ = 'primary_key_constraint' def _set_parent(self, table): super(PrimaryKeyConstraint, self)._set_parent(table) if table.primary_key is not self: table.constraints.discard(table.primary_key) table.primary_key = self table.constraints.add(self) table_pks = [c for c in table.c if c.primary_key] if self.columns and table_pks and \ set(table_pks) != set(self.columns.values()): util.warn( "Table '%s' specifies columns %s as primary_key=True, " "not matching locally specified columns %s; setting the " "current primary key columns to %s. This warning " "may become an exception in a future release" % ( table.name, ", ".join("'%s'" % c.name for c in table_pks), ", ".join("'%s'" % c.name for c in self.columns), ", ".join("'%s'" % c.name for c in self.columns) ) ) table_pks[:] = [] for c in self.columns: c.primary_key = True c.nullable = False self.columns.extend(table_pks) def _reload(self, columns): """repopulate this :class:`.PrimaryKeyConstraint` given a set of columns. Existing columns in the table that are marked as primary_key=True are maintained. Also fires a new event. This is basically like putting a whole new :class:`.PrimaryKeyConstraint` object on the parent :class:`.Table` object without actually replacing the object. The ordering of the given list of columns is also maintained; these columns will be appended to the list of columns after any which are already present. """ # set the primary key flag on new columns. # note any existing PK cols on the table also have their # flag still set. for col in columns: col.primary_key = True self.columns.extend(columns) self._set_parent_with_dispatch(self.table) def _replace(self, col): self.columns.replace(col) class UniqueConstraint(ColumnCollectionConstraint): """A table-level UNIQUE constraint. Defines a single column or composite UNIQUE constraint. For a no-frills, single column constraint, adding ``unique=True`` to the ``Column`` definition is a shorthand equivalent for an unnamed, single column UniqueConstraint. """ __visit_name__ = 'unique_constraint' class Index(DialectKWArgs, ColumnCollectionMixin, SchemaItem): """A table-level INDEX. Defines a composite (one or more column) INDEX. E.g.:: sometable = Table("sometable", metadata, Column("name", String(50)), Column("address", String(100)) ) Index("some_index", sometable.c.name) For a no-frills, single column index, adding :class:`.Column` also supports ``index=True``:: sometable = Table("sometable", metadata, Column("name", String(50), index=True) ) For a composite index, multiple columns can be specified:: Index("some_index", sometable.c.name, sometable.c.address) Functional indexes are supported as well, typically by using the :data:`.func` construct in conjunction with table-bound :class:`.Column` objects:: Index("some_index", func.lower(sometable.c.name)) .. versionadded:: 0.8 support for functional and expression-based indexes. An :class:`.Index` can also be manually associated with a :class:`.Table`, either through inline declaration or using :meth:`.Table.append_constraint`. When this approach is used, the names of the indexed columns can be specified as strings:: Table("sometable", metadata, Column("name", String(50)), Column("address", String(100)), Index("some_index", "name", "address") ) To support functional or expression-based indexes in this form, the :func:`.text` construct may be used:: from sqlalchemy import text Table("sometable", metadata, Column("name", String(50)), Column("address", String(100)), Index("some_index", text("lower(name)")) ) .. versionadded:: 0.9.5 the :func:`.text` construct may be used to specify :class:`.Index` expressions, provided the :class:`.Index` is explicitly associated with the :class:`.Table`. .. seealso:: :ref:`schema_indexes` - General information on :class:`.Index`. :ref:`postgresql_indexes` - PostgreSQL-specific options available for the :class:`.Index` construct. :ref:`mysql_indexes` - MySQL-specific options available for the :class:`.Index` construct. :ref:`mssql_indexes` - MSSQL-specific options available for the :class:`.Index` construct. """ __visit_name__ = 'index' def __init__(self, name, *expressions, **kw): """Construct an index object. :param name: The name of the index :param \*expressions: Column expressions to include in the index. The expressions are normally instances of :class:`.Column`, but may also be arbitrary SQL expressions which ultimately refer to a :class:`.Column`. :param unique=False: Keyword only argument; if True, create a unique index. :param quote=None: Keyword only argument; whether to apply quoting to the name of the index. Works in the same manner as that of :paramref:`.Column.quote`. :param info=None: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. .. versionadded:: 1.0.0 :param \**kw: Additional keyword arguments not mentioned above are dialect specific, and passed in the form ``<dialectname>_<argname>``. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. """ self.table = None columns = [] for expr, column, strname, add_element in self.\ _extract_col_expression_collection(expressions): if add_element is not None: columns.append(add_element) self.expressions = expressions self.name = quoted_name(name, kw.pop("quote", None)) self.unique = kw.pop('unique', False) if 'info' in kw: self.info = kw.pop('info') self._validate_dialect_kwargs(kw) # will call _set_parent() if table-bound column # objects are present ColumnCollectionMixin.__init__(self, *columns) def _set_parent(self, table): ColumnCollectionMixin._set_parent(self, table) if self.table is not None and table is not self.table: raise exc.ArgumentError( "Index '%s' is against table '%s', and " "cannot be associated with table '%s'." % ( self.name, self.table.description, table.description ) ) self.table = table table.indexes.add(self) self.expressions = [ expr if isinstance(expr, ClauseElement) else colexpr for expr, colexpr in util.zip_longest(self.expressions, self.columns) ] @property def bind(self): """Return the connectable associated with this Index.""" return self.table.bind def create(self, bind=None): """Issue a ``CREATE`` statement for this :class:`.Index`, using the given :class:`.Connectable` for connectivity. .. seealso:: :meth:`.MetaData.create_all`. """ if bind is None: bind = _bind_or_error(self) bind._run_visitor(ddl.SchemaGenerator, self) return self def drop(self, bind=None): """Issue a ``DROP`` statement for this :class:`.Index`, using the given :class:`.Connectable` for connectivity. .. seealso:: :meth:`.MetaData.drop_all`. """ if bind is None: bind = _bind_or_error(self) bind._run_visitor(ddl.SchemaDropper, self) def __repr__(self): return 'Index(%s)' % ( ", ".join( [repr(self.name)] + [repr(e) for e in self.expressions] + (self.unique and ["unique=True"] or []) )) DEFAULT_NAMING_CONVENTION = util.immutabledict({ "ix": 'ix_%(column_0_label)s' }) class MetaData(SchemaItem): """A collection of :class:`.Table` objects and their associated schema constructs. Holds a collection of :class:`.Table` objects as well as an optional binding to an :class:`.Engine` or :class:`.Connection`. If bound, the :class:`.Table` objects in the collection and their columns may participate in implicit SQL execution. The :class:`.Table` objects themselves are stored in the :attr:`.MetaData.tables` dictionary. :class:`.MetaData` is a thread-safe object for read operations. Construction of new tables within a single :class:`.MetaData` object, either explicitly or via reflection, may not be completely thread-safe. .. seealso:: :ref:`metadata_describing` - Introduction to database metadata """ __visit_name__ = 'metadata' def __init__(self, bind=None, reflect=False, schema=None, quote_schema=None, naming_convention=DEFAULT_NAMING_CONVENTION, info=None ): """Create a new MetaData object. :param bind: An Engine or Connection to bind to. May also be a string or URL instance, these are passed to create_engine() and this MetaData will be bound to the resulting engine. :param reflect: Optional, automatically load all tables from the bound database. Defaults to False. ``bind`` is required when this option is set. .. deprecated:: 0.8 Please use the :meth:`.MetaData.reflect` method. :param schema: The default schema to use for the :class:`.Table`, :class:`.Sequence`, and other objects associated with this :class:`.MetaData`. Defaults to ``None``. :param quote_schema: Sets the ``quote_schema`` flag for those :class:`.Table`, :class:`.Sequence`, and other objects which make usage of the local ``schema`` name. :param info: Optional data dictionary which will be populated into the :attr:`.SchemaItem.info` attribute of this object. .. versionadded:: 1.0.0 :param naming_convention: a dictionary referring to values which will establish default naming conventions for :class:`.Constraint` and :class:`.Index` objects, for those objects which are not given a name explicitly. The keys of this dictionary may be: * a constraint or Index class, e.g. the :class:`.UniqueConstraint`, :class:`.ForeignKeyConstraint` class, the :class:`.Index` class * a string mnemonic for one of the known constraint classes; ``"fk"``, ``"pk"``, ``"ix"``, ``"ck"``, ``"uq"`` for foreign key, primary key, index, check, and unique constraint, respectively. * the string name of a user-defined "token" that can be used to define new naming tokens. The values associated with each "constraint class" or "constraint mnemonic" key are string naming templates, such as ``"uq_%(table_name)s_%(column_0_name)s"``, which describe how the name should be composed. The values associated with user-defined "token" keys should be callables of the form ``fn(constraint, table)``, which accepts the constraint/index object and :class:`.Table` as arguments, returning a string result. The built-in names are as follows, some of which may only be available for certain types of constraint: * ``%(table_name)s`` - the name of the :class:`.Table` object associated with the constraint. * ``%(referred_table_name)s`` - the name of the :class:`.Table` object associated with the referencing target of a :class:`.ForeignKeyConstraint`. * ``%(column_0_name)s`` - the name of the :class:`.Column` at index position "0" within the constraint. * ``%(column_0_label)s`` - the label of the :class:`.Column` at index position "0", e.g. :attr:`.Column.label` * ``%(column_0_key)s`` - the key of the :class:`.Column` at index position "0", e.g. :attr:`.Column.key` * ``%(referred_column_0_name)s`` - the name of a :class:`.Column` at index position "0" referenced by a :class:`.ForeignKeyConstraint`. * ``%(constraint_name)s`` - a special key that refers to the existing name given to the constraint. When this key is present, the :class:`.Constraint` object's existing name will be replaced with one that is composed from template string that uses this token. When this token is present, it is required that the :class:`.Constraint` is given an expicit name ahead of time. * user-defined: any additional token may be implemented by passing it along with a ``fn(constraint, table)`` callable to the naming_convention dictionary. .. versionadded:: 0.9.2 .. seealso:: :ref:`constraint_naming_conventions` - for detailed usage examples. """ self.tables = util.immutabledict() self.schema = quoted_name(schema, quote_schema) self.naming_convention = naming_convention if info: self.info = info self._schemas = set() self._sequences = {} self._fk_memos = collections.defaultdict(list) self.bind = bind if reflect: util.warn_deprecated("reflect=True is deprecate; please " "use the reflect() method.") if not bind: raise exc.ArgumentError( "A bind must be supplied in conjunction " "with reflect=True") self.reflect() tables = None """A dictionary of :class:`.Table` objects keyed to their name or "table key". The exact key is that determined by the :attr:`.Table.key` attribute; for a table with no :attr:`.Table.schema` attribute, this is the same as :attr:`.Table.name`. For a table with a schema, it is typically of the form ``schemaname.tablename``. .. seealso:: :attr:`.MetaData.sorted_tables` """ def __repr__(self): return 'MetaData(bind=%r)' % self.bind def __contains__(self, table_or_key): if not isinstance(table_or_key, util.string_types): table_or_key = table_or_key.key return table_or_key in self.tables def _add_table(self, name, schema, table): key = _get_table_key(name, schema) dict.__setitem__(self.tables, key, table) if schema: self._schemas.add(schema) def _remove_table(self, name, schema): key = _get_table_key(name, schema) removed = dict.pop(self.tables, key, None) if removed is not None: for fk in removed.foreign_keys: fk._remove_from_metadata(self) if self._schemas: self._schemas = set([t.schema for t in self.tables.values() if t.schema is not None]) def __getstate__(self): return {'tables': self.tables, 'schema': self.schema, 'schemas': self._schemas, 'sequences': self._sequences, 'fk_memos': self._fk_memos, 'naming_convention': self.naming_convention } def __setstate__(self, state): self.tables = state['tables'] self.schema = state['schema'] self.naming_convention = state['naming_convention'] self._bind = None self._sequences = state['sequences'] self._schemas = state['schemas'] self._fk_memos = state['fk_memos'] def is_bound(self): """True if this MetaData is bound to an Engine or Connection.""" return self._bind is not None def bind(self): """An :class:`.Engine` or :class:`.Connection` to which this :class:`.MetaData` is bound. Typically, a :class:`.Engine` is assigned to this attribute so that "implicit execution" may be used, or alternatively as a means of providing engine binding information to an ORM :class:`.Session` object:: engine = create_engine("someurl://") metadata.bind = engine .. seealso:: :ref:`dbengine_implicit` - background on "bound metadata" """ return self._bind @util.dependencies("sqlalchemy.engine.url") def _bind_to(self, url, bind): """Bind this MetaData to an Engine, Connection, string or URL.""" if isinstance(bind, util.string_types + (url.URL, )): self._bind = sqlalchemy.create_engine(bind) else: self._bind = bind bind = property(bind, _bind_to) def clear(self): """Clear all Table objects from this MetaData.""" dict.clear(self.tables) self._schemas.clear() self._fk_memos.clear() def remove(self, table): """Remove the given Table object from this MetaData.""" self._remove_table(table.name, table.schema) @property def sorted_tables(self): """Returns a list of :class:`.Table` objects sorted in order of foreign key dependency. The sorting will place :class:`.Table` objects that have dependencies first, before the dependencies themselves, representing the order in which they can be created. To get the order in which the tables would be dropped, use the ``reversed()`` Python built-in. .. warning:: The :attr:`.sorted_tables` accessor cannot by itself accommodate automatic resolution of dependency cycles between tables, which are usually caused by mutually dependent foreign key constraints. To resolve these cycles, either the :paramref:`.ForeignKeyConstraint.use_alter` parameter may be appled to those constraints, or use the :func:`.schema.sort_tables_and_constraints` function which will break out foreign key constraints involved in cycles separately. .. seealso:: :func:`.schema.sort_tables` :func:`.schema.sort_tables_and_constraints` :attr:`.MetaData.tables` :meth:`.Inspector.get_table_names` :meth:`.Inspector.get_sorted_table_and_fkc_names` """ return ddl.sort_tables(sorted(self.tables.values(), key=lambda t: t.key)) def reflect(self, bind=None, schema=None, views=False, only=None, extend_existing=False, autoload_replace=True, **dialect_kwargs): """Load all available table definitions from the database. Automatically creates ``Table`` entries in this ``MetaData`` for any table available in the database but not yet present in the ``MetaData``. May be called multiple times to pick up tables recently added to the database, however no special action is taken if a table in this ``MetaData`` no longer exists in the database. :param bind: A :class:`.Connectable` used to access the database; if None, uses the existing bind on this ``MetaData``, if any. :param schema: Optional, query and reflect tables from an alterate schema. If None, the schema associated with this :class:`.MetaData` is used, if any. :param views: If True, also reflect views. :param only: Optional. Load only a sub-set of available named tables. May be specified as a sequence of names or a callable. If a sequence of names is provided, only those tables will be reflected. An error is raised if a table is requested but not available. Named tables already present in this ``MetaData`` are ignored. If a callable is provided, it will be used as a boolean predicate to filter the list of potential table names. The callable is called with a table name and this ``MetaData`` instance as positional arguments and should return a true value for any table to reflect. :param extend_existing: Passed along to each :class:`.Table` as :paramref:`.Table.extend_existing`. .. versionadded:: 0.9.1 :param autoload_replace: Passed along to each :class:`.Table` as :paramref:`.Table.autoload_replace`. .. versionadded:: 0.9.1 :param \**dialect_kwargs: Additional keyword arguments not mentioned above are dialect specific, and passed in the form ``<dialectname>_<argname>``. See the documentation regarding an individual dialect at :ref:`dialect_toplevel` for detail on documented arguments. .. versionadded:: 0.9.2 - Added :paramref:`.MetaData.reflect.**dialect_kwargs` to support dialect-level reflection options for all :class:`.Table` objects reflected. """ if bind is None: bind = _bind_or_error(self) with bind.connect() as conn: reflect_opts = { 'autoload': True, 'autoload_with': conn, 'extend_existing': extend_existing, 'autoload_replace': autoload_replace } reflect_opts.update(dialect_kwargs) if schema is None: schema = self.schema if schema is not None: reflect_opts['schema'] = schema available = util.OrderedSet( bind.engine.table_names(schema, connection=conn)) if views: available.update( bind.dialect.get_view_names(conn, schema) ) if schema is not None: available_w_schema = util.OrderedSet(["%s.%s" % (schema, name) for name in available]) else: available_w_schema = available current = set(self.tables) if only is None: load = [name for name, schname in zip(available, available_w_schema) if extend_existing or schname not in current] elif util.callable(only): load = [name for name, schname in zip(available, available_w_schema) if (extend_existing or schname not in current) and only(name, self)] else: missing = [name for name in only if name not in available] if missing: s = schema and (" schema '%s'" % schema) or '' raise exc.InvalidRequestError( 'Could not reflect: requested table(s) not available ' 'in %s%s: (%s)' % (bind.engine.url, s, ', '.join(missing))) load = [name for name in only if extend_existing or name not in current] for name in load: Table(name, self, **reflect_opts) def append_ddl_listener(self, event_name, listener): """Append a DDL event listener to this ``MetaData``. .. deprecated:: 0.7 See :class:`.DDLEvents`. """ def adapt_listener(target, connection, **kw): tables = kw['tables'] listener(event, target, connection, tables=tables) event.listen(self, "" + event_name.replace('-', '_'), adapt_listener) def create_all(self, bind=None, tables=None, checkfirst=True): """Create all tables stored in this metadata. Conditional by default, will not attempt to recreate tables already present in the target database. :param bind: A :class:`.Connectable` used to access the database; if None, uses the existing bind on this ``MetaData``, if any. :param tables: Optional list of ``Table`` objects, which is a subset of the total tables in the ``MetaData`` (others are ignored). :param checkfirst: Defaults to True, don't issue CREATEs for tables already present in the target database. """ if bind is None: bind = _bind_or_error(self) bind._run_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst, tables=tables) def drop_all(self, bind=None, tables=None, checkfirst=True): """Drop all tables stored in this metadata. Conditional by default, will not attempt to drop tables not present in the target database. :param bind: A :class:`.Connectable` used to access the database; if None, uses the existing bind on this ``MetaData``, if any. :param tables: Optional list of ``Table`` objects, which is a subset of the total tables in the ``MetaData`` (others are ignored). :param checkfirst: Defaults to True, only issue DROPs for tables confirmed to be present in the target database. """ if bind is None: bind = _bind_or_error(self) bind._run_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst, tables=tables) class ThreadLocalMetaData(MetaData): """A MetaData variant that presents a different ``bind`` in every thread. Makes the ``bind`` property of the MetaData a thread-local value, allowing this collection of tables to be bound to different ``Engine`` implementations or connections in each thread. The ThreadLocalMetaData starts off bound to None in each thread. Binds must be made explicitly by assigning to the ``bind`` property or using ``connect()``. You can also re-bind dynamically multiple times per thread, just like a regular ``MetaData``. """ __visit_name__ = 'metadata' def __init__(self): """Construct a ThreadLocalMetaData.""" self.context = util.threading.local() self.__engines = {} super(ThreadLocalMetaData, self).__init__() def bind(self): """The bound Engine or Connection for this thread. This property may be assigned an Engine or Connection, or assigned a string or URL to automatically create a basic Engine for this bind with ``create_engine()``.""" return getattr(self.context, '_engine', None) @util.dependencies("sqlalchemy.engine.url") def _bind_to(self, url, bind): """Bind to a Connectable in the caller's thread.""" if isinstance(bind, util.string_types + (url.URL, )): try: self.context._engine = self.__engines[bind] except KeyError: e = sqlalchemy.create_engine(bind) self.__engines[bind] = e self.context._engine = e else: # TODO: this is squirrely. we shouldn't have to hold onto engines # in a case like this if bind not in self.__engines: self.__engines[bind] = bind self.context._engine = bind bind = property(bind, _bind_to) def is_bound(self): """True if there is a bind for this thread.""" return (hasattr(self.context, '_engine') and self.context._engine is not None) def dispose(self): """Dispose all bound engines, in all thread contexts.""" for e in self.__engines.values(): if hasattr(e, 'dispose'): e.dispose()
hatwar/focal-erpnext
refs/heads/develop
erpnext/accounts/doctype/payment_to_invoice_matching_tool/test_payment_to_invoice_matching_tool.py
8
# 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 unittest import frappe test_records = frappe.get_test_records('Payment To Invoice Matching Tool')
openstack/python-openstacksdk
refs/heads/master
openstack/tests/unit/orchestration/v1/test_proxy.py
1
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from testscenarios import load_tests_apply_scenarios as load_tests # noqa import mock import six from openstack import exceptions from openstack.orchestration.v1 import _proxy from openstack.orchestration.v1 import resource from openstack.orchestration.v1 import software_config as sc from openstack.orchestration.v1 import software_deployment as sd from openstack.orchestration.v1 import stack from openstack.orchestration.v1 import stack_environment from openstack.orchestration.v1 import stack_files from openstack.orchestration.v1 import stack_template from openstack.orchestration.v1 import template from openstack.tests.unit import test_proxy_base class TestOrchestrationProxy(test_proxy_base.TestProxyBase): def setUp(self): super(TestOrchestrationProxy, self).setUp() self.proxy = _proxy.Proxy(self.session) def test_create_stack(self): self.verify_create(self.proxy.create_stack, stack.Stack) def test_create_stack_preview(self): method_kwargs = {"preview": True, "x": 1, "y": 2, "z": 3} self.verify_create(self.proxy.create_stack, stack.Stack, method_kwargs=method_kwargs) def test_find_stack(self): self.verify_find(self.proxy.find_stack, stack.Stack, expected_kwargs={'resolve_outputs': True}) # mock_method="openstack.proxy.Proxy._find" # test_method=self.proxy.find_stack # method_kwargs = { # 'resolve_outputs': False, # 'ignore_missing': False # } # method_args=["name_or_id"] # self._verify2(mock_method, test_method, # method_args=method_args, # method_kwargs=method_kwargs, # expected_args=[stack.Stack, "name_or_id"], # expected_kwargs=method_kwargs, # expected_result="result") # # method_kwargs = { # 'resolve_outputs': True, # 'ignore_missing': True # } # self._verify2(mock_method, test_method, # method_args=method_args, # method_kwargs=method_kwargs, # expected_args=[stack.Stack, "name_or_id"], # expected_kwargs=method_kwargs, # expected_result="result") def test_stacks(self): self.verify_list(self.proxy.stacks, stack.Stack) def test_get_stack(self): self.verify_get(self.proxy.get_stack, stack.Stack, method_kwargs={'resolve_outputs': False}, expected_kwargs={'resolve_outputs': False}) self.verify_get_overrided( self.proxy, stack.Stack, 'openstack.orchestration.v1.stack.Stack') def test_update_stack(self): self._verify2('openstack.orchestration.v1.stack.Stack.update', self.proxy.update_stack, expected_result='result', method_args=['stack'], method_kwargs={'preview': False}, expected_args=[self.proxy, False]) def test_update_stack_preview(self): self._verify2('openstack.orchestration.v1.stack.Stack.update', self.proxy.update_stack, expected_result='result', method_args=['stack'], method_kwargs={'preview': True}, expected_args=[self.proxy, True]) def test_abandon_stack(self): self._verify2('openstack.orchestration.v1.stack.Stack.abandon', self.proxy.abandon_stack, expected_result='result', method_args=['stack'], expected_args=[self.proxy]) def test_delete_stack(self): self.verify_delete(self.proxy.delete_stack, stack.Stack, False) def test_delete_stack_ignore(self): self.verify_delete(self.proxy.delete_stack, stack.Stack, True) @mock.patch.object(stack.Stack, 'check') def test_check_stack_with_stack_object(self, mock_check): stk = stack.Stack(id='FAKE_ID') res = self.proxy.check_stack(stk) self.assertIsNone(res) mock_check.assert_called_once_with(self.proxy) @mock.patch.object(stack.Stack, 'existing') def test_check_stack_with_stack_ID(self, mock_stack): stk = mock.Mock() mock_stack.return_value = stk res = self.proxy.check_stack('FAKE_ID') self.assertIsNone(res) mock_stack.assert_called_once_with(id='FAKE_ID') stk.check.assert_called_once_with(self.proxy) @mock.patch.object(stack.Stack, 'find') def test_get_stack_environment_with_stack_identity(self, mock_find): stack_id = '1234' stack_name = 'test_stack' stk = stack.Stack(id=stack_id, name=stack_name) mock_find.return_value = stk self._verify2('openstack.proxy.Proxy._get', self.proxy.get_stack_environment, method_args=['IDENTITY'], expected_args=[stack_environment.StackEnvironment], expected_kwargs={'requires_id': False, 'stack_name': stack_name, 'stack_id': stack_id}) mock_find.assert_called_once_with(mock.ANY, 'IDENTITY', ignore_missing=False) def test_get_stack_environment_with_stack_object(self): stack_id = '1234' stack_name = 'test_stack' stk = stack.Stack(id=stack_id, name=stack_name) self._verify2('openstack.proxy.Proxy._get', self.proxy.get_stack_environment, method_args=[stk], expected_args=[stack_environment.StackEnvironment], expected_kwargs={'requires_id': False, 'stack_name': stack_name, 'stack_id': stack_id}) @mock.patch.object(stack_files.StackFiles, 'fetch') @mock.patch.object(stack.Stack, 'find') def test_get_stack_files_with_stack_identity(self, mock_find, mock_fetch): stack_id = '1234' stack_name = 'test_stack' stk = stack.Stack(id=stack_id, name=stack_name) mock_find.return_value = stk mock_fetch.return_value = {'file': 'content'} res = self.proxy.get_stack_files('IDENTITY') self.assertEqual({'file': 'content'}, res) mock_find.assert_called_once_with(mock.ANY, 'IDENTITY', ignore_missing=False) mock_fetch.assert_called_once_with(self.proxy) @mock.patch.object(stack_files.StackFiles, 'fetch') def test_get_stack_files_with_stack_object(self, mock_fetch): stack_id = '1234' stack_name = 'test_stack' stk = stack.Stack(id=stack_id, name=stack_name) mock_fetch.return_value = {'file': 'content'} res = self.proxy.get_stack_files(stk) self.assertEqual({'file': 'content'}, res) mock_fetch.assert_called_once_with(self.proxy) @mock.patch.object(stack.Stack, 'find') def test_get_stack_template_with_stack_identity(self, mock_find): stack_id = '1234' stack_name = 'test_stack' stk = stack.Stack(id=stack_id, name=stack_name) mock_find.return_value = stk self._verify2('openstack.proxy.Proxy._get', self.proxy.get_stack_template, method_args=['IDENTITY'], expected_args=[stack_template.StackTemplate], expected_kwargs={'requires_id': False, 'stack_name': stack_name, 'stack_id': stack_id}) mock_find.assert_called_once_with(mock.ANY, 'IDENTITY', ignore_missing=False) def test_get_stack_template_with_stack_object(self): stack_id = '1234' stack_name = 'test_stack' stk = stack.Stack(id=stack_id, name=stack_name) self._verify2('openstack.proxy.Proxy._get', self.proxy.get_stack_template, method_args=[stk], expected_args=[stack_template.StackTemplate], expected_kwargs={'requires_id': False, 'stack_name': stack_name, 'stack_id': stack_id}) @mock.patch.object(stack.Stack, 'find') def test_resources_with_stack_object(self, mock_find): stack_id = '1234' stack_name = 'test_stack' stk = stack.Stack(id=stack_id, name=stack_name) self.verify_list(self.proxy.resources, resource.Resource, method_args=[stk], expected_kwargs={'stack_name': stack_name, 'stack_id': stack_id}) self.assertEqual(0, mock_find.call_count) @mock.patch.object(stack.Stack, 'find') def test_resources_with_stack_name(self, mock_find): stack_id = '1234' stack_name = 'test_stack' stk = stack.Stack(id=stack_id, name=stack_name) mock_find.return_value = stk self.verify_list(self.proxy.resources, resource.Resource, method_args=[stack_id], expected_kwargs={'stack_name': stack_name, 'stack_id': stack_id}) mock_find.assert_called_once_with(mock.ANY, stack_id, ignore_missing=False) @mock.patch.object(stack.Stack, 'find') @mock.patch.object(resource.Resource, 'list') def test_resources_stack_not_found(self, mock_list, mock_find): stack_name = 'test_stack' mock_find.side_effect = exceptions.ResourceNotFound( 'No stack found for test_stack') ex = self.assertRaises(exceptions.ResourceNotFound, self.proxy.resources, stack_name) self.assertEqual('No stack found for test_stack', six.text_type(ex)) def test_create_software_config(self): self.verify_create(self.proxy.create_software_config, sc.SoftwareConfig) def test_software_configs(self): self.verify_list(self.proxy.software_configs, sc.SoftwareConfig) def test_get_software_config(self): self.verify_get(self.proxy.get_software_config, sc.SoftwareConfig) def test_delete_software_config(self): self.verify_delete(self.proxy.delete_software_config, sc.SoftwareConfig, True) self.verify_delete(self.proxy.delete_software_config, sc.SoftwareConfig, False) def test_create_software_deployment(self): self.verify_create(self.proxy.create_software_deployment, sd.SoftwareDeployment) def test_software_deployments(self): self.verify_list(self.proxy.software_deployments, sd.SoftwareDeployment) def test_get_software_deployment(self): self.verify_get(self.proxy.get_software_deployment, sd.SoftwareDeployment) def test_update_software_deployment(self): self.verify_update(self.proxy.update_software_deployment, sd.SoftwareDeployment) def test_delete_software_deployment(self): self.verify_delete(self.proxy.delete_software_deployment, sd.SoftwareDeployment, True) self.verify_delete(self.proxy.delete_software_deployment, sd.SoftwareDeployment, False) @mock.patch.object(template.Template, 'validate') def test_validate_template(self, mock_validate): tmpl = mock.Mock() env = mock.Mock() tmpl_url = 'A_URI' ignore_errors = 'a_string' res = self.proxy.validate_template(tmpl, env, tmpl_url, ignore_errors) mock_validate.assert_called_once_with( self.proxy, tmpl, environment=env, template_url=tmpl_url, ignore_errors=ignore_errors) self.assertEqual(mock_validate.return_value, res) def test_validate_template_no_env(self): tmpl = "openstack/tests/unit/orchestration/v1/hello_world.yaml" res = self.proxy.read_env_and_templates(tmpl) self.assertIsInstance(res, dict) self.assertIsInstance(res["files"], dict) def test_validate_template_invalid_request(self): err = self.assertRaises(exceptions.InvalidRequest, self.proxy.validate_template, None, template_url=None) self.assertEqual("'template_url' must be specified when template is " "None", six.text_type(err)) class TestExtractName(TestOrchestrationProxy): scenarios = [ ('stacks', dict(url='/stacks', parts=['stacks'])), ('name_id', dict(url='/stacks/name/id', parts=['stack'])), ('identity', dict(url='/stacks/id', parts=['stack'])), ('preview', dict(url='/stacks/name/preview', parts=['stack', 'preview'])), ('stack_act', dict(url='/stacks/name/id/preview', parts=['stack', 'preview'])), ('stack_subres', dict(url='/stacks/name/id/resources', parts=['stack', 'resources'])), ('stack_subres_id', dict(url='/stacks/name/id/resources/id', parts=['stack', 'resource'])), ('stack_subres_id_act', dict(url='/stacks/name/id/resources/id/action', parts=['stack', 'resource', 'action'])), ('event', dict(url='/stacks/ignore/ignore/resources/ignore/events/id', parts=['stack', 'resource', 'event'])), ('sd_metadata', dict(url='/software_deployments/metadata/ignore', parts=['software_deployment', 'metadata'])) ] def test_extract_name(self): results = self.proxy._extract_name(self.url) self.assertEqual(self.parts, results)
uw-it-aca/django-blti
refs/heads/main
blti/performance.py
1
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 import time from logging import getLogger from blti import BLTI logger = getLogger(__name__) def log_response_time(func): def wrapper(*args, **kwargs): self = args[0] start = time.time() try: val = func(*args, **kwargs) except Exception: raise finally: module = self.__module__ function = func.__name__ is_view_class = True if module == "django.core.handlers.wsgi": is_view_class = False if is_view_class: arg_str = str(args[2:]) else: arg_str = str(args[1:]) kw_str = str(kwargs) end = time.time() try: request = args[1] login_id = BLTI().get_session(request).get( 'custom_canvas_user_login_id') except Exception as ex: login_id = None arg_str = arg_str.replace("#", "___") kw_str = kw_str.replace("#", "___") logger.info( 'user: {}, method: {}.{}, args: {}, kwargs: {}, ' 'time: {}'.format( login_id, module, function, arg_str, kw_str, end - start)) return val return wrapper
danielvdao/TheAnimalFarm
refs/heads/master
venv/lib/python2.7/site-packages/jinja2/testsuite/loader.py
411
# -*- coding: utf-8 -*- """ jinja2.testsuite.loader ~~~~~~~~~~~~~~~~~~~~~~~ Test the loaders. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import os import sys import tempfile import shutil import unittest from jinja2.testsuite import JinjaTestCase, dict_loader, \ package_loader, filesystem_loader, function_loader, \ choice_loader, prefix_loader from jinja2 import Environment, loaders from jinja2._compat import PYPY, PY2 from jinja2.loaders import split_template_path from jinja2.exceptions import TemplateNotFound class LoaderTestCase(JinjaTestCase): def test_dict_loader(self): env = Environment(loader=dict_loader) tmpl = env.get_template('justdict.html') assert tmpl.render().strip() == 'FOO' self.assert_raises(TemplateNotFound, env.get_template, 'missing.html') def test_package_loader(self): env = Environment(loader=package_loader) tmpl = env.get_template('test.html') assert tmpl.render().strip() == 'BAR' self.assert_raises(TemplateNotFound, env.get_template, 'missing.html') def test_filesystem_loader(self): env = Environment(loader=filesystem_loader) tmpl = env.get_template('test.html') assert tmpl.render().strip() == 'BAR' tmpl = env.get_template('foo/test.html') assert tmpl.render().strip() == 'FOO' self.assert_raises(TemplateNotFound, env.get_template, 'missing.html') def test_choice_loader(self): env = Environment(loader=choice_loader) tmpl = env.get_template('justdict.html') assert tmpl.render().strip() == 'FOO' tmpl = env.get_template('test.html') assert tmpl.render().strip() == 'BAR' self.assert_raises(TemplateNotFound, env.get_template, 'missing.html') def test_function_loader(self): env = Environment(loader=function_loader) tmpl = env.get_template('justfunction.html') assert tmpl.render().strip() == 'FOO' self.assert_raises(TemplateNotFound, env.get_template, 'missing.html') def test_prefix_loader(self): env = Environment(loader=prefix_loader) tmpl = env.get_template('a/test.html') assert tmpl.render().strip() == 'BAR' tmpl = env.get_template('b/justdict.html') assert tmpl.render().strip() == 'FOO' self.assert_raises(TemplateNotFound, env.get_template, 'missing') def test_caching(self): changed = False class TestLoader(loaders.BaseLoader): def get_source(self, environment, template): return u'foo', None, lambda: not changed env = Environment(loader=TestLoader(), cache_size=-1) tmpl = env.get_template('template') assert tmpl is env.get_template('template') changed = True assert tmpl is not env.get_template('template') changed = False env = Environment(loader=TestLoader(), cache_size=0) assert env.get_template('template') \ is not env.get_template('template') env = Environment(loader=TestLoader(), cache_size=2) t1 = env.get_template('one') t2 = env.get_template('two') assert t2 is env.get_template('two') assert t1 is env.get_template('one') t3 = env.get_template('three') assert 'one' in env.cache assert 'two' not in env.cache assert 'three' in env.cache def test_dict_loader_cache_invalidates(self): mapping = {'foo': "one"} env = Environment(loader=loaders.DictLoader(mapping)) assert env.get_template('foo').render() == "one" mapping['foo'] = "two" assert env.get_template('foo').render() == "two" def test_split_template_path(self): assert split_template_path('foo/bar') == ['foo', 'bar'] assert split_template_path('./foo/bar') == ['foo', 'bar'] self.assert_raises(TemplateNotFound, split_template_path, '../foo') class ModuleLoaderTestCase(JinjaTestCase): archive = None def compile_down(self, zip='deflated', py_compile=False): super(ModuleLoaderTestCase, self).setup() log = [] self.reg_env = Environment(loader=prefix_loader) if zip is not None: self.archive = tempfile.mkstemp(suffix='.zip')[1] else: self.archive = tempfile.mkdtemp() self.reg_env.compile_templates(self.archive, zip=zip, log_function=log.append, py_compile=py_compile) self.mod_env = Environment(loader=loaders.ModuleLoader(self.archive)) return ''.join(log) def teardown(self): super(ModuleLoaderTestCase, self).teardown() if hasattr(self, 'mod_env'): if os.path.isfile(self.archive): os.remove(self.archive) else: shutil.rmtree(self.archive) self.archive = None def test_log(self): log = self.compile_down() assert 'Compiled "a/foo/test.html" as ' \ 'tmpl_a790caf9d669e39ea4d280d597ec891c4ef0404a' in log assert 'Finished compiling templates' in log assert 'Could not compile "a/syntaxerror.html": ' \ 'Encountered unknown tag \'endif\'' in log def _test_common(self): tmpl1 = self.reg_env.get_template('a/test.html') tmpl2 = self.mod_env.get_template('a/test.html') assert tmpl1.render() == tmpl2.render() tmpl1 = self.reg_env.get_template('b/justdict.html') tmpl2 = self.mod_env.get_template('b/justdict.html') assert tmpl1.render() == tmpl2.render() def test_deflated_zip_compile(self): self.compile_down(zip='deflated') self._test_common() def test_stored_zip_compile(self): self.compile_down(zip='stored') self._test_common() def test_filesystem_compile(self): self.compile_down(zip=None) self._test_common() def test_weak_references(self): self.compile_down() tmpl = self.mod_env.get_template('a/test.html') key = loaders.ModuleLoader.get_template_key('a/test.html') name = self.mod_env.loader.module.__name__ assert hasattr(self.mod_env.loader.module, key) assert name in sys.modules # unset all, ensure the module is gone from sys.modules self.mod_env = tmpl = None try: import gc gc.collect() except: pass assert name not in sys.modules # This test only makes sense on non-pypy python 2 if PY2 and not PYPY: def test_byte_compilation(self): log = self.compile_down(py_compile=True) assert 'Byte-compiled "a/test.html"' in log tmpl1 = self.mod_env.get_template('a/test.html') mod = self.mod_env.loader.module. \ tmpl_3c4ddf650c1a73df961a6d3d2ce2752f1b8fd490 assert mod.__file__.endswith('.pyc') def test_choice_loader(self): log = self.compile_down() self.mod_env.loader = loaders.ChoiceLoader([ self.mod_env.loader, loaders.DictLoader({'DICT_SOURCE': 'DICT_TEMPLATE'}) ]) tmpl1 = self.mod_env.get_template('a/test.html') self.assert_equal(tmpl1.render(), 'BAR') tmpl2 = self.mod_env.get_template('DICT_SOURCE') self.assert_equal(tmpl2.render(), 'DICT_TEMPLATE') def test_prefix_loader(self): log = self.compile_down() self.mod_env.loader = loaders.PrefixLoader({ 'MOD': self.mod_env.loader, 'DICT': loaders.DictLoader({'test.html': 'DICT_TEMPLATE'}) }) tmpl1 = self.mod_env.get_template('MOD/a/test.html') self.assert_equal(tmpl1.render(), 'BAR') tmpl2 = self.mod_env.get_template('DICT/test.html') self.assert_equal(tmpl2.render(), 'DICT_TEMPLATE') def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(LoaderTestCase)) suite.addTest(unittest.makeSuite(ModuleLoaderTestCase)) return suite
versatica/mediasoup
refs/heads/v3
worker/deps/gyp/test/win/gyptest-link-fixed-base.py
344
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Make sure fixed base setting is extracted properly. """ import TestGyp import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('fixed-base.gyp', chdir=CHDIR) test.build('fixed-base.gyp', test.ALL, chdir=CHDIR) def GetHeaders(exe): full_path = test.built_file_path(exe, chdir=CHDIR) return test.run_dumpbin('/headers', full_path) # For exe, default is fixed, for dll, it's not fixed. if 'Relocations stripped' not in GetHeaders('test_fixed_default_exe.exe'): test.fail_test() if 'Relocations stripped' in GetHeaders('test_fixed_default_dll.dll'): test.fail_test() # Explicitly not fixed. if 'Relocations stripped' in GetHeaders('test_fixed_no.exe'): test.fail_test() # Explicitly fixed. if 'Relocations stripped' not in GetHeaders('test_fixed_yes.exe'): test.fail_test() test.pass_test()
eduNEXT/edunext-platform
refs/heads/master
common/djangoapps/third_party_auth/api/views.py
2
""" Third Party Auth REST API views """ from collections import namedtuple from django.conf import settings from django.contrib.auth.models import User from django.db.models import Q from django.http import Http404 from django.urls import reverse from edx_rest_framework_extensions.auth.jwt.authentication import JwtAuthentication from edx_rest_framework_extensions.auth.session.authentication import SessionAuthenticationAllowInactiveUser from rest_framework import exceptions, permissions, status, throttling from rest_framework.generics import ListAPIView from rest_framework.response import Response from rest_framework.views import APIView from social_django.models import UserSocialAuth from openedx.core.lib.api.authentication import ( BearerAuthentication, BearerAuthenticationAllowInactiveUser ) from openedx.core.lib.api.permissions import ApiKeyHeaderPermission from third_party_auth import pipeline from third_party_auth.api import serializers from third_party_auth.api.permissions import TPA_PERMISSIONS from third_party_auth.provider import Registry from common.djangoapps.third_party_auth.api.utils import filter_user_social_auth_queryset_by_provider class ProviderBaseThrottle(throttling.UserRateThrottle): """ Base throttle for provider queries """ def allow_request(self, request, view): """ Only throttle unprivileged requests. """ if view.is_unprivileged_query(request, view.get_identifier_for_requested_user(request)): return super(ProviderBaseThrottle, self).allow_request(request, view) return True class ProviderBurstThrottle(ProviderBaseThrottle): """ Maximum number of provider requests in a quick burst. """ rate = settings.TPA_PROVIDER_BURST_THROTTLE # Default '10/min' class ProviderSustainedThrottle(ProviderBaseThrottle): """ Maximum number of provider requests over time. """ rate = settings.TPA_PROVIDER_SUSTAINED_THROTTLE # Default '50/day' class BaseUserView(APIView): """ Common core of UserView and UserViewV2 """ identifier = namedtuple('identifier', ['kind', 'value']) identifier_kinds = ['email', 'username'] authentication_classes = ( # Users may want to view/edit the providers used for authentication before they've # activated their account, so we allow inactive users. BearerAuthenticationAllowInactiveUser, SessionAuthenticationAllowInactiveUser, ) throttle_classes = [ProviderSustainedThrottle, ProviderBurstThrottle] def do_get(self, request, identifier): """ Fulfill the request, now that the identifier has been specified. """ is_unprivileged = self.is_unprivileged_query(request, identifier) if is_unprivileged: if not getattr(settings, 'ALLOW_UNPRIVILEGED_SSO_PROVIDER_QUERY', False): return Response(status=status.HTTP_403_FORBIDDEN) try: user = User.objects.get(**{identifier.kind: identifier.value}) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) providers = pipeline.get_provider_user_states(user) active_providers = [ self.get_provider_data(assoc, is_unprivileged) for assoc in providers if assoc.has_account ] # In the future this can be trivially modified to return the inactive/disconnected providers as well. return Response({ "active": active_providers }) def get_provider_data(self, assoc, is_unprivileged): """ Return the data for the specified provider. If the request is unprivileged, do not return the remote ID of the user. """ provider_data = { "provider_id": assoc.provider.provider_id, "name": assoc.provider.name, } if not is_unprivileged: provider_data["remote_id"] = assoc.remote_id return provider_data def is_unprivileged_query(self, request, identifier): """ Return True if a non-superuser requests information about another user. Params must be a dict that includes only one of 'username' or 'email' """ if identifier.kind not in self.identifier_kinds: # This is already checked before we get here, so raise a 500 error # if the check fails. raise ValueError(u"Identifier kind {} not in {}".format(identifier.kind, self.identifier_kinds)) self_request = False if identifier == self.identifier('username', request.user.username): self_request = True elif identifier.kind == 'email' and getattr(identifier, 'value', object()) == request.user.email: # AnonymousUser does not have an email attribute, so fall back to # something that will never compare equal to the provided email. self_request = True if self_request: # We can always ask for our own provider return False # We are querying permissions for a user other than the current user. if not request.user.is_superuser and not ApiKeyHeaderPermission().has_permission(request, self): # The user does not have elevated permissions. return True return False class UserView(BaseUserView): """ List the third party auth accounts linked to the specified user account. [DEPRECATED] This view uses heuristics to guess whether the provided identifier is a username or email address. Instead, use /api/third_party_auth/v0/users/ and specify ?username=foo or ?email=foo@exmaple.com. **Example Request** GET /api/third_party_auth/v0/users/{username} GET /api/third_party_auth/v0/users/{email@example.com} **Response Values** If the request for information about the user is successful, an HTTP 200 "OK" response is returned. The HTTP 200 response has the following values. * active: A list of all the third party auth providers currently linked to the given user's account. Each object in this list has the following attributes: * provider_id: The unique identifier of this provider (string) * name: The name of this provider (string) * remote_id: The ID of the user according to the provider. This ID is what is used to link the user to their edX account during login. """ def get(self, request, username): """Read provider information for a user. Allows reading the list of providers for a specified user. Args: request (Request): The HTTP GET request username (str): Fetch the list of providers linked to this user Return: JSON serialized list of the providers linked to this user. """ identifier = self.get_identifier_for_requested_user(request) return self.do_get(request, identifier) def get_identifier_for_requested_user(self, _request): """ Return an identifier namedtuple for the requested user. """ if u'@' in self.kwargs[u'username']: id_kind = u'email' else: id_kind = u'username' return self.identifier(id_kind, self.kwargs[u'username']) # TODO: When removing deprecated UserView, rename this view to UserView. class UserViewV2(BaseUserView): """ List the third party auth accounts linked to the specified user account. **Example Request** GET /api/third_party_auth/v0/users/?username={username} GET /api/third_party_auth/v0/users/?email={email@example.com} **Response Values** If the request for information about the user is successful, an HTTP 200 "OK" response is returned. The HTTP 200 response has the following values. * active: A list of all the third party auth providers currently linked to the given user's account. Each object in this list has the following attributes: * provider_id: The unique identifier of this provider (string) * name: The name of this provider (string) * remote_id: The ID of the user according to the provider. This ID is what is used to link the user to their edX account during login. """ def get(self, request): """ Read provider information for a user. Allows reading the list of providers for a specified user. Args: request (Request): The HTTP GET request Request Parameters: Must provide one of 'email' or 'username'. If both are provided, the username will be ignored. Return: JSON serialized list of the providers linked to this user. """ identifier = self.get_identifier_for_requested_user(request) return self.do_get(request, identifier) def get_identifier_for_requested_user(self, request): """ Return an identifier namedtuple for the requested user. """ identifier = None for id_kind in self.identifier_kinds: if id_kind in request.GET: identifier = self.identifier(id_kind, request.GET[id_kind]) break if identifier is None: raise exceptions.ValidationError(u"Must provide one of {}".format(self.identifier_kinds)) return identifier class UserMappingView(ListAPIView): """ Map between the third party auth account IDs (remote_id) and EdX username. This API is intended to be a server-to-server endpoint. An on-campus middleware or system should consume this. **Use Case** Get a paginated list of mappings between edX users and remote user IDs for all users currently linked to the given backend. The list can be filtered by edx username or third party ids. The filter is limited by the max length of URL. It is suggested to query no more than 50 usernames or remote_ids in each request to stay within above limitation The page size can be changed by specifying `page_size` parameter in the request. **Example Requests** GET /api/third_party_auth/v0/providers/{provider_id}/users GET /api/third_party_auth/v0/providers/{provider_id}/users?username={username1},{username2} GET /api/third_party_auth/v0/providers/{provider_id}/users?username={username1}&usernames={username2} GET /api/third_party_auth/v0/providers/{provider_id}/users?remote_id={remote_id1},{remote_id2} GET /api/third_party_auth/v0/providers/{provider_id}/users?remote_id={remote_id1}&remote_id={remote_id2} GET /api/third_party_auth/v0/providers/{provider_id}/users?username={username1}&remote_id={remote_id1} **URL Parameters** * provider_id: The unique identifier of third_party_auth provider (e.g. "saml-ubc", "oa2-google", etc. This is not the same thing as the backend_name.). (Optional/future: We may also want to allow this to be an 'external domain' like 'ssl:MIT' so that this API can also search the legacy ExternalAuthMap table used by Standford/MIT) **Query Parameters** * remote_ids: Optional. List of comma separated remote (third party) user IDs to filter the result set. e.g. ?remote_ids=8721384623 * usernames: Optional. List of comma separated edX usernames to filter the result set. e.g. ?usernames=bob123,jane456 * page, page_size: Optional. Used for paging the result set, especially when getting an unfiltered list. **Response Values** If the request for information about the user is successful, an HTTP 200 "OK" response is returned. The HTTP 200 response has the following values: * count: The number of mappings for the backend. * next: The URI to the next page of the mappings. * previous: The URI to the previous page of the mappings. * num_pages: The number of pages listing the mappings. * results: A list of mappings returned. Each collection in the list contains these fields. * username: The edx username * remote_id: The Id from third party auth provider """ authentication_classes = (JwtAuthentication, BearerAuthentication, ) permission_classes = (TPA_PERMISSIONS, ) required_scopes = ['tpa:read'] serializer_class = serializers.UserMappingSerializer provider = None def get_queryset(self): provider_id = self.kwargs.get('provider_id') # provider existence checking self.provider = Registry.get(provider_id) if not self.provider: raise Http404 query_set = filter_user_social_auth_queryset_by_provider( UserSocialAuth.objects.select_related('user'), self.provider, ) query = Q() usernames = self.request.query_params.getlist('username', None) remote_ids = self.request.query_params.getlist('remote_id', None) if usernames: usernames = ','.join(usernames) usernames = set(usernames.split(',')) if usernames else set() if usernames: query = query | Q(user__username__in=usernames) if remote_ids: remote_ids = ','.join(remote_ids) remote_ids = set(remote_ids.split(',')) if remote_ids else set() if remote_ids: query = query | Q(uid__in=[self.provider.get_social_auth_uid(remote_id) for remote_id in remote_ids]) return query_set.filter(query) def get_serializer_context(self): """ Extra context provided to the serializer class with current provider. We need the provider to remove idp_slug from the remote_id if there is any """ context = super(UserMappingView, self).get_serializer_context() context['provider'] = self.provider return context class ThirdPartyAuthUserStatusView(APIView): """ Provides an API endpoint for retrieving the linked status of the authenticated user with respect to the third party auth providers configured in the system. """ authentication_classes = ( JwtAuthentication, BearerAuthenticationAllowInactiveUser, SessionAuthenticationAllowInactiveUser ) permission_classes = (permissions.IsAuthenticated,) def get(self, request): """ GET /api/third_party_auth/v0/providers/user_status/ **GET Response Values** ``` { "accepts_logins": true, "name": "Google", "disconnect_url": "/auth/disconnect/google-oauth2/?", "connect_url": "/auth/login/google-oauth2/?auth_entry=account_settings&next=%2Faccount%2Fsettings", "connected": false, "id": "oa2-google-oauth2" } ``` """ tpa_states = [] for state in pipeline.get_provider_user_states(request.user): # We only want to include providers if they are either currently available to be logged # in with, or if the user is already authenticated with them. if state.provider.display_for_login or state.has_account: tpa_states.append({ 'id': state.provider.provider_id, 'name': state.provider.name, # The name of the provider e.g. Facebook 'connected': state.has_account, # Whether the user's edX account is connected with the provider. # If the user is not connected, they should be directed to this page to authenticate # with the particular provider, as long as the provider supports initiating a login. 'connect_url': pipeline.get_login_url( state.provider.provider_id, pipeline.AUTH_ENTRY_ACCOUNT_SETTINGS, # The url the user should be directed to after the auth process has completed. redirect_url=reverse('account_settings'), ), 'accepts_logins': state.provider.accepts_logins, # If the user is connected, sending a POST request to this url removes the connection # information for this provider from their edX account. 'disconnect_url': pipeline.get_disconnect_url(state.provider.provider_id, state.association_id), }) return Response(tpa_states)
Varriount/Colliberation
refs/heads/master
libs/twisted/words/test/test_xmpproutertap.py
40
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.words.xmpproutertap}. """ from twisted.application import internet from twisted.trial import unittest from twisted.words import xmpproutertap as tap from twisted.words.protocols.jabber import component class XMPPRouterTapTest(unittest.TestCase): def test_port(self): """ The port option is recognised as a parameter. """ opt = tap.Options() opt.parseOptions(['--port', '7001']) self.assertEqual(opt['port'], '7001') def test_portDefault(self): """ The port option has '5347' as default value """ opt = tap.Options() opt.parseOptions([]) self.assertEqual(opt['port'], 'tcp:5347:interface=127.0.0.1') def test_secret(self): """ The secret option is recognised as a parameter. """ opt = tap.Options() opt.parseOptions(['--secret', 'hushhush']) self.assertEqual(opt['secret'], 'hushhush') def test_secretDefault(self): """ The secret option has 'secret' as default value """ opt = tap.Options() opt.parseOptions([]) self.assertEqual(opt['secret'], 'secret') def test_verbose(self): """ The verbose option is recognised as a flag. """ opt = tap.Options() opt.parseOptions(['--verbose']) self.assertTrue(opt['verbose']) def test_makeService(self): """ The service gets set up with a router and factory. """ opt = tap.Options() opt.parseOptions([]) s = tap.makeService(opt) self.assertIsInstance(s, internet.StreamServerEndpointService) self.assertEqual('127.0.0.1', s.endpoint._interface) self.assertEqual(5347, s.endpoint._port) factory = s.factory self.assertIsInstance(factory, component.XMPPComponentServerFactory) self.assertIsInstance(factory.router, component.Router) self.assertEqual('secret', factory.secret) self.assertFalse(factory.logTraffic) def test_makeServiceVerbose(self): """ The verbose flag enables traffic logging. """ opt = tap.Options() opt.parseOptions(['--verbose']) s = tap.makeService(opt) self.assertTrue(s.factory.logTraffic)
jasonabele/gnuradio
refs/heads/rfx2200
gr-utils/src/python/usrp_rx_cfile.py
11
#!/usr/bin/env python """ Read samples from the USRP and write to file formatted as binary outputs single precision complex float values or complex short values (interleaved 16 bit signed short integers). """ from gnuradio import gr, eng_notation from gnuradio import audio from gnuradio import usrp from gnuradio.eng_option import eng_option from optparse import OptionParser import sys class my_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) usage="%prog: [options] output_filename" parser = OptionParser(option_class=eng_option, usage=usage) parser.add_option("-R", "--rx-subdev-spec", type="subdev", default=(0, 0), help="select USRP Rx side A or B (default=A)") parser.add_option("-d", "--decim", type="int", default=16, help="set fgpa decimation rate to DECIM [default=%default]") parser.add_option("-f", "--freq", type="eng_float", default=None, help="set frequency to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=None, help="set gain in dB (default is midpoint)") parser.add_option("-8", "--width-8", action="store_true", default=False, help="Enable 8-bit samples across USB") parser.add_option( "--no-hb", action="store_true", default=False, help="don't use halfband filter in usrp") parser.add_option( "-s","--output-shorts", action="store_true", default=False, help="output interleaved shorts in stead of complex floats") parser.add_option("-N", "--nsamples", type="eng_float", default=None, help="number of samples to collect [default=+inf]") (options, args) = parser.parse_args () if len(args) != 1: parser.print_help() raise SystemExit, 1 filename = args[0] if options.freq is None: parser.print_help() sys.stderr.write('You must specify the frequency with -f FREQ\n'); raise SystemExit, 1 # build the graph if options.no_hb or (options.decim<8): self.fpga_filename="std_4rx_0tx.rbf" #Min decimation of this firmware is 4. contains 4 Rx paths without halfbands and 0 tx paths. if options.output_shorts: self.u = usrp.source_s(decim_rate=options.decim,fpga_filename=self.fpga_filename) else: self.u = usrp.source_c(decim_rate=options.decim,fpga_filename=self.fpga_filename) else: #standard fpga firmware "std_2rxhb_2tx.rbf" contains 2 Rx paths with halfband filters and 2 tx paths (the default) min decimation 8 if options.output_shorts: self.u = usrp.source_s(decim_rate=options.decim) else: self.u = usrp.source_c(decim_rate=options.decim) if options.width_8: sample_width = 8 sample_shift = 8 format = self.u.make_format(sample_width, sample_shift) r = self.u.set_format(format) if options.output_shorts: self.dst = gr.file_sink(gr.sizeof_short, filename) else: self.dst = gr.file_sink(gr.sizeof_gr_complex, filename) if options.nsamples is None: self.connect(self.u, self.dst) else: if options.output_shorts: self.head = gr.head(gr.sizeof_short, int(options.nsamples)*2) else: self.head = gr.head(gr.sizeof_gr_complex, int(options.nsamples)) self.connect(self.u, self.head, self.dst) if options.rx_subdev_spec is None: options.rx_subdev_spec = usrp.pick_rx_subdevice(self.u) self.u.set_mux(usrp.determine_rx_mux_value(self.u, options.rx_subdev_spec)) # determine the daughterboard subdevice we're using self.subdev = usrp.selected_subdev(self.u, options.rx_subdev_spec) print "Using RX d'board %s" % (self.subdev.side_and_name(),) input_rate = self.u.adc_freq() / self.u.decim_rate() print "USB sample rate %s" % (eng_notation.num_to_str(input_rate)) if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.subdev.gain_range() options.gain = float(g[0]+g[1])/2 self.subdev.set_gain(options.gain) r = self.u.tune(0, self.subdev, options.freq) if not r: sys.stderr.write('Failed to set frequency\n') raise SystemExit, 1 if __name__ == '__main__': try: my_top_block().run() except KeyboardInterrupt: pass
Orav/kbengine
refs/heads/master
kbe/src/lib/python/Lib/sqlite3/test/hooks.py
2
#-*- coding: iso-8859-1 -*- # pysqlite2/test/hooks.py: tests for various SQLite-specific hooks # # Copyright (C) 2006-2007 Gerhard Häring <gh@ghaering.de> # # This file is part of pysqlite. # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from the use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. import unittest import sqlite3 as sqlite class CollationTests(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def CheckCreateCollationNotCallable(self): con = sqlite.connect(":memory:") try: con.create_collation("X", 42) self.fail("should have raised a TypeError") except TypeError as e: self.assertEqual(e.args[0], "parameter must be callable") def CheckCreateCollationNotAscii(self): con = sqlite.connect(":memory:") try: con.create_collation("collä", lambda x, y: (x > y) - (x < y)) self.fail("should have raised a ProgrammingError") except sqlite.ProgrammingError as e: pass @unittest.skipIf(sqlite.sqlite_version_info < (3, 2, 1), 'old SQLite versions crash on this test') def CheckCollationIsUsed(self): def mycoll(x, y): # reverse order return -((x > y) - (x < y)) con = sqlite.connect(":memory:") con.create_collation("mycoll", mycoll) sql = """ select x from ( select 'a' as x union select 'b' as x union select 'c' as x ) order by x collate mycoll """ result = con.execute(sql).fetchall() if result[0][0] != "c" or result[1][0] != "b" or result[2][0] != "a": self.fail("the expected order was not returned") con.create_collation("mycoll", None) try: result = con.execute(sql).fetchall() self.fail("should have raised an OperationalError") except sqlite.OperationalError as e: self.assertEqual(e.args[0].lower(), "no such collation sequence: mycoll") def CheckCollationReturnsLargeInteger(self): def mycoll(x, y): # reverse order return -((x > y) - (x < y)) * 2**32 con = sqlite.connect(":memory:") con.create_collation("mycoll", mycoll) sql = """ select x from ( select 'a' as x union select 'b' as x union select 'c' as x ) order by x collate mycoll """ result = con.execute(sql).fetchall() self.assertEqual(result, [('c',), ('b',), ('a',)], msg="the expected order was not returned") def CheckCollationRegisterTwice(self): """ Register two different collation functions under the same name. Verify that the last one is actually used. """ con = sqlite.connect(":memory:") con.create_collation("mycoll", lambda x, y: (x > y) - (x < y)) con.create_collation("mycoll", lambda x, y: -((x > y) - (x < y))) result = con.execute(""" select x from (select 'a' as x union select 'b' as x) order by x collate mycoll """).fetchall() if result[0][0] != 'b' or result[1][0] != 'a': self.fail("wrong collation function is used") def CheckDeregisterCollation(self): """ Register a collation, then deregister it. Make sure an error is raised if we try to use it. """ con = sqlite.connect(":memory:") con.create_collation("mycoll", lambda x, y: (x > y) - (x < y)) con.create_collation("mycoll", None) try: con.execute("select 'a' as x union select 'b' as x order by x collate mycoll") self.fail("should have raised an OperationalError") except sqlite.OperationalError as e: if not e.args[0].startswith("no such collation sequence"): self.fail("wrong OperationalError raised") class ProgressTests(unittest.TestCase): def CheckProgressHandlerUsed(self): """ Test that the progress handler is invoked once it is set. """ con = sqlite.connect(":memory:") progress_calls = [] def progress(): progress_calls.append(None) return 0 con.set_progress_handler(progress, 1) con.execute(""" create table foo(a, b) """) self.assertTrue(progress_calls) def CheckOpcodeCount(self): """ Test that the opcode argument is respected. """ con = sqlite.connect(":memory:") progress_calls = [] def progress(): progress_calls.append(None) return 0 con.set_progress_handler(progress, 1) curs = con.cursor() curs.execute(""" create table foo (a, b) """) first_count = len(progress_calls) progress_calls = [] con.set_progress_handler(progress, 2) curs.execute(""" create table bar (a, b) """) second_count = len(progress_calls) self.assertGreaterEqual(first_count, second_count) def CheckCancelOperation(self): """ Test that returning a non-zero value stops the operation in progress. """ con = sqlite.connect(":memory:") progress_calls = [] def progress(): progress_calls.append(None) return 1 con.set_progress_handler(progress, 1) curs = con.cursor() self.assertRaises( sqlite.OperationalError, curs.execute, "create table bar (a, b)") def CheckClearHandler(self): """ Test that setting the progress handler to None clears the previously set handler. """ con = sqlite.connect(":memory:") action = 0 def progress(): nonlocal action action = 1 return 0 con.set_progress_handler(progress, 1) con.set_progress_handler(None, 1) con.execute("select 1 union select 2 union select 3").fetchall() self.assertEqual(action, 0, "progress handler was not cleared") class TraceCallbackTests(unittest.TestCase): def CheckTraceCallbackUsed(self): """ Test that the trace callback is invoked once it is set. """ con = sqlite.connect(":memory:") traced_statements = [] def trace(statement): traced_statements.append(statement) con.set_trace_callback(trace) con.execute("create table foo(a, b)") self.assertTrue(traced_statements) self.assertTrue(any("create table foo" in stmt for stmt in traced_statements)) def CheckClearTraceCallback(self): """ Test that setting the trace callback to None clears the previously set callback. """ con = sqlite.connect(":memory:") traced_statements = [] def trace(statement): traced_statements.append(statement) con.set_trace_callback(trace) con.set_trace_callback(None) con.execute("create table foo(a, b)") self.assertFalse(traced_statements, "trace callback was not cleared") def CheckUnicodeContent(self): """ Test that the statement can contain unicode literals. """ unicode_value = '\xf6\xe4\xfc\xd6\xc4\xdc\xdf\u20ac' con = sqlite.connect(":memory:") traced_statements = [] def trace(statement): traced_statements.append(statement) con.set_trace_callback(trace) con.execute("create table foo(x)") # Can't execute bound parameters as their values don't appear # in traced statements before SQLite 3.6.21 # (cf. http://www.sqlite.org/draft/releaselog/3_6_21.html) con.execute('insert into foo(x) values ("%s")' % unicode_value) con.commit() self.assertTrue(any(unicode_value in stmt for stmt in traced_statements), "Unicode data %s garbled in trace callback: %s" % (ascii(unicode_value), ', '.join(map(ascii, traced_statements)))) def suite(): collation_suite = unittest.makeSuite(CollationTests, "Check") progress_suite = unittest.makeSuite(ProgressTests, "Check") trace_suite = unittest.makeSuite(TraceCallbackTests, "Check") return unittest.TestSuite((collation_suite, progress_suite, trace_suite)) def test(): runner = unittest.TextTestRunner() runner.run(suite()) if __name__ == "__main__": test()
subailong/ns3-wireless-planning.ns-3
refs/heads/master
bindings/python/apidefs/gcc-LP64/ns3_module_node.py
4
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers def register_types(module): root_module = module.get_root() ## packetbb.h: ns3::PbbAddressLength [enumeration] module.add_enum('PbbAddressLength', ['IPV4', 'IPV6']) ## ethernet-header.h: ns3::ethernet_header_t [enumeration] module.add_enum('ethernet_header_t', ['LENGTH', 'VLAN', 'QINQ']) ## address.h: ns3::Address [class] module.add_class('Address') ## address.h: ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address']) ## channel-list.h: ns3::ChannelList [class] module.add_class('ChannelList') ## inet6-socket-address.h: ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress') ## inet6-socket-address.h: ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h: ns3::InetSocketAddress [class] module.add_class('InetSocketAddress') ## inet-socket-address.h: ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h: ns3::Ipv4Address [class] module.add_class('Ipv4Address') ## ipv4-address.h: ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address-generator.h: ns3::Ipv4AddressGenerator [class] module.add_class('Ipv4AddressGenerator') ## ipv4-interface-address.h: ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress') ## ipv4-interface-address.h: ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress']) ## ipv4-address.h: ns3::Ipv4Mask [class] module.add_class('Ipv4Mask') ## ipv6-address.h: ns3::Ipv6Address [class] module.add_class('Ipv6Address') ## ipv6-address.h: ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-interface-address.h: ns3::Ipv6InterfaceAddress [class] module.add_class('Ipv6InterfaceAddress') ## ipv6-interface-address.h: ns3::Ipv6InterfaceAddress::State_e [enumeration] module.add_enum('State_e', ['TENTATIVE', 'DEPRECATED', 'PREFERRED', 'PERMANENT', 'HOMEADDRESS', 'TENTATIVE_OPTIMISTIC', 'INVALID'], outer_class=root_module['ns3::Ipv6InterfaceAddress']) ## ipv6-interface-address.h: ns3::Ipv6InterfaceAddress::Scope_e [enumeration] module.add_enum('Scope_e', ['HOST', 'LINKLOCAL', 'GLOBAL'], outer_class=root_module['ns3::Ipv6InterfaceAddress']) ## ipv6-address.h: ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix') ## mac48-address.h: ns3::Mac48Address [class] module.add_class('Mac48Address') ## mac48-address.h: ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## mac64-address.h: ns3::Mac64Address [class] module.add_class('Mac64Address') ## mac64-address.h: ns3::Mac64Address [class] root_module['ns3::Mac64Address'].implicitly_converts_to(root_module['ns3::Address']) ## node-list.h: ns3::NodeList [class] module.add_class('NodeList') ## packet-socket-address.h: ns3::PacketSocketAddress [class] module.add_class('PacketSocketAddress') ## packet-socket-address.h: ns3::PacketSocketAddress [class] root_module['ns3::PacketSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## packetbb.h: ns3::PbbAddressTlvBlock [class] module.add_class('PbbAddressTlvBlock') ## packetbb.h: ns3::PbbTlvBlock [class] module.add_class('PbbTlvBlock') ## ipv4-header.h: ns3::Ipv4Header [class] module.add_class('Ipv4Header', parent=root_module['ns3::Header']) ## ipv6-header.h: ns3::Ipv6Header [class] module.add_class('Ipv6Header', parent=root_module['ns3::Header']) ## ipv6-header.h: ns3::Ipv6Header::NextHeader_e [enumeration] module.add_enum('NextHeader_e', ['IPV6_EXT_HOP_BY_HOP', 'IPV6_IPV4', 'IPV6_TCP', 'IPV6_UDP', 'IPV6_IPV6', 'IPV6_EXT_ROUTING', 'IPV6_EXT_FRAGMENTATION', 'IPV6_EXT_CONFIDENTIALITY', 'IPV6_EXT_AUTHENTIFICATION', 'IPV6_ICMPV6', 'IPV6_EXT_END', 'IPV6_EXT_DESTINATION', 'IPV6_SCTP', 'IPV6_EXT_MOBILITY', 'IPV6_UDP_LITE'], outer_class=root_module['ns3::Ipv6Header']) ## llc-snap-header.h: ns3::LlcSnapHeader [class] module.add_class('LlcSnapHeader', parent=root_module['ns3::Header']) ## queue.h: ns3::Queue [class] module.add_class('Queue', parent=root_module['ns3::Object']) ## radiotap-header.h: ns3::RadiotapHeader [class] module.add_class('RadiotapHeader', parent=root_module['ns3::Header']) ## radiotap-header.h: ns3::RadiotapHeader [enumeration] module.add_enum('', ['FRAME_FLAG_NONE', 'FRAME_FLAG_CFP', 'FRAME_FLAG_SHORT_PREAMBLE', 'FRAME_FLAG_WEP', 'FRAME_FLAG_FRAGMENTED', 'FRAME_FLAG_FCS_INCLUDED', 'FRAME_FLAG_DATA_PADDING', 'FRAME_FLAG_BAD_FCS', 'FRAME_FLAG_SHORT_GUARD'], outer_class=root_module['ns3::RadiotapHeader']) ## radiotap-header.h: ns3::RadiotapHeader [enumeration] module.add_enum('', ['CHANNEL_FLAG_NONE', 'CHANNEL_FLAG_TURBO', 'CHANNEL_FLAG_CCK', 'CHANNEL_FLAG_OFDM', 'CHANNEL_FLAG_SPECTRUM_2GHZ', 'CHANNEL_FLAG_SPECTRUM_5GHZ', 'CHANNEL_FLAG_PASSIVE', 'CHANNEL_FLAG_DYNAMIC', 'CHANNEL_FLAG_GFSK'], outer_class=root_module['ns3::RadiotapHeader']) ## simple-ref-count.h: ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, 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: ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, 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: ns3::SimpleRefCount<ns3::Ipv6MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv6MulticastRoute> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::Ipv6MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv6MulticastRoute>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h: ns3::SimpleRefCount<ns3::Ipv6Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv6Route> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::Ipv6Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv6Route>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h: ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::PbbAddressBlock', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbAddressBlock>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h: ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::PbbMessage', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbMessage>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h: ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::PbbPacket', 'ns3::Header', 'ns3::DefaultDeleter<ns3::PbbPacket>'], parent=root_module['ns3::Header'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h: ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::PbbTlv', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbTlv>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## socket.h: ns3::Socket [class] module.add_class('Socket', parent=root_module['ns3::Object']) ## socket.h: 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', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket']) ## socket.h: ns3::SocketAddressTag [class] module.add_class('SocketAddressTag', parent=root_module['ns3::Tag']) ## socket-factory.h: ns3::SocketFactory [class] module.add_class('SocketFactory', parent=root_module['ns3::Object']) ## socket.h: ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', parent=root_module['ns3::Tag']) ## socket.h: ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', parent=root_module['ns3::Tag']) ## tcp-socket.h: ns3::TcpSocket [class] module.add_class('TcpSocket', parent=root_module['ns3::Socket']) ## tcp-socket-factory.h: ns3::TcpSocketFactory [class] module.add_class('TcpSocketFactory', parent=root_module['ns3::SocketFactory']) ## udp-socket.h: ns3::UdpSocket [class] module.add_class('UdpSocket', parent=root_module['ns3::Socket']) ## udp-socket-factory.h: ns3::UdpSocketFactory [class] module.add_class('UdpSocketFactory', parent=root_module['ns3::SocketFactory']) ## application.h: ns3::Application [class] module.add_class('Application', parent=root_module['ns3::Object']) ## channel.h: ns3::Channel [class] module.add_class('Channel', parent=root_module['ns3::Object']) ## drop-tail-queue.h: ns3::DropTailQueue [class] module.add_class('DropTailQueue', parent=root_module['ns3::Queue']) ## drop-tail-queue.h: ns3::DropTailQueue::Mode [enumeration] module.add_enum('Mode', ['ILLEGAL', 'PACKETS', 'BYTES'], outer_class=root_module['ns3::DropTailQueue']) ## ethernet-header.h: ns3::EthernetHeader [class] module.add_class('EthernetHeader', parent=root_module['ns3::Header']) ## ethernet-trailer.h: ns3::EthernetTrailer [class] module.add_class('EthernetTrailer', parent=root_module['ns3::Trailer']) ## ipv4.h: ns3::Ipv4 [class] module.add_class('Ipv4', parent=root_module['ns3::Object']) ## ipv4-address.h: ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h: ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h: ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h: ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', parent=root_module['ns3::AttributeValue']) ## ipv4-route.h: ns3::Ipv4MulticastRoute [class] module.add_class('Ipv4MulticastRoute', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) ## ipv4-raw-socket-factory.h: ns3::Ipv4RawSocketFactory [class] module.add_class('Ipv4RawSocketFactory', parent=root_module['ns3::SocketFactory']) ## ipv4-route.h: ns3::Ipv4Route [class] module.add_class('Ipv4Route', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) ## ipv4-routing-protocol.h: ns3::Ipv4RoutingProtocol [class] module.add_class('Ipv4RoutingProtocol', parent=root_module['ns3::Object']) ## ipv6.h: ns3::Ipv6 [class] module.add_class('Ipv6', parent=root_module['ns3::Object']) ## ipv6-address.h: ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h: ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', parent=root_module['ns3::AttributeValue']) ## ipv6-route.h: ns3::Ipv6MulticastRoute [class] module.add_class('Ipv6MulticastRoute', parent=root_module['ns3::SimpleRefCount< ns3::Ipv6MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv6MulticastRoute> >']) ## ipv6-address.h: ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h: ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', parent=root_module['ns3::AttributeValue']) ## ipv6-raw-socket-factory.h: ns3::Ipv6RawSocketFactory [class] module.add_class('Ipv6RawSocketFactory', parent=root_module['ns3::SocketFactory']) ## ipv6-route.h: ns3::Ipv6Route [class] module.add_class('Ipv6Route', parent=root_module['ns3::SimpleRefCount< ns3::Ipv6Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv6Route> >']) ## ipv6-routing-protocol.h: ns3::Ipv6RoutingProtocol [class] module.add_class('Ipv6RoutingProtocol', parent=root_module['ns3::Object']) ## mac48-address.h: ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h: ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', parent=root_module['ns3::AttributeValue']) ## net-device.h: ns3::NetDevice [class] module.add_class('NetDevice', parent=root_module['ns3::Object']) ## net-device.h: 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']) ## node.h: ns3::Node [class] module.add_class('Node', parent=root_module['ns3::Object']) ## packet-socket-factory.h: ns3::PacketSocketFactory [class] module.add_class('PacketSocketFactory', parent=root_module['ns3::SocketFactory']) ## packetbb.h: ns3::PbbAddressBlock [class] module.add_class('PbbAddressBlock', parent=root_module['ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >']) ## packetbb.h: ns3::PbbAddressBlockIpv4 [class] module.add_class('PbbAddressBlockIpv4', parent=root_module['ns3::PbbAddressBlock']) ## packetbb.h: ns3::PbbAddressBlockIpv6 [class] module.add_class('PbbAddressBlockIpv6', parent=root_module['ns3::PbbAddressBlock']) ## packetbb.h: ns3::PbbMessage [class] module.add_class('PbbMessage', parent=root_module['ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >']) ## packetbb.h: ns3::PbbMessageIpv4 [class] module.add_class('PbbMessageIpv4', parent=root_module['ns3::PbbMessage']) ## packetbb.h: ns3::PbbMessageIpv6 [class] module.add_class('PbbMessageIpv6', parent=root_module['ns3::PbbMessage']) ## packetbb.h: ns3::PbbPacket [class] module.add_class('PbbPacket', parent=root_module['ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >']) ## packetbb.h: ns3::PbbTlv [class] module.add_class('PbbTlv', parent=root_module['ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >']) ## simple-channel.h: ns3::SimpleChannel [class] module.add_class('SimpleChannel', parent=root_module['ns3::Channel']) ## simple-net-device.h: ns3::SimpleNetDevice [class] module.add_class('SimpleNetDevice', parent=root_module['ns3::NetDevice']) ## address.h: ns3::AddressChecker [class] module.add_class('AddressChecker', parent=root_module['ns3::AttributeChecker']) ## address.h: ns3::AddressValue [class] module.add_class('AddressValue', parent=root_module['ns3::AttributeValue']) ## packetbb.h: ns3::PbbAddressTlv [class] module.add_class('PbbAddressTlv', parent=root_module['ns3::PbbTlv']) module.add_container('ns3::olsr::MprSet', 'ns3::Ipv4Address', container_type='set') module.add_container('std::vector< ns3::Ipv4Address >', 'ns3::Ipv4Address', container_type='vector') module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type='vector') ## Register a nested module for the namespace Config nested_module = module.add_cpp_namespace('Config') register_types_ns3_Config(nested_module) ## Register a nested module for the namespace TimeStepPrecision nested_module = module.add_cpp_namespace('TimeStepPrecision') register_types_ns3_TimeStepPrecision(nested_module) ## Register a nested module for the namespace addressUtils nested_module = module.add_cpp_namespace('addressUtils') register_types_ns3_addressUtils(nested_module) ## Register a nested module for the namespace aodv nested_module = module.add_cpp_namespace('aodv') register_types_ns3_aodv(nested_module) ## Register a nested module for the namespace dot11s nested_module = module.add_cpp_namespace('dot11s') register_types_ns3_dot11s(nested_module) ## Register a nested module for the namespace flame nested_module = module.add_cpp_namespace('flame') register_types_ns3_flame(nested_module) ## Register a nested module for the namespace internal nested_module = module.add_cpp_namespace('internal') register_types_ns3_internal(nested_module) ## Register a nested module for the namespace olsr nested_module = module.add_cpp_namespace('olsr') register_types_ns3_olsr(nested_module) def register_types_ns3_Config(module): root_module = module.get_root() def register_types_ns3_TimeStepPrecision(module): root_module = module.get_root() def register_types_ns3_addressUtils(module): root_module = module.get_root() def register_types_ns3_aodv(module): root_module = module.get_root() def register_types_ns3_dot11s(module): root_module = module.get_root() module.add_container('std::vector< ns3::Mac48Address >', 'ns3::Mac48Address', container_type='vector') def register_types_ns3_flame(module): root_module = module.get_root() def register_types_ns3_internal(module): root_module = module.get_root() def register_types_ns3_olsr(module): root_module = module.get_root() def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3ChannelList_methods(root_module, root_module['ns3::ChannelList']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4AddressGenerator_methods(root_module, root_module['ns3::Ipv4AddressGenerator']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6InterfaceAddress_methods(root_module, root_module['ns3::Ipv6InterfaceAddress']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3Mac64Address_methods(root_module, root_module['ns3::Mac64Address']) register_Ns3NodeList_methods(root_module, root_module['ns3::NodeList']) register_Ns3PacketSocketAddress_methods(root_module, root_module['ns3::PacketSocketAddress']) register_Ns3PbbAddressTlvBlock_methods(root_module, root_module['ns3::PbbAddressTlvBlock']) register_Ns3PbbTlvBlock_methods(root_module, root_module['ns3::PbbTlvBlock']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Ipv6Header_methods(root_module, root_module['ns3::Ipv6Header']) register_Ns3LlcSnapHeader_methods(root_module, root_module['ns3::LlcSnapHeader']) register_Ns3Queue_methods(root_module, root_module['ns3::Queue']) register_Ns3RadiotapHeader_methods(root_module, root_module['ns3::RadiotapHeader']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketAddressTag_methods(root_module, root_module['ns3::SocketAddressTag']) register_Ns3SocketFactory_methods(root_module, root_module['ns3::SocketFactory']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3TcpSocket_methods(root_module, root_module['ns3::TcpSocket']) register_Ns3TcpSocketFactory_methods(root_module, root_module['ns3::TcpSocketFactory']) register_Ns3UdpSocket_methods(root_module, root_module['ns3::UdpSocket']) register_Ns3UdpSocketFactory_methods(root_module, root_module['ns3::UdpSocketFactory']) register_Ns3Application_methods(root_module, root_module['ns3::Application']) register_Ns3Channel_methods(root_module, root_module['ns3::Channel']) register_Ns3DropTailQueue_methods(root_module, root_module['ns3::DropTailQueue']) register_Ns3EthernetHeader_methods(root_module, root_module['ns3::EthernetHeader']) register_Ns3EthernetTrailer_methods(root_module, root_module['ns3::EthernetTrailer']) 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_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_Ns3Ipv4RawSocketFactory_methods(root_module, root_module['ns3::Ipv4RawSocketFactory']) register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route']) register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol']) register_Ns3Ipv6_methods(root_module, root_module['ns3::Ipv6']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6MulticastRoute_methods(root_module, root_module['ns3::Ipv6MulticastRoute']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3Ipv6RawSocketFactory_methods(root_module, root_module['ns3::Ipv6RawSocketFactory']) register_Ns3Ipv6Route_methods(root_module, root_module['ns3::Ipv6Route']) register_Ns3Ipv6RoutingProtocol_methods(root_module, root_module['ns3::Ipv6RoutingProtocol']) 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_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3PacketSocketFactory_methods(root_module, root_module['ns3::PacketSocketFactory']) register_Ns3PbbAddressBlock_methods(root_module, root_module['ns3::PbbAddressBlock']) register_Ns3PbbAddressBlockIpv4_methods(root_module, root_module['ns3::PbbAddressBlockIpv4']) register_Ns3PbbAddressBlockIpv6_methods(root_module, root_module['ns3::PbbAddressBlockIpv6']) register_Ns3PbbMessage_methods(root_module, root_module['ns3::PbbMessage']) register_Ns3PbbMessageIpv4_methods(root_module, root_module['ns3::PbbMessageIpv4']) register_Ns3PbbMessageIpv6_methods(root_module, root_module['ns3::PbbMessageIpv6']) register_Ns3PbbPacket_methods(root_module, root_module['ns3::PbbPacket']) register_Ns3PbbTlv_methods(root_module, root_module['ns3::PbbTlv']) register_Ns3SimpleChannel_methods(root_module, root_module['ns3::SimpleChannel']) register_Ns3SimpleNetDevice_methods(root_module, root_module['ns3::SimpleNetDevice']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3PbbAddressTlv_methods(root_module, root_module['ns3::PbbAddressTlv']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h: ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h: 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: ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h: 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: 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: 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: 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: 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: void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h: uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h: uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h: bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h: bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h: static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h: 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_Ns3ChannelList_methods(root_module, cls): ## channel-list.h: ns3::ChannelList::ChannelList() [constructor] cls.add_constructor([]) ## channel-list.h: ns3::ChannelList::ChannelList(ns3::ChannelList const & arg0) [copy constructor] cls.add_constructor([param('ns3::ChannelList const &', 'arg0')]) ## channel-list.h: static uint32_t ns3::ChannelList::Add(ns3::Ptr<ns3::Channel> channel) [member function] cls.add_method('Add', 'uint32_t', [param('ns3::Ptr< ns3::Channel >', 'channel')], is_static=True) ## channel-list.h: static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Channel>*,std::vector<ns3::Ptr<ns3::Channel>, std::allocator<ns3::Ptr<ns3::Channel> > > > ns3::ChannelList::Begin() [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Channel > const, std::vector< ns3::Ptr< ns3::Channel > > >', [], is_static=True) ## channel-list.h: static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Channel>*,std::vector<ns3::Ptr<ns3::Channel>, std::allocator<ns3::Ptr<ns3::Channel> > > > ns3::ChannelList::End() [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Channel > const, std::vector< ns3::Ptr< ns3::Channel > > >', [], is_static=True) ## channel-list.h: static ns3::Ptr<ns3::Channel> ns3::ChannelList::GetChannel(uint32_t n) [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [param('uint32_t', 'n')], is_static=True) ## channel-list.h: static uint32_t ns3::ChannelList::GetNChannels() [member function] cls.add_method('GetNChannels', 'uint32_t', [], is_static=True) return def register_Ns3Inet6SocketAddress_methods(root_module, cls): ## inet6-socket-address.h: ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')]) ## inet6-socket-address.h: 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: ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h: ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet6-socket-address.h: 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: ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor] cls.add_constructor([param('char const *', 'ipv6')]) ## inet6-socket-address.h: 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: ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function] cls.add_method('GetIpv6', 'ns3::Ipv6Address', [], is_const=True) ## inet6-socket-address.h: uint16_t ns3::Inet6SocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet6-socket-address.h: 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: void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function] cls.add_method('SetIpv6', 'void', [param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h: 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: ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')]) ## inet-socket-address.h: 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: ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')]) ## inet-socket-address.h: ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet-socket-address.h: 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: ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor] cls.add_constructor([param('char const *', 'ipv4')]) ## inet-socket-address.h: 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: ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function] cls.add_method('GetIpv4', 'ns3::Ipv4Address', [], is_const=True) ## inet-socket-address.h: uint16_t ns3::InetSocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet-socket-address.h: 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: void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ipv4Address', 'address')]) ## inet-socket-address.h: void ns3::InetSocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h: ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h: ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h: ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h: ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h: 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: 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: 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: uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h: static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h: static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h: static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h: 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: static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h: bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h: 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: 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: bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h: 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: 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: 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: void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h: void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4AddressGenerator_methods(root_module, cls): ## ipv4-address-generator.h: ns3::Ipv4AddressGenerator::Ipv4AddressGenerator() [constructor] cls.add_constructor([]) ## ipv4-address-generator.h: ns3::Ipv4AddressGenerator::Ipv4AddressGenerator(ns3::Ipv4AddressGenerator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressGenerator const &', 'arg0')]) ## ipv4-address-generator.h: static bool ns3::Ipv4AddressGenerator::AddAllocated(ns3::Ipv4Address const addr) [member function] cls.add_method('AddAllocated', 'bool', [param('ns3::Ipv4Address const', 'addr')], is_static=True) ## ipv4-address-generator.h: static ns3::Ipv4Address ns3::Ipv4AddressGenerator::GetAddress(ns3::Ipv4Mask const mask) [member function] cls.add_method('GetAddress', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const', 'mask')], is_static=True) ## ipv4-address-generator.h: static ns3::Ipv4Address ns3::Ipv4AddressGenerator::GetNetwork(ns3::Ipv4Mask const mask) [member function] cls.add_method('GetNetwork', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const', 'mask')], is_static=True) ## ipv4-address-generator.h: static void ns3::Ipv4AddressGenerator::Init(ns3::Ipv4Address const net, ns3::Ipv4Mask const mask, ns3::Ipv4Address const addr="0.0.0.1") [member function] cls.add_method('Init', 'void', [param('ns3::Ipv4Address const', 'net'), param('ns3::Ipv4Mask const', 'mask'), param('ns3::Ipv4Address const', 'addr', default_value='"0.0.0.1"')], is_static=True) ## ipv4-address-generator.h: static void ns3::Ipv4AddressGenerator::InitAddress(ns3::Ipv4Address const addr, ns3::Ipv4Mask const mask) [member function] cls.add_method('InitAddress', 'void', [param('ns3::Ipv4Address const', 'addr'), param('ns3::Ipv4Mask const', 'mask')], is_static=True) ## ipv4-address-generator.h: static ns3::Ipv4Address ns3::Ipv4AddressGenerator::NextAddress(ns3::Ipv4Mask const mask) [member function] cls.add_method('NextAddress', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const', 'mask')], is_static=True) ## ipv4-address-generator.h: static ns3::Ipv4Address ns3::Ipv4AddressGenerator::NextNetwork(ns3::Ipv4Mask const mask) [member function] cls.add_method('NextNetwork', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const', 'mask')], is_static=True) ## ipv4-address-generator.h: static void ns3::Ipv4AddressGenerator::Reset() [member function] cls.add_method('Reset', 'void', [], is_static=True) ## ipv4-address-generator.h: static void ns3::Ipv4AddressGenerator::TestMode() [member function] cls.add_method('TestMode', 'void', [], is_static=True) return def register_Ns3Ipv4InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-interface-address.h: ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv4-interface-address.h: 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: ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')]) ## ipv4-interface-address.h: ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h: ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function] cls.add_method('GetLocal', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h: ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function] cls.add_method('GetMask', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-interface-address.h: 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: bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function] cls.add_method('IsSecondary', 'bool', [], is_const=True) ## ipv4-interface-address.h: void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function] cls.add_method('SetBroadcast', 'void', [param('ns3::Ipv4Address', 'broadcast')]) ## ipv4-interface-address.h: void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv4Address', 'local')]) ## ipv4-interface-address.h: void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function] cls.add_method('SetMask', 'void', [param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h: void ns3::Ipv4InterfaceAddress::SetPrimary() [member function] cls.add_method('SetPrimary', 'void', []) ## ipv4-interface-address.h: 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: void ns3::Ipv4InterfaceAddress::SetSecondary() [member function] cls.add_method('SetSecondary', 'void', []) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h: ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h: ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h: ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h: ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h: uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h: uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h: static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h: static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h: uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h: static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h: 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: 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: 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: void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h: ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h: ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h: ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h: ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h: ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h: 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: 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: 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: static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h: static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h: static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h: static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h: 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: static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h: static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h: static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h: bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], is_const=True) ## ipv6-address.h: bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h: bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h: bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h: 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: bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h: bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h: 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: bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h: bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h: 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: 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: 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: 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: 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: void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h: void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-interface-address.h: ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv6-interface-address.h: ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'address')]) ## ipv6-interface-address.h: ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address, ns3::Ipv6Prefix prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6Prefix', 'prefix')]) ## ipv6-interface-address.h: ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv6InterfaceAddress const &', 'o')]) ## ipv6-interface-address.h: ns3::Ipv6Address ns3::Ipv6InterfaceAddress::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-interface-address.h: uint32_t ns3::Ipv6InterfaceAddress::GetNsDadUid() const [member function] cls.add_method('GetNsDadUid', 'uint32_t', [], is_const=True) ## ipv6-interface-address.h: ns3::Ipv6Prefix ns3::Ipv6InterfaceAddress::GetPrefix() const [member function] cls.add_method('GetPrefix', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-interface-address.h: ns3::Ipv6InterfaceAddress::Scope_e ns3::Ipv6InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv6InterfaceAddress::Scope_e', [], is_const=True) ## ipv6-interface-address.h: ns3::Ipv6InterfaceAddress::State_e ns3::Ipv6InterfaceAddress::GetState() const [member function] cls.add_method('GetState', 'ns3::Ipv6InterfaceAddress::State_e', [], is_const=True) ## ipv6-interface-address.h: void ns3::Ipv6InterfaceAddress::SetAddress(ns3::Ipv6Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Ipv6Address', 'address')]) ## ipv6-interface-address.h: void ns3::Ipv6InterfaceAddress::SetNsDadUid(uint32_t uid) [member function] cls.add_method('SetNsDadUid', 'void', [param('uint32_t', 'uid')]) ## ipv6-interface-address.h: void ns3::Ipv6InterfaceAddress::SetScope(ns3::Ipv6InterfaceAddress::Scope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv6InterfaceAddress::Scope_e', 'scope')]) ## ipv6-interface-address.h: void ns3::Ipv6InterfaceAddress::SetState(ns3::Ipv6InterfaceAddress::State_e state) [member function] cls.add_method('SetState', 'void', [param('ns3::Ipv6InterfaceAddress::State_e', 'state')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h: ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h: ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h: ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h: ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h: ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h: ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h: 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: static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h: static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h: uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h: static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h: 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: 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: void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h: ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h: ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h: ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h: static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h: 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: void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h: 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: static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h: 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: 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: static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h: static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h: bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h: bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h: static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3Mac64Address_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac64-address.h: ns3::Mac64Address::Mac64Address(ns3::Mac64Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac64Address const &', 'arg0')]) ## mac64-address.h: ns3::Mac64Address::Mac64Address() [constructor] cls.add_constructor([]) ## mac64-address.h: ns3::Mac64Address::Mac64Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac64-address.h: static ns3::Mac64Address ns3::Mac64Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac64Address', [], is_static=True) ## mac64-address.h: static ns3::Mac64Address ns3::Mac64Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac64Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac64-address.h: void ns3::Mac64Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac64-address.h: void ns3::Mac64Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac64-address.h: static bool ns3::Mac64Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NodeList_methods(root_module, cls): ## node-list.h: ns3::NodeList::NodeList() [constructor] cls.add_constructor([]) ## node-list.h: ns3::NodeList::NodeList(ns3::NodeList const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeList const &', 'arg0')]) ## node-list.h: static uint32_t ns3::NodeList::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'uint32_t', [param('ns3::Ptr< ns3::Node >', 'node')], is_static=True) ## node-list.h: static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::Begin() [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_static=True) ## node-list.h: static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::End() [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_static=True) ## node-list.h: static uint32_t ns3::NodeList::GetNNodes() [member function] cls.add_method('GetNNodes', 'uint32_t', [], is_static=True) ## node-list.h: static ns3::Ptr<ns3::Node> ns3::NodeList::GetNode(uint32_t n) [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'n')], is_static=True) return def register_Ns3PacketSocketAddress_methods(root_module, cls): ## packet-socket-address.h: ns3::PacketSocketAddress::PacketSocketAddress(ns3::PacketSocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketSocketAddress const &', 'arg0')]) ## packet-socket-address.h: ns3::PacketSocketAddress::PacketSocketAddress() [constructor] cls.add_constructor([]) ## packet-socket-address.h: static ns3::PacketSocketAddress ns3::PacketSocketAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::PacketSocketAddress', [param('ns3::Address const &', 'address')], is_static=True) ## packet-socket-address.h: ns3::Address ns3::PacketSocketAddress::GetPhysicalAddress() const [member function] cls.add_method('GetPhysicalAddress', 'ns3::Address', [], is_const=True) ## packet-socket-address.h: uint16_t ns3::PacketSocketAddress::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint16_t', [], is_const=True) ## packet-socket-address.h: uint32_t ns3::PacketSocketAddress::GetSingleDevice() const [member function] cls.add_method('GetSingleDevice', 'uint32_t', [], is_const=True) ## packet-socket-address.h: static bool ns3::PacketSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## packet-socket-address.h: bool ns3::PacketSocketAddress::IsSingleDevice() const [member function] cls.add_method('IsSingleDevice', 'bool', [], is_const=True) ## packet-socket-address.h: void ns3::PacketSocketAddress::SetAllDevices() [member function] cls.add_method('SetAllDevices', 'void', []) ## packet-socket-address.h: void ns3::PacketSocketAddress::SetPhysicalAddress(ns3::Address const address) [member function] cls.add_method('SetPhysicalAddress', 'void', [param('ns3::Address const', 'address')]) ## packet-socket-address.h: void ns3::PacketSocketAddress::SetProtocol(uint16_t protocol) [member function] cls.add_method('SetProtocol', 'void', [param('uint16_t', 'protocol')]) ## packet-socket-address.h: void ns3::PacketSocketAddress::SetSingleDevice(uint32_t device) [member function] cls.add_method('SetSingleDevice', 'void', [param('uint32_t', 'device')]) return def register_Ns3PbbAddressTlvBlock_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h: ns3::PbbAddressTlvBlock::PbbAddressTlvBlock(ns3::PbbAddressTlvBlock const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbAddressTlvBlock const &', 'arg0')]) ## packetbb.h: ns3::PbbAddressTlvBlock::PbbAddressTlvBlock() [constructor] cls.add_constructor([]) ## packetbb.h: ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressTlvBlock::Back() const [member function] cls.add_method('Back', 'ns3::Ptr< ns3::PbbAddressTlv >', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Begin() [member function] cls.add_method('Begin', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [], is_const=True) ## packetbb.h: void ns3::PbbAddressTlvBlock::Clear() [member function] cls.add_method('Clear', 'void', []) ## packetbb.h: void ns3::PbbAddressTlvBlock::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h: bool ns3::PbbAddressTlvBlock::Empty() const [member function] cls.add_method('Empty', 'bool', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::End() [member function] cls.add_method('End', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position')]) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > last) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'last')]) ## packetbb.h: ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressTlvBlock::Front() const [member function] cls.add_method('Front', 'ns3::Ptr< ns3::PbbAddressTlv >', [], is_const=True) ## packetbb.h: uint32_t ns3::PbbAddressTlvBlock::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Insert(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position, ns3::Ptr<ns3::PbbAddressTlv> const tlv) [member function] cls.add_method('Insert', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position'), param('ns3::Ptr< ns3::PbbAddressTlv > const', 'tlv')]) ## packetbb.h: void ns3::PbbAddressTlvBlock::PopBack() [member function] cls.add_method('PopBack', 'void', []) ## packetbb.h: void ns3::PbbAddressTlvBlock::PopFront() [member function] cls.add_method('PopFront', 'void', []) ## packetbb.h: void ns3::PbbAddressTlvBlock::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h: void ns3::PbbAddressTlvBlock::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h: void ns3::PbbAddressTlvBlock::PushBack(ns3::Ptr<ns3::PbbAddressTlv> tlv) [member function] cls.add_method('PushBack', 'void', [param('ns3::Ptr< ns3::PbbAddressTlv >', 'tlv')]) ## packetbb.h: void ns3::PbbAddressTlvBlock::PushFront(ns3::Ptr<ns3::PbbAddressTlv> tlv) [member function] cls.add_method('PushFront', 'void', [param('ns3::Ptr< ns3::PbbAddressTlv >', 'tlv')]) ## packetbb.h: void ns3::PbbAddressTlvBlock::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h: int ns3::PbbAddressTlvBlock::Size() const [member function] cls.add_method('Size', 'int', [], is_const=True) return def register_Ns3PbbTlvBlock_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h: ns3::PbbTlvBlock::PbbTlvBlock(ns3::PbbTlvBlock const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbTlvBlock const &', 'arg0')]) ## packetbb.h: ns3::PbbTlvBlock::PbbTlvBlock() [constructor] cls.add_constructor([]) ## packetbb.h: ns3::Ptr<ns3::PbbTlv> ns3::PbbTlvBlock::Back() const [member function] cls.add_method('Back', 'ns3::Ptr< ns3::PbbTlv >', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Begin() [member function] cls.add_method('Begin', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >', [], is_const=True) ## packetbb.h: void ns3::PbbTlvBlock::Clear() [member function] cls.add_method('Clear', 'void', []) ## packetbb.h: void ns3::PbbTlvBlock::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h: bool ns3::PbbTlvBlock::Empty() const [member function] cls.add_method('Empty', 'bool', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::End() [member function] cls.add_method('End', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')]) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')]) ## packetbb.h: ns3::Ptr<ns3::PbbTlv> ns3::PbbTlvBlock::Front() const [member function] cls.add_method('Front', 'ns3::Ptr< ns3::PbbTlv >', [], is_const=True) ## packetbb.h: uint32_t ns3::PbbTlvBlock::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Insert(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position, ns3::Ptr<ns3::PbbTlv> const tlv) [member function] cls.add_method('Insert', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position'), param('ns3::Ptr< ns3::PbbTlv > const', 'tlv')]) ## packetbb.h: void ns3::PbbTlvBlock::PopBack() [member function] cls.add_method('PopBack', 'void', []) ## packetbb.h: void ns3::PbbTlvBlock::PopFront() [member function] cls.add_method('PopFront', 'void', []) ## packetbb.h: void ns3::PbbTlvBlock::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h: void ns3::PbbTlvBlock::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h: void ns3::PbbTlvBlock::PushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('PushBack', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h: void ns3::PbbTlvBlock::PushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('PushFront', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h: void ns3::PbbTlvBlock::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h: int ns3::PbbTlvBlock::Size() const [member function] cls.add_method('Size', 'int', [], is_const=True) return def register_Ns3Ipv4Header_methods(root_module, cls): ## ipv4-header.h: ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')]) ## ipv4-header.h: ns3::Ipv4Header::Ipv4Header() [constructor] cls.add_constructor([]) ## ipv4-header.h: 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: void ns3::Ipv4Header::EnableChecksum() [member function] cls.add_method('EnableChecksum', 'void', []) ## ipv4-header.h: ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h: uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function] cls.add_method('GetFragmentOffset', 'uint16_t', [], is_const=True) ## ipv4-header.h: uint16_t ns3::Ipv4Header::GetIdentification() const [member function] cls.add_method('GetIdentification', 'uint16_t', [], is_const=True) ## ipv4-header.h: ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv4-header.h: uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function] cls.add_method('GetPayloadSize', 'uint16_t', [], is_const=True) ## ipv4-header.h: uint8_t ns3::Ipv4Header::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint8_t', [], is_const=True) ## ipv4-header.h: uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-header.h: ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h: uint8_t ns3::Ipv4Header::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## ipv4-header.h: uint8_t ns3::Ipv4Header::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## ipv4-header.h: static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-header.h: bool ns3::Ipv4Header::IsChecksumOk() const [member function] cls.add_method('IsChecksumOk', 'bool', [], is_const=True) ## ipv4-header.h: bool ns3::Ipv4Header::IsDontFragment() const [member function] cls.add_method('IsDontFragment', 'bool', [], is_const=True) ## ipv4-header.h: bool ns3::Ipv4Header::IsLastFragment() const [member function] cls.add_method('IsLastFragment', 'bool', [], is_const=True) ## ipv4-header.h: 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: 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: void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'destination')]) ## ipv4-header.h: void ns3::Ipv4Header::SetDontFragment() [member function] cls.add_method('SetDontFragment', 'void', []) ## ipv4-header.h: void ns3::Ipv4Header::SetFragmentOffset(uint16_t offset) [member function] cls.add_method('SetFragmentOffset', 'void', [param('uint16_t', 'offset')]) ## ipv4-header.h: void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function] cls.add_method('SetIdentification', 'void', [param('uint16_t', 'identification')]) ## ipv4-header.h: void ns3::Ipv4Header::SetLastFragment() [member function] cls.add_method('SetLastFragment', 'void', []) ## ipv4-header.h: void ns3::Ipv4Header::SetMayFragment() [member function] cls.add_method('SetMayFragment', 'void', []) ## ipv4-header.h: void ns3::Ipv4Header::SetMoreFragments() [member function] cls.add_method('SetMoreFragments', 'void', []) ## ipv4-header.h: void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function] cls.add_method('SetPayloadSize', 'void', [param('uint16_t', 'size')]) ## ipv4-header.h: void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function] cls.add_method('SetProtocol', 'void', [param('uint8_t', 'num')]) ## ipv4-header.h: void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'source')]) ## ipv4-header.h: void ns3::Ipv4Header::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) ## ipv4-header.h: void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3Ipv6Header_methods(root_module, cls): ## ipv6-header.h: ns3::Ipv6Header::Ipv6Header(ns3::Ipv6Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6Header const &', 'arg0')]) ## ipv6-header.h: ns3::Ipv6Header::Ipv6Header() [constructor] cls.add_constructor([]) ## ipv6-header.h: uint32_t ns3::Ipv6Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv6-header.h: ns3::Ipv6Address ns3::Ipv6Header::GetDestinationAddress() const [member function] cls.add_method('GetDestinationAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-header.h: uint32_t ns3::Ipv6Header::GetFlowLabel() const [member function] cls.add_method('GetFlowLabel', 'uint32_t', [], is_const=True) ## ipv6-header.h: uint8_t ns3::Ipv6Header::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## ipv6-header.h: ns3::TypeId ns3::Ipv6Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv6-header.h: uint8_t ns3::Ipv6Header::GetNextHeader() const [member function] cls.add_method('GetNextHeader', 'uint8_t', [], is_const=True) ## ipv6-header.h: uint16_t ns3::Ipv6Header::GetPayloadLength() const [member function] cls.add_method('GetPayloadLength', 'uint16_t', [], is_const=True) ## ipv6-header.h: uint32_t ns3::Ipv6Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv6-header.h: ns3::Ipv6Address ns3::Ipv6Header::GetSourceAddress() const [member function] cls.add_method('GetSourceAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-header.h: uint8_t ns3::Ipv6Header::GetTrafficClass() const [member function] cls.add_method('GetTrafficClass', 'uint8_t', [], is_const=True) ## ipv6-header.h: static ns3::TypeId ns3::Ipv6Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-header.h: void ns3::Ipv6Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv6-header.h: void ns3::Ipv6Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv6-header.h: void ns3::Ipv6Header::SetDestinationAddress(ns3::Ipv6Address dst) [member function] cls.add_method('SetDestinationAddress', 'void', [param('ns3::Ipv6Address', 'dst')]) ## ipv6-header.h: void ns3::Ipv6Header::SetFlowLabel(uint32_t flow) [member function] cls.add_method('SetFlowLabel', 'void', [param('uint32_t', 'flow')]) ## ipv6-header.h: void ns3::Ipv6Header::SetHopLimit(uint8_t limit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'limit')]) ## ipv6-header.h: void ns3::Ipv6Header::SetNextHeader(uint8_t next) [member function] cls.add_method('SetNextHeader', 'void', [param('uint8_t', 'next')]) ## ipv6-header.h: void ns3::Ipv6Header::SetPayloadLength(uint16_t len) [member function] cls.add_method('SetPayloadLength', 'void', [param('uint16_t', 'len')]) ## ipv6-header.h: void ns3::Ipv6Header::SetSourceAddress(ns3::Ipv6Address src) [member function] cls.add_method('SetSourceAddress', 'void', [param('ns3::Ipv6Address', 'src')]) ## ipv6-header.h: void ns3::Ipv6Header::SetTrafficClass(uint8_t traffic) [member function] cls.add_method('SetTrafficClass', 'void', [param('uint8_t', 'traffic')]) return def register_Ns3LlcSnapHeader_methods(root_module, cls): ## llc-snap-header.h: ns3::LlcSnapHeader::LlcSnapHeader(ns3::LlcSnapHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::LlcSnapHeader const &', 'arg0')]) ## llc-snap-header.h: ns3::LlcSnapHeader::LlcSnapHeader() [constructor] cls.add_constructor([]) ## llc-snap-header.h: uint32_t ns3::LlcSnapHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## llc-snap-header.h: ns3::TypeId ns3::LlcSnapHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## llc-snap-header.h: uint32_t ns3::LlcSnapHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## llc-snap-header.h: uint16_t ns3::LlcSnapHeader::GetType() [member function] cls.add_method('GetType', 'uint16_t', []) ## llc-snap-header.h: static ns3::TypeId ns3::LlcSnapHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## llc-snap-header.h: void ns3::LlcSnapHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## llc-snap-header.h: void ns3::LlcSnapHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## llc-snap-header.h: void ns3::LlcSnapHeader::SetType(uint16_t type) [member function] cls.add_method('SetType', 'void', [param('uint16_t', 'type')]) return def register_Ns3Queue_methods(root_module, cls): ## queue.h: ns3::Queue::Queue(ns3::Queue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Queue const &', 'arg0')]) ## queue.h: ns3::Queue::Queue() [constructor] cls.add_constructor([]) ## queue.h: ns3::Ptr<ns3::Packet> ns3::Queue::Dequeue() [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', []) ## queue.h: void ns3::Queue::DequeueAll() [member function] cls.add_method('DequeueAll', 'void', []) ## queue.h: bool ns3::Queue::Enqueue(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## queue.h: uint32_t ns3::Queue::GetNBytes() const [member function] cls.add_method('GetNBytes', 'uint32_t', [], is_const=True) ## queue.h: uint32_t ns3::Queue::GetNPackets() const [member function] cls.add_method('GetNPackets', 'uint32_t', [], is_const=True) ## queue.h: uint32_t ns3::Queue::GetTotalDroppedBytes() const [member function] cls.add_method('GetTotalDroppedBytes', 'uint32_t', [], is_const=True) ## queue.h: uint32_t ns3::Queue::GetTotalDroppedPackets() const [member function] cls.add_method('GetTotalDroppedPackets', 'uint32_t', [], is_const=True) ## queue.h: uint32_t ns3::Queue::GetTotalReceivedBytes() const [member function] cls.add_method('GetTotalReceivedBytes', 'uint32_t', [], is_const=True) ## queue.h: uint32_t ns3::Queue::GetTotalReceivedPackets() const [member function] cls.add_method('GetTotalReceivedPackets', 'uint32_t', [], is_const=True) ## queue.h: static ns3::TypeId ns3::Queue::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## queue.h: bool ns3::Queue::IsEmpty() const [member function] cls.add_method('IsEmpty', 'bool', [], is_const=True) ## queue.h: ns3::Ptr<ns3::Packet const> ns3::Queue::Peek() const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::Packet const >', [], is_const=True) ## queue.h: void ns3::Queue::ResetStatistics() [member function] cls.add_method('ResetStatistics', 'void', []) ## queue.h: void ns3::Queue::Drop(ns3::Ptr<ns3::Packet> packet) [member function] cls.add_method('Drop', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet')], visibility='protected') ## queue.h: ns3::Ptr<ns3::Packet> ns3::Queue::DoDequeue() [member function] cls.add_method('DoDequeue', 'ns3::Ptr< ns3::Packet >', [], is_pure_virtual=True, visibility='private', is_virtual=True) ## queue.h: bool ns3::Queue::DoEnqueue(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoEnqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], is_pure_virtual=True, visibility='private', is_virtual=True) ## queue.h: ns3::Ptr<ns3::Packet const> ns3::Queue::DoPeek() const [member function] cls.add_method('DoPeek', 'ns3::Ptr< ns3::Packet const >', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3RadiotapHeader_methods(root_module, cls): ## radiotap-header.h: ns3::RadiotapHeader::RadiotapHeader(ns3::RadiotapHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::RadiotapHeader const &', 'arg0')]) ## radiotap-header.h: ns3::RadiotapHeader::RadiotapHeader() [constructor] cls.add_constructor([]) ## radiotap-header.h: uint32_t ns3::RadiotapHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## radiotap-header.h: uint8_t ns3::RadiotapHeader::GetAntennaNoisePower() const [member function] cls.add_method('GetAntennaNoisePower', 'uint8_t', [], is_const=True) ## radiotap-header.h: uint8_t ns3::RadiotapHeader::GetAntennaSignalPower() const [member function] cls.add_method('GetAntennaSignalPower', 'uint8_t', [], is_const=True) ## radiotap-header.h: uint16_t ns3::RadiotapHeader::GetChannelFlags() const [member function] cls.add_method('GetChannelFlags', 'uint16_t', [], is_const=True) ## radiotap-header.h: uint16_t ns3::RadiotapHeader::GetChannelFrequency() const [member function] cls.add_method('GetChannelFrequency', 'uint16_t', [], is_const=True) ## radiotap-header.h: uint8_t ns3::RadiotapHeader::GetFrameFlags() const [member function] cls.add_method('GetFrameFlags', 'uint8_t', [], is_const=True) ## radiotap-header.h: ns3::TypeId ns3::RadiotapHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## radiotap-header.h: uint8_t ns3::RadiotapHeader::GetRate() const [member function] cls.add_method('GetRate', 'uint8_t', [], is_const=True) ## radiotap-header.h: uint32_t ns3::RadiotapHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## radiotap-header.h: uint64_t ns3::RadiotapHeader::GetTsft() const [member function] cls.add_method('GetTsft', 'uint64_t', [], is_const=True) ## radiotap-header.h: static ns3::TypeId ns3::RadiotapHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## radiotap-header.h: void ns3::RadiotapHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## radiotap-header.h: void ns3::RadiotapHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## radiotap-header.h: void ns3::RadiotapHeader::SetAntennaNoisePower(int8_t noise) [member function] cls.add_method('SetAntennaNoisePower', 'void', [param('int8_t', 'noise')]) ## radiotap-header.h: void ns3::RadiotapHeader::SetAntennaNoisePower(double noise) [member function] cls.add_method('SetAntennaNoisePower', 'void', [param('double', 'noise')]) ## radiotap-header.h: void ns3::RadiotapHeader::SetAntennaSignalPower(int8_t signal) [member function] cls.add_method('SetAntennaSignalPower', 'void', [param('int8_t', 'signal')]) ## radiotap-header.h: void ns3::RadiotapHeader::SetAntennaSignalPower(double signal) [member function] cls.add_method('SetAntennaSignalPower', 'void', [param('double', 'signal')]) ## radiotap-header.h: void ns3::RadiotapHeader::SetChannelFrequencyAndFlags(uint16_t frequency, uint16_t flags) [member function] cls.add_method('SetChannelFrequencyAndFlags', 'void', [param('uint16_t', 'frequency'), param('uint16_t', 'flags')]) ## radiotap-header.h: void ns3::RadiotapHeader::SetFrameFlags(uint8_t flags) [member function] cls.add_method('SetFrameFlags', 'void', [param('uint8_t', 'flags')]) ## radiotap-header.h: void ns3::RadiotapHeader::SetRate(uint8_t rate) [member function] cls.add_method('SetRate', 'void', [param('uint8_t', 'rate')]) ## radiotap-header.h: void ns3::RadiotapHeader::SetTsft(uint64_t tsft) [member function] cls.add_method('SetTsft', 'void', [param('uint64_t', 'tsft')]) return def register_Ns3Socket_methods(root_module, cls): ## socket.h: ns3::Socket::Socket(ns3::Socket const & arg0) [copy constructor] cls.add_constructor([param('ns3::Socket const &', 'arg0')]) ## socket.h: ns3::Socket::Socket() [constructor] cls.add_constructor([]) ## socket.h: 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: int ns3::Socket::Bind() [member function] cls.add_method('Bind', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h: 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: int ns3::Socket::Close() [member function] cls.add_method('Close', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h: 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: 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: ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function] cls.add_method('GetBoundNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## socket.h: 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: 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: 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: 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: 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: int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h: 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: ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h: 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: 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: 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: 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: 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: int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h: 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: 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: 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: void ns3::Socket::SetAcceptCallback(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, 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) [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: 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: 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: 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: 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: 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: int ns3::Socket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h: int ns3::Socket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h: void ns3::Socket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## socket.h: void ns3::Socket::NotifyConnectionFailed() [member function] cls.add_method('NotifyConnectionFailed', 'void', [], visibility='protected') ## socket.h: bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function] cls.add_method('NotifyConnectionRequest', 'bool', [param('ns3::Address const &', 'from')], visibility='protected') ## socket.h: void ns3::Socket::NotifyConnectionSucceeded() [member function] cls.add_method('NotifyConnectionSucceeded', 'void', [], visibility='protected') ## socket.h: void ns3::Socket::NotifyDataRecv() [member function] cls.add_method('NotifyDataRecv', 'void', [], visibility='protected') ## socket.h: void ns3::Socket::NotifyDataSent(uint32_t size) [member function] cls.add_method('NotifyDataSent', 'void', [param('uint32_t', 'size')], visibility='protected') ## socket.h: void ns3::Socket::NotifyErrorClose() [member function] cls.add_method('NotifyErrorClose', 'void', [], visibility='protected') ## socket.h: 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: void ns3::Socket::NotifyNormalClose() [member function] cls.add_method('NotifyNormalClose', 'void', [], visibility='protected') ## socket.h: void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function] cls.add_method('NotifySend', 'void', [param('uint32_t', 'spaceAvailable')], visibility='protected') return def register_Ns3SocketAddressTag_methods(root_module, cls): ## socket.h: ns3::SocketAddressTag::SocketAddressTag(ns3::SocketAddressTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketAddressTag const &', 'arg0')]) ## socket.h: ns3::SocketAddressTag::SocketAddressTag() [constructor] cls.add_constructor([]) ## socket.h: void ns3::SocketAddressTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h: ns3::Address ns3::SocketAddressTag::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True) ## socket.h: ns3::TypeId ns3::SocketAddressTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h: uint32_t ns3::SocketAddressTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h: static ns3::TypeId ns3::SocketAddressTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h: void ns3::SocketAddressTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h: void ns3::SocketAddressTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h: void ns3::SocketAddressTag::SetAddress(ns3::Address addr) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'addr')]) return def register_Ns3SocketFactory_methods(root_module, cls): ## socket-factory.h: ns3::SocketFactory::SocketFactory(ns3::SocketFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketFactory const &', 'arg0')]) ## socket-factory.h: ns3::SocketFactory::SocketFactory() [constructor] cls.add_constructor([]) ## socket-factory.h: ns3::Ptr<ns3::Socket> ns3::SocketFactory::CreateSocket() [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [], is_pure_virtual=True, is_virtual=True) ## socket-factory.h: static ns3::TypeId ns3::SocketFactory::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3SocketIpTtlTag_methods(root_module, cls): ## socket.h: ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')]) ## socket.h: ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor] cls.add_constructor([]) ## socket.h: void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h: ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h: uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h: uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## socket.h: static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h: 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: 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: void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h: ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) ## socket.h: ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] cls.add_constructor([]) ## socket.h: void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h: void ns3::SocketSetDontFragmentTag::Disable() [member function] cls.add_method('Disable', 'void', []) ## socket.h: void ns3::SocketSetDontFragmentTag::Enable() [member function] cls.add_method('Enable', 'void', []) ## socket.h: ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h: uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h: static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h: bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## socket.h: 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: 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_Ns3TcpSocket_methods(root_module, cls): ## tcp-socket.h: ns3::TcpSocket::TcpSocket(ns3::TcpSocket const & arg0) [copy constructor] cls.add_constructor([param('ns3::TcpSocket const &', 'arg0')]) ## tcp-socket.h: ns3::TcpSocket::TcpSocket() [constructor] cls.add_constructor([]) ## tcp-socket.h: static ns3::TypeId ns3::TcpSocket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tcp-socket.h: uint32_t ns3::TcpSocket::GetConnCount() const [member function] cls.add_method('GetConnCount', 'uint32_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## tcp-socket.h: ns3::Time ns3::TcpSocket::GetConnTimeout() const [member function] cls.add_method('GetConnTimeout', 'ns3::Time', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## tcp-socket.h: uint32_t ns3::TcpSocket::GetDelAckMaxCount() const [member function] cls.add_method('GetDelAckMaxCount', 'uint32_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## tcp-socket.h: ns3::Time ns3::TcpSocket::GetDelAckTimeout() const [member function] cls.add_method('GetDelAckTimeout', 'ns3::Time', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## tcp-socket.h: uint32_t ns3::TcpSocket::GetInitialCwnd() const [member function] cls.add_method('GetInitialCwnd', 'uint32_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## tcp-socket.h: uint32_t ns3::TcpSocket::GetRcvBufSize() const [member function] cls.add_method('GetRcvBufSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## tcp-socket.h: uint32_t ns3::TcpSocket::GetSSThresh() const [member function] cls.add_method('GetSSThresh', 'uint32_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## tcp-socket.h: uint32_t ns3::TcpSocket::GetSegSize() const [member function] cls.add_method('GetSegSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## tcp-socket.h: uint32_t ns3::TcpSocket::GetSndBufSize() const [member function] cls.add_method('GetSndBufSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## tcp-socket.h: void ns3::TcpSocket::SetConnCount(uint32_t count) [member function] cls.add_method('SetConnCount', 'void', [param('uint32_t', 'count')], is_pure_virtual=True, visibility='private', is_virtual=True) ## tcp-socket.h: void ns3::TcpSocket::SetConnTimeout(ns3::Time timeout) [member function] cls.add_method('SetConnTimeout', 'void', [param('ns3::Time', 'timeout')], is_pure_virtual=True, visibility='private', is_virtual=True) ## tcp-socket.h: void ns3::TcpSocket::SetDelAckMaxCount(uint32_t count) [member function] cls.add_method('SetDelAckMaxCount', 'void', [param('uint32_t', 'count')], is_pure_virtual=True, visibility='private', is_virtual=True) ## tcp-socket.h: void ns3::TcpSocket::SetDelAckTimeout(ns3::Time timeout) [member function] cls.add_method('SetDelAckTimeout', 'void', [param('ns3::Time', 'timeout')], is_pure_virtual=True, visibility='private', is_virtual=True) ## tcp-socket.h: void ns3::TcpSocket::SetInitialCwnd(uint32_t count) [member function] cls.add_method('SetInitialCwnd', 'void', [param('uint32_t', 'count')], is_pure_virtual=True, visibility='private', is_virtual=True) ## tcp-socket.h: void ns3::TcpSocket::SetRcvBufSize(uint32_t size) [member function] cls.add_method('SetRcvBufSize', 'void', [param('uint32_t', 'size')], is_pure_virtual=True, visibility='private', is_virtual=True) ## tcp-socket.h: void ns3::TcpSocket::SetSSThresh(uint32_t threshold) [member function] cls.add_method('SetSSThresh', 'void', [param('uint32_t', 'threshold')], is_pure_virtual=True, visibility='private', is_virtual=True) ## tcp-socket.h: void ns3::TcpSocket::SetSegSize(uint32_t size) [member function] cls.add_method('SetSegSize', 'void', [param('uint32_t', 'size')], is_pure_virtual=True, visibility='private', is_virtual=True) ## tcp-socket.h: void ns3::TcpSocket::SetSndBufSize(uint32_t size) [member function] cls.add_method('SetSndBufSize', 'void', [param('uint32_t', 'size')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3TcpSocketFactory_methods(root_module, cls): ## tcp-socket-factory.h: ns3::TcpSocketFactory::TcpSocketFactory() [constructor] cls.add_constructor([]) ## tcp-socket-factory.h: ns3::TcpSocketFactory::TcpSocketFactory(ns3::TcpSocketFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::TcpSocketFactory const &', 'arg0')]) ## tcp-socket-factory.h: static ns3::TypeId ns3::TcpSocketFactory::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3UdpSocket_methods(root_module, cls): ## udp-socket.h: ns3::UdpSocket::UdpSocket(ns3::UdpSocket const & arg0) [copy constructor] cls.add_constructor([param('ns3::UdpSocket const &', 'arg0')]) ## udp-socket.h: ns3::UdpSocket::UdpSocket() [constructor] cls.add_constructor([]) ## udp-socket.h: static ns3::TypeId ns3::UdpSocket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## udp-socket.h: int ns3::UdpSocket::MulticastJoinGroup(uint32_t interface, ns3::Address const & groupAddress) [member function] cls.add_method('MulticastJoinGroup', 'int', [param('uint32_t', 'interface'), param('ns3::Address const &', 'groupAddress')], is_pure_virtual=True, is_virtual=True) ## udp-socket.h: int ns3::UdpSocket::MulticastLeaveGroup(uint32_t interface, ns3::Address const & groupAddress) [member function] cls.add_method('MulticastLeaveGroup', 'int', [param('uint32_t', 'interface'), param('ns3::Address const &', 'groupAddress')], is_pure_virtual=True, is_virtual=True) ## udp-socket.h: int32_t ns3::UdpSocket::GetIpMulticastIf() const [member function] cls.add_method('GetIpMulticastIf', 'int32_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## udp-socket.h: bool ns3::UdpSocket::GetIpMulticastLoop() const [member function] cls.add_method('GetIpMulticastLoop', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## udp-socket.h: uint8_t ns3::UdpSocket::GetIpMulticastTtl() const [member function] cls.add_method('GetIpMulticastTtl', 'uint8_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## udp-socket.h: uint8_t ns3::UdpSocket::GetIpTtl() const [member function] cls.add_method('GetIpTtl', 'uint8_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## udp-socket.h: bool ns3::UdpSocket::GetMtuDiscover() const [member function] cls.add_method('GetMtuDiscover', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## udp-socket.h: uint32_t ns3::UdpSocket::GetRcvBufSize() const [member function] cls.add_method('GetRcvBufSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## udp-socket.h: void ns3::UdpSocket::SetIpMulticastIf(int32_t ipIf) [member function] cls.add_method('SetIpMulticastIf', 'void', [param('int32_t', 'ipIf')], is_pure_virtual=True, visibility='private', is_virtual=True) ## udp-socket.h: void ns3::UdpSocket::SetIpMulticastLoop(bool loop) [member function] cls.add_method('SetIpMulticastLoop', 'void', [param('bool', 'loop')], is_pure_virtual=True, visibility='private', is_virtual=True) ## udp-socket.h: void ns3::UdpSocket::SetIpMulticastTtl(uint8_t ipTtl) [member function] cls.add_method('SetIpMulticastTtl', 'void', [param('uint8_t', 'ipTtl')], is_pure_virtual=True, visibility='private', is_virtual=True) ## udp-socket.h: void ns3::UdpSocket::SetIpTtl(uint8_t ipTtl) [member function] cls.add_method('SetIpTtl', 'void', [param('uint8_t', 'ipTtl')], is_pure_virtual=True, visibility='private', is_virtual=True) ## udp-socket.h: void ns3::UdpSocket::SetMtuDiscover(bool discover) [member function] cls.add_method('SetMtuDiscover', 'void', [param('bool', 'discover')], is_pure_virtual=True, visibility='private', is_virtual=True) ## udp-socket.h: void ns3::UdpSocket::SetRcvBufSize(uint32_t size) [member function] cls.add_method('SetRcvBufSize', 'void', [param('uint32_t', 'size')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3UdpSocketFactory_methods(root_module, cls): ## udp-socket-factory.h: ns3::UdpSocketFactory::UdpSocketFactory() [constructor] cls.add_constructor([]) ## udp-socket-factory.h: ns3::UdpSocketFactory::UdpSocketFactory(ns3::UdpSocketFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::UdpSocketFactory const &', 'arg0')]) ## udp-socket-factory.h: static ns3::TypeId ns3::UdpSocketFactory::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3Application_methods(root_module, cls): ## application.h: ns3::Application::Application(ns3::Application const & arg0) [copy constructor] cls.add_constructor([param('ns3::Application const &', 'arg0')]) ## application.h: ns3::Application::Application() [constructor] cls.add_constructor([]) ## application.h: ns3::Ptr<ns3::Node> ns3::Application::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True) ## application.h: static ns3::TypeId ns3::Application::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## application.h: void ns3::Application::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## application.h: void ns3::Application::SetStartTime(ns3::Time start) [member function] cls.add_method('SetStartTime', 'void', [param('ns3::Time', 'start')]) ## application.h: void ns3::Application::SetStopTime(ns3::Time stop) [member function] cls.add_method('SetStopTime', 'void', [param('ns3::Time', 'stop')]) ## application.h: void ns3::Application::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## application.h: void ns3::Application::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='protected', is_virtual=True) ## application.h: void ns3::Application::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## application.h: void ns3::Application::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=True) return def register_Ns3Channel_methods(root_module, cls): ## channel.h: ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor] cls.add_constructor([param('ns3::Channel const &', 'arg0')]) ## channel.h: ns3::Channel::Channel() [constructor] cls.add_constructor([]) ## channel.h: ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h: uint32_t ns3::Channel::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## channel.h: uint32_t ns3::Channel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h: static ns3::TypeId ns3::Channel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3DropTailQueue_methods(root_module, cls): ## drop-tail-queue.h: ns3::DropTailQueue::DropTailQueue(ns3::DropTailQueue const & arg0) [copy constructor] cls.add_constructor([param('ns3::DropTailQueue const &', 'arg0')]) ## drop-tail-queue.h: ns3::DropTailQueue::DropTailQueue() [constructor] cls.add_constructor([]) ## drop-tail-queue.h: ns3::DropTailQueue::Mode ns3::DropTailQueue::GetMode() [member function] cls.add_method('GetMode', 'ns3::DropTailQueue::Mode', []) ## drop-tail-queue.h: static ns3::TypeId ns3::DropTailQueue::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## drop-tail-queue.h: void ns3::DropTailQueue::SetMode(ns3::DropTailQueue::Mode mode) [member function] cls.add_method('SetMode', 'void', [param('ns3::DropTailQueue::Mode', 'mode')]) ## drop-tail-queue.h: ns3::Ptr<ns3::Packet> ns3::DropTailQueue::DoDequeue() [member function] cls.add_method('DoDequeue', 'ns3::Ptr< ns3::Packet >', [], visibility='private', is_virtual=True) ## drop-tail-queue.h: bool ns3::DropTailQueue::DoEnqueue(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoEnqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## drop-tail-queue.h: ns3::Ptr<ns3::Packet const> ns3::DropTailQueue::DoPeek() const [member function] cls.add_method('DoPeek', 'ns3::Ptr< ns3::Packet const >', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3EthernetHeader_methods(root_module, cls): ## ethernet-header.h: ns3::EthernetHeader::EthernetHeader(ns3::EthernetHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::EthernetHeader const &', 'arg0')]) ## ethernet-header.h: ns3::EthernetHeader::EthernetHeader(bool hasPreamble) [constructor] cls.add_constructor([param('bool', 'hasPreamble')]) ## ethernet-header.h: ns3::EthernetHeader::EthernetHeader() [constructor] cls.add_constructor([]) ## ethernet-header.h: uint32_t ns3::EthernetHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ethernet-header.h: ns3::Mac48Address ns3::EthernetHeader::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Mac48Address', [], is_const=True) ## ethernet-header.h: uint32_t ns3::EthernetHeader::GetHeaderSize() const [member function] cls.add_method('GetHeaderSize', 'uint32_t', [], is_const=True) ## ethernet-header.h: ns3::TypeId ns3::EthernetHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ethernet-header.h: uint16_t ns3::EthernetHeader::GetLengthType() const [member function] cls.add_method('GetLengthType', 'uint16_t', [], is_const=True) ## ethernet-header.h: ns3::ethernet_header_t ns3::EthernetHeader::GetPacketType() const [member function] cls.add_method('GetPacketType', 'ns3::ethernet_header_t', [], is_const=True) ## ethernet-header.h: uint64_t ns3::EthernetHeader::GetPreambleSfd() const [member function] cls.add_method('GetPreambleSfd', 'uint64_t', [], is_const=True) ## ethernet-header.h: uint32_t ns3::EthernetHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ethernet-header.h: ns3::Mac48Address ns3::EthernetHeader::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Mac48Address', [], is_const=True) ## ethernet-header.h: static ns3::TypeId ns3::EthernetHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ethernet-header.h: void ns3::EthernetHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ethernet-header.h: void ns3::EthernetHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ethernet-header.h: void ns3::EthernetHeader::SetDestination(ns3::Mac48Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Mac48Address', 'destination')]) ## ethernet-header.h: void ns3::EthernetHeader::SetLengthType(uint16_t size) [member function] cls.add_method('SetLengthType', 'void', [param('uint16_t', 'size')]) ## ethernet-header.h: void ns3::EthernetHeader::SetPreambleSfd(uint64_t preambleSfd) [member function] cls.add_method('SetPreambleSfd', 'void', [param('uint64_t', 'preambleSfd')]) ## ethernet-header.h: void ns3::EthernetHeader::SetSource(ns3::Mac48Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Mac48Address', 'source')]) return def register_Ns3EthernetTrailer_methods(root_module, cls): ## ethernet-trailer.h: ns3::EthernetTrailer::EthernetTrailer(ns3::EthernetTrailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::EthernetTrailer const &', 'arg0')]) ## ethernet-trailer.h: ns3::EthernetTrailer::EthernetTrailer() [constructor] cls.add_constructor([]) ## ethernet-trailer.h: void ns3::EthernetTrailer::CalcFcs(ns3::Ptr<ns3::Packet const> p) [member function] cls.add_method('CalcFcs', 'void', [param('ns3::Ptr< ns3::Packet const >', 'p')]) ## ethernet-trailer.h: bool ns3::EthernetTrailer::CheckFcs(ns3::Ptr<ns3::Packet const> p) const [member function] cls.add_method('CheckFcs', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p')], is_const=True) ## ethernet-trailer.h: uint32_t ns3::EthernetTrailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_virtual=True) ## ethernet-trailer.h: void ns3::EthernetTrailer::EnableFcs(bool enable) [member function] cls.add_method('EnableFcs', 'void', [param('bool', 'enable')]) ## ethernet-trailer.h: uint32_t ns3::EthernetTrailer::GetFcs() [member function] cls.add_method('GetFcs', 'uint32_t', []) ## ethernet-trailer.h: ns3::TypeId ns3::EthernetTrailer::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ethernet-trailer.h: uint32_t ns3::EthernetTrailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ethernet-trailer.h: uint32_t ns3::EthernetTrailer::GetTrailerSize() const [member function] cls.add_method('GetTrailerSize', 'uint32_t', [], is_const=True) ## ethernet-trailer.h: static ns3::TypeId ns3::EthernetTrailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ethernet-trailer.h: void ns3::EthernetTrailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ethernet-trailer.h: void ns3::EthernetTrailer::Serialize(ns3::Buffer::Iterator end) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'end')], is_const=True, is_virtual=True) ## ethernet-trailer.h: void ns3::EthernetTrailer::SetFcs(uint32_t fcs) [member function] cls.add_method('SetFcs', 'void', [param('uint32_t', 'fcs')]) return def register_Ns3Ipv4_methods(root_module, cls): ## ipv4.h: ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')]) ## ipv4.h: ns3::Ipv4::Ipv4() [constructor] cls.add_constructor([]) ## ipv4.h: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: static ns3::TypeId ns3::Ipv4::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4.h: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: ns3::Ipv4::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv4.h: 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: 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: 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: 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: ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h: ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h: ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h: ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h: ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h: 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: bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h: ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h: std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h: void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h: ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h: ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h: ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h: ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h: ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h: 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: bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h: ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h: std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h: 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: ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')]) ## ipv4-route.h: ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor] cls.add_constructor([]) ## ipv4-route.h: ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function] cls.add_method('GetGroup', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h: ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function] cls.add_method('GetOrigin', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h: uint32_t ns3::Ipv4MulticastRoute::GetOutputTtl(uint32_t oif) const [member function] cls.add_method('GetOutputTtl', 'uint32_t', [param('uint32_t', 'oif')], is_const=True) ## ipv4-route.h: uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function] cls.add_method('GetParent', 'uint32_t', [], is_const=True) ## ipv4-route.h: void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function] cls.add_method('SetGroup', 'void', [param('ns3::Ipv4Address const', 'group')]) ## ipv4-route.h: void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function] cls.add_method('SetOrigin', 'void', [param('ns3::Ipv4Address const', 'origin')]) ## ipv4-route.h: 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: void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function] cls.add_method('SetParent', 'void', [param('uint32_t', 'iif')]) ## ipv4-route.h: ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable] cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True) ## ipv4-route.h: ns3::Ipv4MulticastRoute::MAX_TTL [variable] cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True) return def register_Ns3Ipv4RawSocketFactory_methods(root_module, cls): ## ipv4-raw-socket-factory.h: ns3::Ipv4RawSocketFactory::Ipv4RawSocketFactory() [constructor] cls.add_constructor([]) ## ipv4-raw-socket-factory.h: ns3::Ipv4RawSocketFactory::Ipv4RawSocketFactory(ns3::Ipv4RawSocketFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4RawSocketFactory const &', 'arg0')]) ## ipv4-raw-socket-factory.h: static ns3::TypeId ns3::Ipv4RawSocketFactory::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3Ipv4Route_methods(root_module, cls): cls.add_output_stream_operator() ## ipv4-route.h: ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')]) ## ipv4-route.h: ns3::Ipv4Route::Ipv4Route() [constructor] cls.add_constructor([]) ## ipv4-route.h: ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h: ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function] cls.add_method('GetGateway', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h: ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-route.h: ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h: void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'dest')]) ## ipv4-route.h: void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function] cls.add_method('SetGateway', 'void', [param('ns3::Ipv4Address', 'gw')]) ## ipv4-route.h: 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: 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: ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor] cls.add_constructor([]) ## ipv4-routing-protocol.h: ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')]) ## ipv4-routing-protocol.h: static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-routing-protocol.h: 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: 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: 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: 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: bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<ns3::Packet const> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, 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, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, 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) [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: 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: 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_Ns3Ipv6_methods(root_module, cls): ## ipv6.h: ns3::Ipv6::Ipv6(ns3::Ipv6 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6 const &', 'arg0')]) ## ipv6.h: ns3::Ipv6::Ipv6() [constructor] cls.add_constructor([]) ## ipv6.h: bool ns3::Ipv6::AddAddress(uint32_t interface, ns3::Ipv6InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv6InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv6.h: uint32_t ns3::Ipv6::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) ## ipv6.h: ns3::Ipv6InterfaceAddress ns3::Ipv6::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h: int32_t ns3::Ipv6::GetInterfaceForAddress(ns3::Ipv6Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv6Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h: int32_t ns3::Ipv6::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) ## ipv6.h: int32_t ns3::Ipv6::GetInterfaceForPrefix(ns3::Ipv6Address address, ns3::Ipv6Prefix mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6Prefix', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h: uint16_t ns3::Ipv6::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) ## ipv6.h: uint16_t ns3::Ipv6::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) ## ipv6.h: uint32_t ns3::Ipv6::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) ## ipv6.h: uint32_t ns3::Ipv6::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h: ns3::Ptr<ns3::NetDevice> ns3::Ipv6::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) ## ipv6.h: ns3::Ptr<ns3::Ipv6RoutingProtocol> ns3::Ipv6::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv6RoutingProtocol >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h: static ns3::TypeId ns3::Ipv6::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6.h: bool ns3::Ipv6::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) ## ipv6.h: bool ns3::Ipv6::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) ## ipv6.h: void ns3::Ipv6::RegisterExtensions() [member function] cls.add_method('RegisterExtensions', 'void', [], is_pure_virtual=True, is_virtual=True) ## ipv6.h: void ns3::Ipv6::RegisterOptions() [member function] cls.add_method('RegisterOptions', 'void', [], is_pure_virtual=True, is_virtual=True) ## ipv6.h: bool ns3::Ipv6::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) ## ipv6.h: void ns3::Ipv6::SetDown(uint32_t interface) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv6.h: void ns3::Ipv6::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) ## ipv6.h: void ns3::Ipv6::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) ## ipv6.h: void ns3::Ipv6::SetRoutingProtocol(ns3::Ptr<ns3::Ipv6RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv6RoutingProtocol >', 'routingProtocol')], is_pure_virtual=True, is_virtual=True) ## ipv6.h: void ns3::Ipv6::SetUp(uint32_t interface) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv6.h: ns3::Ipv6::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv6.h: bool ns3::Ipv6::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv6.h: void ns3::Ipv6::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h: ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h: ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h: ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h: ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h: ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h: 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: bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h: ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h: std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h: void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6MulticastRoute_methods(root_module, cls): cls.add_output_stream_operator() ## ipv6-route.h: ns3::Ipv6MulticastRoute::Ipv6MulticastRoute(ns3::Ipv6MulticastRoute const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6MulticastRoute const &', 'arg0')]) ## ipv6-route.h: ns3::Ipv6MulticastRoute::Ipv6MulticastRoute() [constructor] cls.add_constructor([]) ## ipv6-route.h: ns3::Ipv6Address ns3::Ipv6MulticastRoute::GetGroup() const [member function] cls.add_method('GetGroup', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-route.h: ns3::Ipv6Address ns3::Ipv6MulticastRoute::GetOrigin() const [member function] cls.add_method('GetOrigin', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-route.h: uint32_t ns3::Ipv6MulticastRoute::GetOutputTtl(uint32_t oif) const [member function] cls.add_method('GetOutputTtl', 'uint32_t', [param('uint32_t', 'oif')], is_const=True) ## ipv6-route.h: uint32_t ns3::Ipv6MulticastRoute::GetParent() const [member function] cls.add_method('GetParent', 'uint32_t', [], is_const=True) ## ipv6-route.h: void ns3::Ipv6MulticastRoute::SetGroup(ns3::Ipv6Address const group) [member function] cls.add_method('SetGroup', 'void', [param('ns3::Ipv6Address const', 'group')]) ## ipv6-route.h: void ns3::Ipv6MulticastRoute::SetOrigin(ns3::Ipv6Address const origin) [member function] cls.add_method('SetOrigin', 'void', [param('ns3::Ipv6Address const', 'origin')]) ## ipv6-route.h: void ns3::Ipv6MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function] cls.add_method('SetOutputTtl', 'void', [param('uint32_t', 'oif'), param('uint32_t', 'ttl')]) ## ipv6-route.h: void ns3::Ipv6MulticastRoute::SetParent(uint32_t iif) [member function] cls.add_method('SetParent', 'void', [param('uint32_t', 'iif')]) ## ipv6-route.h: ns3::Ipv6MulticastRoute::MAX_INTERFACES [variable] cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True) ## ipv6-route.h: ns3::Ipv6MulticastRoute::MAX_TTL [variable] cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h: ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h: ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h: ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h: ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h: ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h: 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: bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h: ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h: std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h: void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3Ipv6RawSocketFactory_methods(root_module, cls): ## ipv6-raw-socket-factory.h: ns3::Ipv6RawSocketFactory::Ipv6RawSocketFactory() [constructor] cls.add_constructor([]) ## ipv6-raw-socket-factory.h: ns3::Ipv6RawSocketFactory::Ipv6RawSocketFactory(ns3::Ipv6RawSocketFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6RawSocketFactory const &', 'arg0')]) ## ipv6-raw-socket-factory.h: static ns3::TypeId ns3::Ipv6RawSocketFactory::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3Ipv6Route_methods(root_module, cls): cls.add_output_stream_operator() ## ipv6-route.h: ns3::Ipv6Route::Ipv6Route(ns3::Ipv6Route const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6Route const &', 'arg0')]) ## ipv6-route.h: ns3::Ipv6Route::Ipv6Route() [constructor] cls.add_constructor([]) ## ipv6-route.h: ns3::Ipv6Address ns3::Ipv6Route::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-route.h: ns3::Ipv6Address ns3::Ipv6Route::GetGateway() const [member function] cls.add_method('GetGateway', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-route.h: ns3::Ptr<ns3::NetDevice> ns3::Ipv6Route::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv6-route.h: ns3::Ipv6Address ns3::Ipv6Route::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-route.h: void ns3::Ipv6Route::SetDestination(ns3::Ipv6Address dest) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv6Address', 'dest')]) ## ipv6-route.h: void ns3::Ipv6Route::SetGateway(ns3::Ipv6Address gw) [member function] cls.add_method('SetGateway', 'void', [param('ns3::Ipv6Address', 'gw')]) ## ipv6-route.h: void ns3::Ipv6Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function] cls.add_method('SetOutputDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')]) ## ipv6-route.h: void ns3::Ipv6Route::SetSource(ns3::Ipv6Address src) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv6Address', 'src')]) return def register_Ns3Ipv6RoutingProtocol_methods(root_module, cls): ## ipv6-routing-protocol.h: ns3::Ipv6RoutingProtocol::Ipv6RoutingProtocol() [constructor] cls.add_constructor([]) ## ipv6-routing-protocol.h: ns3::Ipv6RoutingProtocol::Ipv6RoutingProtocol(ns3::Ipv6RoutingProtocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6RoutingProtocol const &', 'arg0')]) ## ipv6-routing-protocol.h: static ns3::TypeId ns3::Ipv6RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-routing-protocol.h: void ns3::Ipv6RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv6InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv6InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv6-routing-protocol.h: void ns3::Ipv6RoutingProtocol::NotifyAddRoute(ns3::Ipv6Address dst, ns3::Ipv6Prefix mask, ns3::Ipv6Address nextHop, uint32_t interface, ns3::Ipv6Address prefixToUse=ns3::Ipv6Address::GetZero( )) [member function] cls.add_method('NotifyAddRoute', 'void', [param('ns3::Ipv6Address', 'dst'), param('ns3::Ipv6Prefix', 'mask'), param('ns3::Ipv6Address', 'nextHop'), param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'prefixToUse', default_value='ns3::Ipv6Address::GetZero( )')], is_pure_virtual=True, is_virtual=True) ## ipv6-routing-protocol.h: void ns3::Ipv6RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv6-routing-protocol.h: void ns3::Ipv6RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv6-routing-protocol.h: void ns3::Ipv6RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv6InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv6InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv6-routing-protocol.h: void ns3::Ipv6RoutingProtocol::NotifyRemoveRoute(ns3::Ipv6Address dst, ns3::Ipv6Prefix mask, ns3::Ipv6Address nextHop, uint32_t interface, ns3::Ipv6Address prefixToUse=ns3::Ipv6Address::GetZero( )) [member function] cls.add_method('NotifyRemoveRoute', 'void', [param('ns3::Ipv6Address', 'dst'), param('ns3::Ipv6Prefix', 'mask'), param('ns3::Ipv6Address', 'nextHop'), param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'prefixToUse', default_value='ns3::Ipv6Address::GetZero( )')], is_pure_virtual=True, is_virtual=True) ## ipv6-routing-protocol.h: bool ns3::Ipv6RoutingProtocol::RouteInput(ns3::Ptr<ns3::Packet const> p, ns3::Ipv6Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void,ns3::Ptr<ns3::Ipv6Route>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv6Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv6MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv6Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv6Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv6Header&,ns3::Socket::SocketErrno,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv6Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv6Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv6Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv6MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv6Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv6Header 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::Ipv6Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_pure_virtual=True, is_virtual=True) ## ipv6-routing-protocol.h: ns3::Ptr<ns3::Ipv6Route> ns3::Ipv6RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv6Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_pure_virtual=True, is_virtual=True) ## ipv6-routing-protocol.h: void ns3::Ipv6RoutingProtocol::SetIpv6(ns3::Ptr<ns3::Ipv6> ipv6) [member function] cls.add_method('SetIpv6', 'void', [param('ns3::Ptr< ns3::Ipv6 >', 'ipv6')], is_pure_virtual=True, is_virtual=True) return def register_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h: ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h: ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h: ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h: ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h: ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h: 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: bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h: ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h: std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h: 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: ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h: ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h: 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: 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: 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: 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: 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: 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: 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: 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: 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: static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h: void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h: 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_Ns3Node_methods(root_module, cls): ## node.h: ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h: ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h: ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h: 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: 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: static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h: 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: 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: uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h: uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h: uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h: uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h: static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h: void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h: void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h: void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h: void ns3::Node::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='protected', is_virtual=True) ## node.h: void ns3::Node::NotifyDeviceAdded(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('NotifyDeviceAdded', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')], visibility='private', is_virtual=True) return def register_Ns3PacketSocketFactory_methods(root_module, cls): ## packet-socket-factory.h: ns3::PacketSocketFactory::PacketSocketFactory(ns3::PacketSocketFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketSocketFactory const &', 'arg0')]) ## packet-socket-factory.h: ns3::PacketSocketFactory::PacketSocketFactory() [constructor] cls.add_constructor([]) ## packet-socket-factory.h: ns3::Ptr<ns3::Socket> ns3::PacketSocketFactory::CreateSocket() [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [], is_virtual=True) ## packet-socket-factory.h: static ns3::TypeId ns3::PacketSocketFactory::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3PbbAddressBlock_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h: ns3::PbbAddressBlock::PbbAddressBlock(ns3::PbbAddressBlock const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbAddressBlock const &', 'arg0')]) ## packetbb.h: ns3::PbbAddressBlock::PbbAddressBlock() [constructor] cls.add_constructor([]) ## packetbb.h: ns3::Address ns3::PbbAddressBlock::AddressBack() const [member function] cls.add_method('AddressBack', 'ns3::Address', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressBegin() [member function] cls.add_method('AddressBegin', 'std::_List_iterator< ns3::Address >', []) ## packetbb.h: std::_List_const_iterator<ns3::Address> ns3::PbbAddressBlock::AddressBegin() const [member function] cls.add_method('AddressBegin', 'std::_List_const_iterator< ns3::Address >', [], is_const=True) ## packetbb.h: void ns3::PbbAddressBlock::AddressClear() [member function] cls.add_method('AddressClear', 'void', []) ## packetbb.h: bool ns3::PbbAddressBlock::AddressEmpty() const [member function] cls.add_method('AddressEmpty', 'bool', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressEnd() [member function] cls.add_method('AddressEnd', 'std::_List_iterator< ns3::Address >', []) ## packetbb.h: std::_List_const_iterator<ns3::Address> ns3::PbbAddressBlock::AddressEnd() const [member function] cls.add_method('AddressEnd', 'std::_List_const_iterator< ns3::Address >', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressErase(std::_List_iterator<ns3::Address> position) [member function] cls.add_method('AddressErase', 'std::_List_iterator< ns3::Address >', [param('std::_List_iterator< ns3::Address >', 'position')]) ## packetbb.h: std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressErase(std::_List_iterator<ns3::Address> first, std::_List_iterator<ns3::Address> last) [member function] cls.add_method('AddressErase', 'std::_List_iterator< ns3::Address >', [param('std::_List_iterator< ns3::Address >', 'first'), param('std::_List_iterator< ns3::Address >', 'last')]) ## packetbb.h: ns3::Address ns3::PbbAddressBlock::AddressFront() const [member function] cls.add_method('AddressFront', 'ns3::Address', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressInsert(std::_List_iterator<ns3::Address> position, ns3::Address const value) [member function] cls.add_method('AddressInsert', 'std::_List_iterator< ns3::Address >', [param('std::_List_iterator< ns3::Address >', 'position'), param('ns3::Address const', 'value')]) ## packetbb.h: void ns3::PbbAddressBlock::AddressPopBack() [member function] cls.add_method('AddressPopBack', 'void', []) ## packetbb.h: void ns3::PbbAddressBlock::AddressPopFront() [member function] cls.add_method('AddressPopFront', 'void', []) ## packetbb.h: void ns3::PbbAddressBlock::AddressPushBack(ns3::Address address) [member function] cls.add_method('AddressPushBack', 'void', [param('ns3::Address', 'address')]) ## packetbb.h: void ns3::PbbAddressBlock::AddressPushFront(ns3::Address address) [member function] cls.add_method('AddressPushFront', 'void', [param('ns3::Address', 'address')]) ## packetbb.h: int ns3::PbbAddressBlock::AddressSize() const [member function] cls.add_method('AddressSize', 'int', [], is_const=True) ## packetbb.h: void ns3::PbbAddressBlock::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h: uint32_t ns3::PbbAddressBlock::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h: uint8_t ns3::PbbAddressBlock::PrefixBack() const [member function] cls.add_method('PrefixBack', 'uint8_t', [], is_const=True) ## packetbb.h: std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixBegin() [member function] cls.add_method('PrefixBegin', 'std::_List_iterator< unsigned char >', []) ## packetbb.h: std::_List_const_iterator<unsigned char> ns3::PbbAddressBlock::PrefixBegin() const [member function] cls.add_method('PrefixBegin', 'std::_List_const_iterator< unsigned char >', [], is_const=True) ## packetbb.h: void ns3::PbbAddressBlock::PrefixClear() [member function] cls.add_method('PrefixClear', 'void', []) ## packetbb.h: bool ns3::PbbAddressBlock::PrefixEmpty() const [member function] cls.add_method('PrefixEmpty', 'bool', [], is_const=True) ## packetbb.h: std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixEnd() [member function] cls.add_method('PrefixEnd', 'std::_List_iterator< unsigned char >', []) ## packetbb.h: std::_List_const_iterator<unsigned char> ns3::PbbAddressBlock::PrefixEnd() const [member function] cls.add_method('PrefixEnd', 'std::_List_const_iterator< unsigned char >', [], is_const=True) ## packetbb.h: std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixErase(std::_List_iterator<unsigned char> position) [member function] cls.add_method('PrefixErase', 'std::_List_iterator< unsigned char >', [param('std::_List_iterator< unsigned char >', 'position')]) ## packetbb.h: std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixErase(std::_List_iterator<unsigned char> first, std::_List_iterator<unsigned char> last) [member function] cls.add_method('PrefixErase', 'std::_List_iterator< unsigned char >', [param('std::_List_iterator< unsigned char >', 'first'), param('std::_List_iterator< unsigned char >', 'last')]) ## packetbb.h: uint8_t ns3::PbbAddressBlock::PrefixFront() const [member function] cls.add_method('PrefixFront', 'uint8_t', [], is_const=True) ## packetbb.h: std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixInsert(std::_List_iterator<unsigned char> position, uint8_t const value) [member function] cls.add_method('PrefixInsert', 'std::_List_iterator< unsigned char >', [param('std::_List_iterator< unsigned char >', 'position'), param('uint8_t const', 'value')]) ## packetbb.h: void ns3::PbbAddressBlock::PrefixPopBack() [member function] cls.add_method('PrefixPopBack', 'void', []) ## packetbb.h: void ns3::PbbAddressBlock::PrefixPopFront() [member function] cls.add_method('PrefixPopFront', 'void', []) ## packetbb.h: void ns3::PbbAddressBlock::PrefixPushBack(uint8_t prefix) [member function] cls.add_method('PrefixPushBack', 'void', [param('uint8_t', 'prefix')]) ## packetbb.h: void ns3::PbbAddressBlock::PrefixPushFront(uint8_t prefix) [member function] cls.add_method('PrefixPushFront', 'void', [param('uint8_t', 'prefix')]) ## packetbb.h: int ns3::PbbAddressBlock::PrefixSize() const [member function] cls.add_method('PrefixSize', 'int', [], is_const=True) ## packetbb.h: void ns3::PbbAddressBlock::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h: void ns3::PbbAddressBlock::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h: void ns3::PbbAddressBlock::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h: ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressBlock::TlvBack() [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbAddressTlv >', []) ## packetbb.h: ns3::Ptr<ns3::PbbAddressTlv> const ns3::PbbAddressBlock::TlvBack() const [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbAddressTlv > const', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvBegin() [member function] cls.add_method('TlvBegin', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvBegin() const [member function] cls.add_method('TlvBegin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [], is_const=True) ## packetbb.h: void ns3::PbbAddressBlock::TlvClear() [member function] cls.add_method('TlvClear', 'void', []) ## packetbb.h: bool ns3::PbbAddressBlock::TlvEmpty() const [member function] cls.add_method('TlvEmpty', 'bool', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvEnd() [member function] cls.add_method('TlvEnd', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvEnd() const [member function] cls.add_method('TlvEnd', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position) [member function] cls.add_method('TlvErase', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position')]) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > last) [member function] cls.add_method('TlvErase', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'last')]) ## packetbb.h: ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressBlock::TlvFront() [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbAddressTlv >', []) ## packetbb.h: ns3::Ptr<ns3::PbbAddressTlv> const ns3::PbbAddressBlock::TlvFront() const [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbAddressTlv > const', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvInsert(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position, ns3::Ptr<ns3::PbbTlv> const value) [member function] cls.add_method('TlvInsert', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position'), param('ns3::Ptr< ns3::PbbTlv > const', 'value')]) ## packetbb.h: void ns3::PbbAddressBlock::TlvPopBack() [member function] cls.add_method('TlvPopBack', 'void', []) ## packetbb.h: void ns3::PbbAddressBlock::TlvPopFront() [member function] cls.add_method('TlvPopFront', 'void', []) ## packetbb.h: void ns3::PbbAddressBlock::TlvPushBack(ns3::Ptr<ns3::PbbAddressTlv> address) [member function] cls.add_method('TlvPushBack', 'void', [param('ns3::Ptr< ns3::PbbAddressTlv >', 'address')]) ## packetbb.h: void ns3::PbbAddressBlock::TlvPushFront(ns3::Ptr<ns3::PbbAddressTlv> address) [member function] cls.add_method('TlvPushFront', 'void', [param('ns3::Ptr< ns3::PbbAddressTlv >', 'address')]) ## packetbb.h: int ns3::PbbAddressBlock::TlvSize() const [member function] cls.add_method('TlvSize', 'int', [], is_const=True) ## packetbb.h: ns3::Address ns3::PbbAddressBlock::DeserializeAddress(uint8_t * buffer) const [member function] cls.add_method('DeserializeAddress', 'ns3::Address', [param('uint8_t *', 'buffer')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: uint8_t ns3::PbbAddressBlock::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'uint8_t', [], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: void ns3::PbbAddressBlock::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function] cls.add_method('PrintAddress', 'void', [param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: void ns3::PbbAddressBlock::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function] cls.add_method('SerializeAddress', 'void', [param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbAddressBlockIpv4_methods(root_module, cls): ## packetbb.h: ns3::PbbAddressBlockIpv4::PbbAddressBlockIpv4(ns3::PbbAddressBlockIpv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbAddressBlockIpv4 const &', 'arg0')]) ## packetbb.h: ns3::PbbAddressBlockIpv4::PbbAddressBlockIpv4() [constructor] cls.add_constructor([]) ## packetbb.h: ns3::Address ns3::PbbAddressBlockIpv4::DeserializeAddress(uint8_t * buffer) const [member function] cls.add_method('DeserializeAddress', 'ns3::Address', [param('uint8_t *', 'buffer')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: uint8_t ns3::PbbAddressBlockIpv4::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'uint8_t', [], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: void ns3::PbbAddressBlockIpv4::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function] cls.add_method('PrintAddress', 'void', [param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: void ns3::PbbAddressBlockIpv4::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function] cls.add_method('SerializeAddress', 'void', [param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')], is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbAddressBlockIpv6_methods(root_module, cls): ## packetbb.h: ns3::PbbAddressBlockIpv6::PbbAddressBlockIpv6(ns3::PbbAddressBlockIpv6 const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbAddressBlockIpv6 const &', 'arg0')]) ## packetbb.h: ns3::PbbAddressBlockIpv6::PbbAddressBlockIpv6() [constructor] cls.add_constructor([]) ## packetbb.h: ns3::Address ns3::PbbAddressBlockIpv6::DeserializeAddress(uint8_t * buffer) const [member function] cls.add_method('DeserializeAddress', 'ns3::Address', [param('uint8_t *', 'buffer')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: uint8_t ns3::PbbAddressBlockIpv6::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'uint8_t', [], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: void ns3::PbbAddressBlockIpv6::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function] cls.add_method('PrintAddress', 'void', [param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: void ns3::PbbAddressBlockIpv6::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function] cls.add_method('SerializeAddress', 'void', [param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')], is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbMessage_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h: ns3::PbbMessage::PbbMessage(ns3::PbbMessage const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbMessage const &', 'arg0')]) ## packetbb.h: ns3::PbbMessage::PbbMessage() [constructor] cls.add_constructor([]) ## packetbb.h: ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockBack() [member function] cls.add_method('AddressBlockBack', 'ns3::Ptr< ns3::PbbAddressBlock >', []) ## packetbb.h: ns3::Ptr<ns3::PbbAddressBlock> const ns3::PbbMessage::AddressBlockBack() const [member function] cls.add_method('AddressBlockBack', 'ns3::Ptr< ns3::PbbAddressBlock > const', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockBegin() [member function] cls.add_method('AddressBlockBegin', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockBegin() const [member function] cls.add_method('AddressBlockBegin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', [], is_const=True) ## packetbb.h: void ns3::PbbMessage::AddressBlockClear() [member function] cls.add_method('AddressBlockClear', 'void', []) ## packetbb.h: bool ns3::PbbMessage::AddressBlockEmpty() const [member function] cls.add_method('AddressBlockEmpty', 'bool', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockEnd() [member function] cls.add_method('AddressBlockEnd', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockEnd() const [member function] cls.add_method('AddressBlockEnd', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > position) [member function] cls.add_method('AddressBlockErase', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'position')]) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > last) [member function] cls.add_method('AddressBlockErase', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'last')]) ## packetbb.h: ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockFront() [member function] cls.add_method('AddressBlockFront', 'ns3::Ptr< ns3::PbbAddressBlock >', []) ## packetbb.h: ns3::Ptr<ns3::PbbAddressBlock> const ns3::PbbMessage::AddressBlockFront() const [member function] cls.add_method('AddressBlockFront', 'ns3::Ptr< ns3::PbbAddressBlock > const', [], is_const=True) ## packetbb.h: void ns3::PbbMessage::AddressBlockPopBack() [member function] cls.add_method('AddressBlockPopBack', 'void', []) ## packetbb.h: void ns3::PbbMessage::AddressBlockPopFront() [member function] cls.add_method('AddressBlockPopFront', 'void', []) ## packetbb.h: void ns3::PbbMessage::AddressBlockPushBack(ns3::Ptr<ns3::PbbAddressBlock> block) [member function] cls.add_method('AddressBlockPushBack', 'void', [param('ns3::Ptr< ns3::PbbAddressBlock >', 'block')]) ## packetbb.h: void ns3::PbbMessage::AddressBlockPushFront(ns3::Ptr<ns3::PbbAddressBlock> block) [member function] cls.add_method('AddressBlockPushFront', 'void', [param('ns3::Ptr< ns3::PbbAddressBlock >', 'block')]) ## packetbb.h: int ns3::PbbMessage::AddressBlockSize() const [member function] cls.add_method('AddressBlockSize', 'int', [], is_const=True) ## packetbb.h: void ns3::PbbMessage::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h: static ns3::Ptr<ns3::PbbMessage> ns3::PbbMessage::DeserializeMessage(ns3::Buffer::Iterator & start) [member function] cls.add_method('DeserializeMessage', 'ns3::Ptr< ns3::PbbMessage >', [param('ns3::Buffer::Iterator &', 'start')], is_static=True) ## packetbb.h: uint8_t ns3::PbbMessage::GetHopCount() const [member function] cls.add_method('GetHopCount', 'uint8_t', [], is_const=True) ## packetbb.h: uint8_t ns3::PbbMessage::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## packetbb.h: ns3::Address ns3::PbbMessage::GetOriginatorAddress() const [member function] cls.add_method('GetOriginatorAddress', 'ns3::Address', [], is_const=True) ## packetbb.h: uint16_t ns3::PbbMessage::GetSequenceNumber() const [member function] cls.add_method('GetSequenceNumber', 'uint16_t', [], is_const=True) ## packetbb.h: uint32_t ns3::PbbMessage::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h: uint8_t ns3::PbbMessage::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## packetbb.h: bool ns3::PbbMessage::HasHopCount() const [member function] cls.add_method('HasHopCount', 'bool', [], is_const=True) ## packetbb.h: bool ns3::PbbMessage::HasHopLimit() const [member function] cls.add_method('HasHopLimit', 'bool', [], is_const=True) ## packetbb.h: bool ns3::PbbMessage::HasOriginatorAddress() const [member function] cls.add_method('HasOriginatorAddress', 'bool', [], is_const=True) ## packetbb.h: bool ns3::PbbMessage::HasSequenceNumber() const [member function] cls.add_method('HasSequenceNumber', 'bool', [], is_const=True) ## packetbb.h: void ns3::PbbMessage::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h: void ns3::PbbMessage::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h: void ns3::PbbMessage::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h: void ns3::PbbMessage::SetHopCount(uint8_t hopcount) [member function] cls.add_method('SetHopCount', 'void', [param('uint8_t', 'hopcount')]) ## packetbb.h: void ns3::PbbMessage::SetHopLimit(uint8_t hoplimit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'hoplimit')]) ## packetbb.h: void ns3::PbbMessage::SetOriginatorAddress(ns3::Address address) [member function] cls.add_method('SetOriginatorAddress', 'void', [param('ns3::Address', 'address')]) ## packetbb.h: void ns3::PbbMessage::SetSequenceNumber(uint16_t seqnum) [member function] cls.add_method('SetSequenceNumber', 'void', [param('uint16_t', 'seqnum')]) ## packetbb.h: void ns3::PbbMessage::SetType(uint8_t type) [member function] cls.add_method('SetType', 'void', [param('uint8_t', 'type')]) ## packetbb.h: ns3::Ptr<ns3::PbbTlv> ns3::PbbMessage::TlvBack() [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbTlv >', []) ## packetbb.h: ns3::Ptr<ns3::PbbTlv> const ns3::PbbMessage::TlvBack() const [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbTlv > const', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvBegin() [member function] cls.add_method('TlvBegin', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvBegin() const [member function] cls.add_method('TlvBegin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >', [], is_const=True) ## packetbb.h: void ns3::PbbMessage::TlvClear() [member function] cls.add_method('TlvClear', 'void', []) ## packetbb.h: bool ns3::PbbMessage::TlvEmpty() const [member function] cls.add_method('TlvEmpty', 'bool', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvEnd() [member function] cls.add_method('TlvEnd', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvEnd() const [member function] cls.add_method('TlvEnd', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function] cls.add_method('TlvErase', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')]) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function] cls.add_method('TlvErase', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')]) ## packetbb.h: ns3::Ptr<ns3::PbbTlv> ns3::PbbMessage::TlvFront() [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbTlv >', []) ## packetbb.h: ns3::Ptr<ns3::PbbTlv> const ns3::PbbMessage::TlvFront() const [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbTlv > const', [], is_const=True) ## packetbb.h: void ns3::PbbMessage::TlvPopBack() [member function] cls.add_method('TlvPopBack', 'void', []) ## packetbb.h: void ns3::PbbMessage::TlvPopFront() [member function] cls.add_method('TlvPopFront', 'void', []) ## packetbb.h: void ns3::PbbMessage::TlvPushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('TlvPushBack', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h: void ns3::PbbMessage::TlvPushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('TlvPushFront', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h: int ns3::PbbMessage::TlvSize() const [member function] cls.add_method('TlvSize', 'int', [], is_const=True) ## packetbb.h: ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('AddressBlockDeserialize', 'ns3::Ptr< ns3::PbbAddressBlock >', [param('ns3::Buffer::Iterator &', 'start')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: ns3::Address ns3::PbbMessage::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('DeserializeOriginatorAddress', 'ns3::Address', [param('ns3::Buffer::Iterator &', 'start')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: ns3::PbbAddressLength ns3::PbbMessage::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'ns3::PbbAddressLength', [], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: void ns3::PbbMessage::PrintOriginatorAddress(std::ostream & os) const [member function] cls.add_method('PrintOriginatorAddress', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: void ns3::PbbMessage::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('SerializeOriginatorAddress', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbMessageIpv4_methods(root_module, cls): ## packetbb.h: ns3::PbbMessageIpv4::PbbMessageIpv4(ns3::PbbMessageIpv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbMessageIpv4 const &', 'arg0')]) ## packetbb.h: ns3::PbbMessageIpv4::PbbMessageIpv4() [constructor] cls.add_constructor([]) ## packetbb.h: ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessageIpv4::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('AddressBlockDeserialize', 'ns3::Ptr< ns3::PbbAddressBlock >', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: ns3::Address ns3::PbbMessageIpv4::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('DeserializeOriginatorAddress', 'ns3::Address', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: ns3::PbbAddressLength ns3::PbbMessageIpv4::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'ns3::PbbAddressLength', [], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: void ns3::PbbMessageIpv4::PrintOriginatorAddress(std::ostream & os) const [member function] cls.add_method('PrintOriginatorAddress', 'void', [param('std::ostream &', 'os')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: void ns3::PbbMessageIpv4::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('SerializeOriginatorAddress', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbMessageIpv6_methods(root_module, cls): ## packetbb.h: ns3::PbbMessageIpv6::PbbMessageIpv6(ns3::PbbMessageIpv6 const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbMessageIpv6 const &', 'arg0')]) ## packetbb.h: ns3::PbbMessageIpv6::PbbMessageIpv6() [constructor] cls.add_constructor([]) ## packetbb.h: ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessageIpv6::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('AddressBlockDeserialize', 'ns3::Ptr< ns3::PbbAddressBlock >', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: ns3::Address ns3::PbbMessageIpv6::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('DeserializeOriginatorAddress', 'ns3::Address', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: ns3::PbbAddressLength ns3::PbbMessageIpv6::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'ns3::PbbAddressLength', [], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: void ns3::PbbMessageIpv6::PrintOriginatorAddress(std::ostream & os) const [member function] cls.add_method('PrintOriginatorAddress', 'void', [param('std::ostream &', 'os')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h: void ns3::PbbMessageIpv6::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('SerializeOriginatorAddress', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbPacket_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h: ns3::PbbPacket::PbbPacket(ns3::PbbPacket const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbPacket const &', 'arg0')]) ## packetbb.h: ns3::PbbPacket::PbbPacket() [constructor] cls.add_constructor([]) ## packetbb.h: uint32_t ns3::PbbPacket::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')]) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')]) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > position) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'position')]) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > first, std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > last) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'last')]) ## packetbb.h: ns3::TypeId ns3::PbbPacket::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## packetbb.h: uint16_t ns3::PbbPacket::GetSequenceNumber() const [member function] cls.add_method('GetSequenceNumber', 'uint16_t', [], is_const=True) ## packetbb.h: uint32_t ns3::PbbPacket::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## packetbb.h: static ns3::TypeId ns3::PbbPacket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packetbb.h: uint8_t ns3::PbbPacket::GetVersion() const [member function] cls.add_method('GetVersion', 'uint8_t', [], is_const=True) ## packetbb.h: bool ns3::PbbPacket::HasSequenceNumber() const [member function] cls.add_method('HasSequenceNumber', 'bool', [], is_const=True) ## packetbb.h: ns3::Ptr<ns3::PbbMessage> ns3::PbbPacket::MessageBack() [member function] cls.add_method('MessageBack', 'ns3::Ptr< ns3::PbbMessage >', []) ## packetbb.h: ns3::Ptr<ns3::PbbMessage> const ns3::PbbPacket::MessageBack() const [member function] cls.add_method('MessageBack', 'ns3::Ptr< ns3::PbbMessage > const', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageBegin() [member function] cls.add_method('MessageBegin', 'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageBegin() const [member function] cls.add_method('MessageBegin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbMessage > >', [], is_const=True) ## packetbb.h: void ns3::PbbPacket::MessageClear() [member function] cls.add_method('MessageClear', 'void', []) ## packetbb.h: bool ns3::PbbPacket::MessageEmpty() const [member function] cls.add_method('MessageEmpty', 'bool', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageEnd() [member function] cls.add_method('MessageEnd', 'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageEnd() const [member function] cls.add_method('MessageEnd', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbMessage > >', [], is_const=True) ## packetbb.h: ns3::Ptr<ns3::PbbMessage> ns3::PbbPacket::MessageFront() [member function] cls.add_method('MessageFront', 'ns3::Ptr< ns3::PbbMessage >', []) ## packetbb.h: ns3::Ptr<ns3::PbbMessage> const ns3::PbbPacket::MessageFront() const [member function] cls.add_method('MessageFront', 'ns3::Ptr< ns3::PbbMessage > const', [], is_const=True) ## packetbb.h: void ns3::PbbPacket::MessagePopBack() [member function] cls.add_method('MessagePopBack', 'void', []) ## packetbb.h: void ns3::PbbPacket::MessagePopFront() [member function] cls.add_method('MessagePopFront', 'void', []) ## packetbb.h: void ns3::PbbPacket::MessagePushBack(ns3::Ptr<ns3::PbbMessage> message) [member function] cls.add_method('MessagePushBack', 'void', [param('ns3::Ptr< ns3::PbbMessage >', 'message')]) ## packetbb.h: void ns3::PbbPacket::MessagePushFront(ns3::Ptr<ns3::PbbMessage> message) [member function] cls.add_method('MessagePushFront', 'void', [param('ns3::Ptr< ns3::PbbMessage >', 'message')]) ## packetbb.h: int ns3::PbbPacket::MessageSize() const [member function] cls.add_method('MessageSize', 'int', [], is_const=True) ## packetbb.h: void ns3::PbbPacket::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## packetbb.h: void ns3::PbbPacket::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## packetbb.h: void ns3::PbbPacket::SetSequenceNumber(uint16_t number) [member function] cls.add_method('SetSequenceNumber', 'void', [param('uint16_t', 'number')]) ## packetbb.h: ns3::Ptr<ns3::PbbTlv> ns3::PbbPacket::TlvBack() [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbTlv >', []) ## packetbb.h: ns3::Ptr<ns3::PbbTlv> const ns3::PbbPacket::TlvBack() const [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbTlv > const', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvBegin() [member function] cls.add_method('TlvBegin', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvBegin() const [member function] cls.add_method('TlvBegin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >', [], is_const=True) ## packetbb.h: void ns3::PbbPacket::TlvClear() [member function] cls.add_method('TlvClear', 'void', []) ## packetbb.h: bool ns3::PbbPacket::TlvEmpty() const [member function] cls.add_method('TlvEmpty', 'bool', [], is_const=True) ## packetbb.h: std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvEnd() [member function] cls.add_method('TlvEnd', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', []) ## packetbb.h: std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvEnd() const [member function] cls.add_method('TlvEnd', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >', [], is_const=True) ## packetbb.h: ns3::Ptr<ns3::PbbTlv> ns3::PbbPacket::TlvFront() [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbTlv >', []) ## packetbb.h: ns3::Ptr<ns3::PbbTlv> const ns3::PbbPacket::TlvFront() const [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbTlv > const', [], is_const=True) ## packetbb.h: void ns3::PbbPacket::TlvPopBack() [member function] cls.add_method('TlvPopBack', 'void', []) ## packetbb.h: void ns3::PbbPacket::TlvPopFront() [member function] cls.add_method('TlvPopFront', 'void', []) ## packetbb.h: void ns3::PbbPacket::TlvPushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('TlvPushBack', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h: void ns3::PbbPacket::TlvPushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('TlvPushFront', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h: int ns3::PbbPacket::TlvSize() const [member function] cls.add_method('TlvSize', 'int', [], is_const=True) return def register_Ns3PbbTlv_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h: ns3::PbbTlv::PbbTlv(ns3::PbbTlv const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbTlv const &', 'arg0')]) ## packetbb.h: ns3::PbbTlv::PbbTlv() [constructor] cls.add_constructor([]) ## packetbb.h: void ns3::PbbTlv::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h: uint32_t ns3::PbbTlv::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h: uint8_t ns3::PbbTlv::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## packetbb.h: uint8_t ns3::PbbTlv::GetTypeExt() const [member function] cls.add_method('GetTypeExt', 'uint8_t', [], is_const=True) ## packetbb.h: ns3::Buffer ns3::PbbTlv::GetValue() const [member function] cls.add_method('GetValue', 'ns3::Buffer', [], is_const=True) ## packetbb.h: bool ns3::PbbTlv::HasTypeExt() const [member function] cls.add_method('HasTypeExt', 'bool', [], is_const=True) ## packetbb.h: bool ns3::PbbTlv::HasValue() const [member function] cls.add_method('HasValue', 'bool', [], is_const=True) ## packetbb.h: void ns3::PbbTlv::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h: void ns3::PbbTlv::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h: void ns3::PbbTlv::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h: void ns3::PbbTlv::SetType(uint8_t type) [member function] cls.add_method('SetType', 'void', [param('uint8_t', 'type')]) ## packetbb.h: void ns3::PbbTlv::SetTypeExt(uint8_t type) [member function] cls.add_method('SetTypeExt', 'void', [param('uint8_t', 'type')]) ## packetbb.h: void ns3::PbbTlv::SetValue(ns3::Buffer start) [member function] cls.add_method('SetValue', 'void', [param('ns3::Buffer', 'start')]) ## packetbb.h: void ns3::PbbTlv::SetValue(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('SetValue', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packetbb.h: uint8_t ns3::PbbTlv::GetIndexStart() const [member function] cls.add_method('GetIndexStart', 'uint8_t', [], is_const=True, visibility='protected') ## packetbb.h: uint8_t ns3::PbbTlv::GetIndexStop() const [member function] cls.add_method('GetIndexStop', 'uint8_t', [], is_const=True, visibility='protected') ## packetbb.h: bool ns3::PbbTlv::HasIndexStart() const [member function] cls.add_method('HasIndexStart', 'bool', [], is_const=True, visibility='protected') ## packetbb.h: bool ns3::PbbTlv::HasIndexStop() const [member function] cls.add_method('HasIndexStop', 'bool', [], is_const=True, visibility='protected') ## packetbb.h: bool ns3::PbbTlv::IsMultivalue() const [member function] cls.add_method('IsMultivalue', 'bool', [], is_const=True, visibility='protected') ## packetbb.h: void ns3::PbbTlv::SetIndexStart(uint8_t index) [member function] cls.add_method('SetIndexStart', 'void', [param('uint8_t', 'index')], visibility='protected') ## packetbb.h: void ns3::PbbTlv::SetIndexStop(uint8_t index) [member function] cls.add_method('SetIndexStop', 'void', [param('uint8_t', 'index')], visibility='protected') ## packetbb.h: void ns3::PbbTlv::SetMultivalue(bool isMultivalue) [member function] cls.add_method('SetMultivalue', 'void', [param('bool', 'isMultivalue')], visibility='protected') return def register_Ns3SimpleChannel_methods(root_module, cls): ## simple-channel.h: ns3::SimpleChannel::SimpleChannel(ns3::SimpleChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SimpleChannel const &', 'arg0')]) ## simple-channel.h: ns3::SimpleChannel::SimpleChannel() [constructor] cls.add_constructor([]) ## simple-channel.h: void ns3::SimpleChannel::Add(ns3::Ptr<ns3::SimpleNetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::SimpleNetDevice >', 'device')]) ## simple-channel.h: ns3::Ptr<ns3::NetDevice> ns3::SimpleChannel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## simple-channel.h: uint32_t ns3::SimpleChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True, is_virtual=True) ## simple-channel.h: static ns3::TypeId ns3::SimpleChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## simple-channel.h: void ns3::SimpleChannel::Send(ns3::Ptr<ns3::Packet> p, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from, ns3::Ptr<ns3::SimpleNetDevice> sender) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'sender')]) return def register_Ns3SimpleNetDevice_methods(root_module, cls): ## simple-net-device.h: ns3::SimpleNetDevice::SimpleNetDevice(ns3::SimpleNetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::SimpleNetDevice const &', 'arg0')]) ## simple-net-device.h: ns3::SimpleNetDevice::SimpleNetDevice() [constructor] cls.add_constructor([]) ## simple-net-device.h: void ns3::SimpleNetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_virtual=True) ## simple-net-device.h: ns3::Address ns3::SimpleNetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## simple-net-device.h: ns3::Address ns3::SimpleNetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## simple-net-device.h: ns3::Ptr<ns3::Channel> ns3::SimpleNetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## simple-net-device.h: uint32_t ns3::SimpleNetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## simple-net-device.h: uint16_t ns3::SimpleNetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## simple-net-device.h: ns3::Address ns3::SimpleNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_const=True, is_virtual=True) ## simple-net-device.h: ns3::Address ns3::SimpleNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## simple-net-device.h: ns3::Ptr<ns3::Node> ns3::SimpleNetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## simple-net-device.h: static ns3::TypeId ns3::SimpleNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## simple-net-device.h: bool ns3::SimpleNetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h: bool ns3::SimpleNetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h: bool ns3::SimpleNetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h: bool ns3::SimpleNetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h: bool ns3::SimpleNetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h: bool ns3::SimpleNetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h: void ns3::SimpleNetDevice::Receive(ns3::Ptr<ns3::Packet> packet, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')]) ## simple-net-device.h: bool ns3::SimpleNetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## simple-net-device.h: bool ns3::SimpleNetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## simple-net-device.h: void ns3::SimpleNetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## simple-net-device.h: void ns3::SimpleNetDevice::SetChannel(ns3::Ptr<ns3::SimpleChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SimpleChannel >', 'channel')]) ## simple-net-device.h: void ns3::SimpleNetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## simple-net-device.h: bool ns3::SimpleNetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## simple-net-device.h: void ns3::SimpleNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## simple-net-device.h: void ns3::SimpleNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## simple-net-device.h: void ns3::SimpleNetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## simple-net-device.h: void ns3::SimpleNetDevice::SetReceiveErrorModel(ns3::Ptr<ns3::ErrorModel> em) [member function] cls.add_method('SetReceiveErrorModel', 'void', [param('ns3::Ptr< ns3::ErrorModel >', 'em')]) ## simple-net-device.h: bool ns3::SimpleNetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h: void ns3::SimpleNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h: ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h: ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h: ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h: ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h: ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h: 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: bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h: ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h: std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h: void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_Ns3PbbAddressTlv_methods(root_module, cls): ## packetbb.h: ns3::PbbAddressTlv::PbbAddressTlv() [constructor] cls.add_constructor([]) ## packetbb.h: ns3::PbbAddressTlv::PbbAddressTlv(ns3::PbbAddressTlv const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbAddressTlv const &', 'arg0')]) ## packetbb.h: uint8_t ns3::PbbAddressTlv::GetIndexStart() const [member function] cls.add_method('GetIndexStart', 'uint8_t', [], is_const=True) ## packetbb.h: uint8_t ns3::PbbAddressTlv::GetIndexStop() const [member function] cls.add_method('GetIndexStop', 'uint8_t', [], is_const=True) ## packetbb.h: bool ns3::PbbAddressTlv::HasIndexStart() const [member function] cls.add_method('HasIndexStart', 'bool', [], is_const=True) ## packetbb.h: bool ns3::PbbAddressTlv::HasIndexStop() const [member function] cls.add_method('HasIndexStop', 'bool', [], is_const=True) ## packetbb.h: bool ns3::PbbAddressTlv::IsMultivalue() const [member function] cls.add_method('IsMultivalue', 'bool', [], is_const=True) ## packetbb.h: void ns3::PbbAddressTlv::SetIndexStart(uint8_t index) [member function] cls.add_method('SetIndexStart', 'void', [param('uint8_t', 'index')]) ## packetbb.h: void ns3::PbbAddressTlv::SetIndexStop(uint8_t index) [member function] cls.add_method('SetIndexStop', 'void', [param('uint8_t', 'index')]) ## packetbb.h: void ns3::PbbAddressTlv::SetMultivalue(bool isMultivalue) [member function] cls.add_method('SetMultivalue', 'void', [param('bool', 'isMultivalue')]) return def register_functions(root_module): module = root_module ## address.h: extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeAddressChecker() [free function] module.add_function('MakeAddressChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## ipv4-address.h: extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeIpv4AddressChecker() [free function] module.add_function('MakeIpv4AddressChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## ipv4-address.h: extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeIpv4MaskChecker() [free function] module.add_function('MakeIpv4MaskChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## ipv6-address.h: extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeIpv6AddressChecker() [free function] module.add_function('MakeIpv6AddressChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## ipv6-address.h: extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeIpv6PrefixChecker() [free function] module.add_function('MakeIpv6PrefixChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## mac48-address.h: extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeMac48AddressChecker() [free function] module.add_function('MakeMac48AddressChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## address-utils.h: extern void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Address & ad, uint32_t len) [free function] module.add_function('ReadFrom', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Address &', 'ad'), param('uint32_t', 'len')]) ## address-utils.h: extern void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Ipv4Address & ad) [free function] module.add_function('ReadFrom', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Ipv4Address &', 'ad')]) ## address-utils.h: extern void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Ipv6Address & ad) [free function] module.add_function('ReadFrom', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Ipv6Address &', 'ad')]) ## address-utils.h: extern void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Mac48Address & ad) [free function] module.add_function('ReadFrom', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac48Address &', 'ad')]) ## address-utils.h: extern void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Address const & ad) [free function] module.add_function('WriteTo', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Address const &', 'ad')]) ## address-utils.h: extern void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Ipv4Address ad) [free function] module.add_function('WriteTo', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Ipv4Address', 'ad')]) ## address-utils.h: extern void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Ipv6Address ad) [free function] module.add_function('WriteTo', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Ipv6Address', 'ad')]) ## address-utils.h: extern void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Mac48Address ad) [free function] module.add_function('WriteTo', 'void', [param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac48Address', 'ad')]) register_functions_ns3_Config(module.get_submodule('Config'), root_module) register_functions_ns3_TimeStepPrecision(module.get_submodule('TimeStepPrecision'), root_module) register_functions_ns3_addressUtils(module.get_submodule('addressUtils'), root_module) register_functions_ns3_aodv(module.get_submodule('aodv'), root_module) register_functions_ns3_dot11s(module.get_submodule('dot11s'), root_module) register_functions_ns3_flame(module.get_submodule('flame'), root_module) register_functions_ns3_internal(module.get_submodule('internal'), root_module) register_functions_ns3_olsr(module.get_submodule('olsr'), root_module) return def register_functions_ns3_Config(module, root_module): return def register_functions_ns3_TimeStepPrecision(module, root_module): return def register_functions_ns3_addressUtils(module, root_module): ## address-utils.h: extern bool ns3::addressUtils::IsMulticast(ns3::Address const & ad) [free function] module.add_function('IsMulticast', 'bool', [param('ns3::Address const &', 'ad')]) return def register_functions_ns3_aodv(module, root_module): return def register_functions_ns3_dot11s(module, root_module): return def register_functions_ns3_flame(module, root_module): return def register_functions_ns3_internal(module, root_module): return def register_functions_ns3_olsr(module, root_module): return
gmarkall/numba
refs/heads/master
numba/tests/test_globals.py
4
import numpy as np from numba import jit, njit from numba.tests import usecases import unittest X = np.arange(10) def global_ndarray_func(x): y = x + X.shape[0] return y # Create complex array with real and imaginary parts of distinct value cplx_X = np.arange(10, dtype=np.complex128) tmp = np.arange(10, dtype=np.complex128) cplx_X += (tmp+10)*1j def global_cplx_arr_copy(a): for i in range(len(a)): a[i] = cplx_X[i] # Create a recarray with fields of distinct value x_dt = np.dtype([('a', np.int32), ('b', np.float32)]) rec_X = np.recarray(10, dtype=x_dt) for i in range(len(rec_X)): rec_X[i].a = i rec_X[i].b = i + 0.5 def global_rec_arr_copy(a): for i in range(len(a)): a[i] = rec_X[i] def global_rec_arr_extract_fields(a, b): for i in range(len(a)): a[i] = rec_X[i].a b[i] = rec_X[i].b # Create additional global recarray y_dt = np.dtype([('c', np.int16), ('d', np.float64)]) rec_Y = np.recarray(10, dtype=y_dt) for i in range(len(rec_Y)): rec_Y[i].c = i + 10 rec_Y[i].d = i + 10.5 def global_two_rec_arrs(a, b, c, d): for i in range(len(a)): a[i] = rec_X[i].a b[i] = rec_X[i].b c[i] = rec_Y[i].c d[i] = rec_Y[i].d # Test a global record record_only_X = np.recarray(1, dtype=x_dt)[0] record_only_X.a = 1 record_only_X.b = 1.5 @jit(nopython=True) def global_record_func(x): return x.a == record_only_X.a @jit(nopython=True) def global_module_func(x, y): return usecases.andornopython(x, y) # Test a global tuple tup_int = (1, 2) tup_str = ('a', 'b') tup_mixed = (1, 'a') tup_float = (1.2, 3.5) tup_npy_ints = (np.uint64(12), np.int8(3)) def global_int_tuple(): return tup_int[0] + tup_int[1] def global_str_tuple(): return tup_str[0] + tup_str[1] def global_mixed_tuple(): idx = tup_mixed[0] field = tup_mixed[1] return rec_X[idx][field] def global_float_tuple(): return tup_float[0] + tup_float[1] def global_npy_int_tuple(): return tup_npy_ints[0] + tup_npy_ints[1] class TestGlobals(unittest.TestCase): def check_global_ndarray(self, **jitargs): # (see github issue #448) ctestfunc = jit(**jitargs)(global_ndarray_func) self.assertEqual(ctestfunc(1), 11) def test_global_ndarray(self): # This also checks we can access an unhashable global value # (see issue #697) self.check_global_ndarray(forceobj=True) def test_global_ndarray_npm(self): self.check_global_ndarray(nopython=True) def check_global_complex_arr(self, **jitargs): # (see github issue #897) ctestfunc = jit(**jitargs)(global_cplx_arr_copy) arr = np.zeros(len(cplx_X), dtype=np.complex128) ctestfunc(arr) np.testing.assert_equal(arr, cplx_X) def test_global_complex_arr(self): self.check_global_complex_arr(forceobj=True) def test_global_complex_arr_npm(self): self.check_global_complex_arr(nopython=True) def check_global_rec_arr(self, **jitargs): # (see github issue #897) ctestfunc = jit(**jitargs)(global_rec_arr_copy) arr = np.zeros(rec_X.shape, dtype=x_dt) ctestfunc(arr) np.testing.assert_equal(arr, rec_X) def test_global_rec_arr(self): self.check_global_rec_arr(forceobj=True) def test_global_rec_arr_npm(self): self.check_global_rec_arr(nopython=True) def check_global_rec_arr_extract(self, **jitargs): # (see github issue #897) ctestfunc = jit(**jitargs)(global_rec_arr_extract_fields) arr1 = np.zeros(rec_X.shape, dtype=np.int32) arr2 = np.zeros(rec_X.shape, dtype=np.float32) ctestfunc(arr1, arr2) np.testing.assert_equal(arr1, rec_X.a) np.testing.assert_equal(arr2, rec_X.b) def test_global_rec_arr_extract(self): self.check_global_rec_arr_extract(forceobj=True) def test_global_rec_arr_extract_npm(self): self.check_global_rec_arr_extract(nopython=True) def check_two_global_rec_arrs(self, **jitargs): # (see github issue #897) ctestfunc = jit(**jitargs)(global_two_rec_arrs) arr1 = np.zeros(rec_X.shape, dtype=np.int32) arr2 = np.zeros(rec_X.shape, dtype=np.float32) arr3 = np.zeros(rec_Y.shape, dtype=np.int16) arr4 = np.zeros(rec_Y.shape, dtype=np.float64) ctestfunc(arr1, arr2, arr3, arr4) np.testing.assert_equal(arr1, rec_X.a) np.testing.assert_equal(arr2, rec_X.b) np.testing.assert_equal(arr3, rec_Y.c) np.testing.assert_equal(arr4, rec_Y.d) def test_two_global_rec_arrs(self): self.check_two_global_rec_arrs(forceobj=True) def test_two_global_rec_arrs_npm(self): self.check_two_global_rec_arrs(nopython=True) def test_global_module(self): # (see github issue #1059) res = global_module_func(5, 6) self.assertEqual(True, res) def test_global_record(self): # (see github issue #1081) x = np.recarray(1, dtype=x_dt)[0] x.a = 1 res = global_record_func(x) self.assertEqual(True, res) x.a = 2 res = global_record_func(x) self.assertEqual(False, res) def test_global_int_tuple(self): pyfunc = global_int_tuple jitfunc = njit(pyfunc) self.assertEqual(pyfunc(), jitfunc()) def test_global_str_tuple(self): pyfunc = global_str_tuple jitfunc = njit(pyfunc) self.assertEqual(pyfunc(), jitfunc()) def test_global_mixed_tuple(self): pyfunc = global_mixed_tuple jitfunc = njit(pyfunc) self.assertEqual(pyfunc(), jitfunc()) def test_global_float_tuple(self): pyfunc = global_float_tuple jitfunc = njit(pyfunc) self.assertEqual(pyfunc(), jitfunc()) def test_global_npy_int_tuple(self): pyfunc = global_npy_int_tuple jitfunc = njit(pyfunc) self.assertEqual(pyfunc(), jitfunc()) if __name__ == '__main__': unittest.main()
imply/chuu
refs/heads/master
build/android/pylib/chrome_test_server_spawner.py
23
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A "Test Server Spawner" that handles killing/stopping per-test test servers. It's used to accept requests from the device to spawn and kill instances of the chrome test server on the host. """ import BaseHTTPServer import json import logging import os import select import struct import subprocess import sys import threading import time import urlparse import constants import ports from pylib.forwarder import Forwarder # Path that are needed to import necessary modules when launching a testserver. os.environ['PYTHONPATH'] = os.environ.get('PYTHONPATH', '') + (':%s:%s:%s:%s:%s' % (os.path.join(constants.DIR_SOURCE_ROOT, 'third_party'), os.path.join(constants.DIR_SOURCE_ROOT, 'third_party', 'tlslite'), os.path.join(constants.DIR_SOURCE_ROOT, 'third_party', 'pyftpdlib', 'src'), os.path.join(constants.DIR_SOURCE_ROOT, 'net', 'tools', 'testserver'), os.path.join(constants.DIR_SOURCE_ROOT, 'sync', 'tools', 'testserver'))) SERVER_TYPES = { 'http': '', 'ftp': '-f', 'sync': '', # Sync uses its own script, and doesn't take a server type arg. 'tcpecho': '--tcp-echo', 'udpecho': '--udp-echo', } # The timeout (in seconds) of starting up the Python test server. TEST_SERVER_STARTUP_TIMEOUT = 10 def _WaitUntil(predicate, max_attempts=5): """Blocks until the provided predicate (function) is true. Returns: Whether the provided predicate was satisfied once (before the timeout). """ sleep_time_sec = 0.025 for attempt in xrange(1, max_attempts): if predicate(): return True time.sleep(sleep_time_sec) sleep_time_sec = min(1, sleep_time_sec * 2) # Don't wait more than 1 sec. return False def _CheckPortStatus(port, expected_status): """Returns True if port has expected_status. Args: port: the port number. expected_status: boolean of expected status. Returns: Returns True if the status is expected. Otherwise returns False. """ return _WaitUntil(lambda: ports.IsHostPortUsed(port) == expected_status) def _CheckDevicePortStatus(adb, port): """Returns whether the provided port is used.""" return _WaitUntil(lambda: ports.IsDevicePortUsed(adb, port)) def _GetServerTypeCommandLine(server_type): """Returns the command-line by the given server type. Args: server_type: the server type to be used (e.g. 'http'). Returns: A string containing the command-line argument. """ if server_type not in SERVER_TYPES: raise NotImplementedError('Unknown server type: %s' % server_type) if server_type == 'udpecho': raise Exception('Please do not run UDP echo tests because we do not have ' 'a UDP forwarder tool.') return SERVER_TYPES[server_type] class TestServerThread(threading.Thread): """A thread to run the test server in a separate process.""" def __init__(self, ready_event, arguments, adb, tool, build_type): """Initialize TestServerThread with the following argument. Args: ready_event: event which will be set when the test server is ready. arguments: dictionary of arguments to run the test server. adb: instance of AndroidCommands. tool: instance of runtime error detection tool. build_type: 'Release' or 'Debug'. """ threading.Thread.__init__(self) self.wait_event = threading.Event() self.stop_flag = False self.ready_event = ready_event self.ready_event.clear() self.arguments = arguments self.adb = adb self.tool = tool self.test_server_process = None self.is_ready = False self.host_port = self.arguments['port'] assert isinstance(self.host_port, int) # The forwarder device port now is dynamically allocated. self.forwarder_device_port = 0 # Anonymous pipe in order to get port info from test server. self.pipe_in = None self.pipe_out = None self.command_line = [] self.build_type = build_type def _WaitToStartAndGetPortFromTestServer(self): """Waits for the Python test server to start and gets the port it is using. The port information is passed by the Python test server with a pipe given by self.pipe_out. It is written as a result to |self.host_port|. Returns: Whether the port used by the test server was successfully fetched. """ assert self.host_port == 0 and self.pipe_out and self.pipe_in (in_fds, _, _) = select.select([self.pipe_in, ], [], [], TEST_SERVER_STARTUP_TIMEOUT) if len(in_fds) == 0: logging.error('Failed to wait to the Python test server to be started.') return False # First read the data length as an unsigned 4-byte value. This # is _not_ using network byte ordering since the Python test server packs # size as native byte order and all Chromium platforms so far are # configured to use little-endian. # TODO(jnd): Change the Python test server and local_test_server_*.cc to # use a unified byte order (either big-endian or little-endian). data_length = os.read(self.pipe_in, struct.calcsize('=L')) if data_length: (data_length,) = struct.unpack('=L', data_length) assert data_length if not data_length: logging.error('Failed to get length of server data.') return False port_json = os.read(self.pipe_in, data_length) if not port_json: logging.error('Failed to get server data.') return False logging.info('Got port json data: %s', port_json) port_json = json.loads(port_json) if port_json.has_key('port') and isinstance(port_json['port'], int): self.host_port = port_json['port'] return _CheckPortStatus(self.host_port, True) logging.error('Failed to get port information from the server data.') return False def _GenerateCommandLineArguments(self): """Generates the command line to run the test server. Note that all options are processed by following the definitions in testserver.py. """ if self.command_line: return # The following arguments must exist. type_cmd = _GetServerTypeCommandLine(self.arguments['server-type']) if type_cmd: self.command_line.append(type_cmd) self.command_line.append('--port=%d' % self.host_port) # Use a pipe to get the port given by the instance of Python test server # if the test does not specify the port. if self.host_port == 0: (self.pipe_in, self.pipe_out) = os.pipe() self.command_line.append('--startup-pipe=%d' % self.pipe_out) self.command_line.append('--host=%s' % self.arguments['host']) data_dir = self.arguments['data-dir'] or 'chrome/test/data' if not os.path.isabs(data_dir): data_dir = os.path.join(constants.DIR_SOURCE_ROOT, data_dir) self.command_line.append('--data-dir=%s' % data_dir) # The following arguments are optional depending on the individual test. if self.arguments.has_key('log-to-console'): self.command_line.append('--log-to-console') if self.arguments.has_key('auth-token'): self.command_line.append('--auth-token=%s' % self.arguments['auth-token']) if self.arguments.has_key('https'): self.command_line.append('--https') if self.arguments.has_key('cert-and-key-file'): self.command_line.append('--cert-and-key-file=%s' % os.path.join( constants.DIR_SOURCE_ROOT, self.arguments['cert-and-key-file'])) if self.arguments.has_key('ocsp'): self.command_line.append('--ocsp=%s' % self.arguments['ocsp']) if self.arguments.has_key('https-record-resume'): self.command_line.append('--https-record-resume') if self.arguments.has_key('ssl-client-auth'): self.command_line.append('--ssl-client-auth') if self.arguments.has_key('tls-intolerant'): self.command_line.append('--tls-intolerant=%s' % self.arguments['tls-intolerant']) if self.arguments.has_key('ssl-client-ca'): for ca in self.arguments['ssl-client-ca']: self.command_line.append('--ssl-client-ca=%s' % os.path.join(constants.DIR_SOURCE_ROOT, ca)) if self.arguments.has_key('ssl-bulk-cipher'): for bulk_cipher in self.arguments['ssl-bulk-cipher']: self.command_line.append('--ssl-bulk-cipher=%s' % bulk_cipher) def _CloseUnnecessaryFDsForTestServerProcess(self): # This is required to avoid subtle deadlocks that could be caused by the # test server child process inheriting undesirable file descriptors such as # file lock file descriptors. for fd in xrange(0, 1024): if fd != self.pipe_out: try: os.close(fd) except: pass def run(self): logging.info('Start running the thread!') self.wait_event.clear() self._GenerateCommandLineArguments() command = constants.DIR_SOURCE_ROOT if self.arguments['server-type'] == 'sync': command = [os.path.join(command, 'sync', 'tools', 'testserver', 'sync_testserver.py')] + self.command_line else: command = [os.path.join(command, 'net', 'tools', 'testserver', 'testserver.py')] + self.command_line logging.info('Running: %s', command) self.process = subprocess.Popen( command, preexec_fn=self._CloseUnnecessaryFDsForTestServerProcess) if self.process: if self.pipe_out: self.is_ready = self._WaitToStartAndGetPortFromTestServer() else: self.is_ready = _CheckPortStatus(self.host_port, True) if self.is_ready: Forwarder.Map([(0, self.host_port)], self.adb, self.build_type, self.tool) # Check whether the forwarder is ready on the device. self.is_ready = False device_port = Forwarder.DevicePortForHostPort(self.host_port) if device_port and _CheckDevicePortStatus(self.adb, device_port): self.is_ready = True self.forwarder_device_port = device_port # Wake up the request handler thread. self.ready_event.set() # Keep thread running until Stop() gets called. _WaitUntil(lambda: self.stop_flag, max_attempts=sys.maxint) if self.process.poll() is None: self.process.kill() Forwarder.UnmapDevicePort(self.forwarder_device_port, self.adb) self.process = None self.is_ready = False if self.pipe_out: os.close(self.pipe_in) os.close(self.pipe_out) self.pipe_in = None self.pipe_out = None logging.info('Test-server has died.') self.wait_event.set() def Stop(self): """Blocks until the loop has finished. Note that this must be called in another thread. """ if not self.process: return self.stop_flag = True self.wait_event.wait() class SpawningServerRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """A handler used to process http GET/POST request.""" def _SendResponse(self, response_code, response_reason, additional_headers, contents): """Generates a response sent to the client from the provided parameters. Args: response_code: number of the response status. response_reason: string of reason description of the response. additional_headers: dict of additional headers. Each key is the name of the header, each value is the content of the header. contents: string of the contents we want to send to client. """ self.send_response(response_code, response_reason) self.send_header('Content-Type', 'text/html') # Specify the content-length as without it the http(s) response will not # be completed properly (and the browser keeps expecting data). self.send_header('Content-Length', len(contents)) for header_name in additional_headers: self.send_header(header_name, additional_headers[header_name]) self.end_headers() self.wfile.write(contents) self.wfile.flush() def _StartTestServer(self): """Starts the test server thread.""" logging.info('Handling request to spawn a test server.') content_type = self.headers.getheader('content-type') if content_type != 'application/json': raise Exception('Bad content-type for start request.') content_length = self.headers.getheader('content-length') if not content_length: content_length = 0 try: content_length = int(content_length) except: raise Exception('Bad content-length for start request.') logging.info(content_length) test_server_argument_json = self.rfile.read(content_length) logging.info(test_server_argument_json) assert not self.server.test_server_instance ready_event = threading.Event() self.server.test_server_instance = TestServerThread( ready_event, json.loads(test_server_argument_json), self.server.adb, self.server.tool, self.server.build_type) self.server.test_server_instance.setDaemon(True) self.server.test_server_instance.start() ready_event.wait() if self.server.test_server_instance.is_ready: self._SendResponse(200, 'OK', {}, json.dumps( {'port': self.server.test_server_instance.forwarder_device_port, 'message': 'started'})) logging.info('Test server is running on port: %d.', self.server.test_server_instance.host_port) else: self.server.test_server_instance.Stop() self.server.test_server_instance = None self._SendResponse(500, 'Test Server Error.', {}, '') logging.info('Encounter problem during starting a test server.') def _KillTestServer(self): """Stops the test server instance.""" # There should only ever be one test server at a time. This may do the # wrong thing if we try and start multiple test servers. if not self.server.test_server_instance: return port = self.server.test_server_instance.host_port logging.info('Handling request to kill a test server on port: %d.', port) self.server.test_server_instance.Stop() # Make sure the status of test server is correct before sending response. if _CheckPortStatus(port, False): self._SendResponse(200, 'OK', {}, 'killed') logging.info('Test server on port %d is killed', port) else: self._SendResponse(500, 'Test Server Error.', {}, '') logging.info('Encounter problem during killing a test server.') self.server.test_server_instance = None def do_POST(self): parsed_path = urlparse.urlparse(self.path) action = parsed_path.path logging.info('Action for POST method is: %s.', action) if action == '/start': self._StartTestServer() else: self._SendResponse(400, 'Unknown request.', {}, '') logging.info('Encounter unknown request: %s.', action) def do_GET(self): parsed_path = urlparse.urlparse(self.path) action = parsed_path.path params = urlparse.parse_qs(parsed_path.query, keep_blank_values=1) logging.info('Action for GET method is: %s.', action) for param in params: logging.info('%s=%s', param, params[param][0]) if action == '/kill': self._KillTestServer() elif action == '/ping': # The ping handler is used to check whether the spawner server is ready # to serve the requests. We don't need to test the status of the test # server when handling ping request. self._SendResponse(200, 'OK', {}, 'ready') logging.info('Handled ping request and sent response.') else: self._SendResponse(400, 'Unknown request', {}, '') logging.info('Encounter unknown request: %s.', action) class SpawningServer(object): """The class used to start/stop a http server.""" def __init__(self, test_server_spawner_port, adb, tool, build_type): logging.info('Creating new spawner on port: %d.', test_server_spawner_port) self.server = BaseHTTPServer.HTTPServer(('', test_server_spawner_port), SpawningServerRequestHandler) self.server.adb = adb self.server.tool = tool self.server.test_server_instance = None self.server.build_type = build_type def _Listen(self): logging.info('Starting test server spawner') self.server.serve_forever() def Start(self): """Starts the test server spawner.""" listener_thread = threading.Thread(target=self._Listen) listener_thread.setDaemon(True) listener_thread.start() def Stop(self): """Stops the test server spawner. Also cleans the server state. """ self.CleanupState() self.server.shutdown() def CleanupState(self): """Cleans up the spawning server state. This should be called if the test server spawner is reused, to avoid sharing the test server instance. """ if self.server.test_server_instance: self.server.test_server_instance.Stop() self.server.test_server_instance = None
mwojnars/nifty
refs/heads/master
web.py
1
# -*- coding: utf-8 -*- ''' Routines for web access, web scraping and HTML/XML processing. External dependencies: Scrapy 0.16.4 (for HTML/XML) TODO: possibly might replace urllib2 with Requests (http://docs.python-requests.org/en/latest/) --- This file is part of Nifty python package. Copyright (c) by Marcin Wojnarski. Nifty 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. Nifty 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 Nifty. If not, see <http://www.gnu.org/licenses/>. ''' from __future__ import absolute_import import os, sys, subprocess, threading #os.environ['http_proxy'] = '' # to fix urllib2 problem: urllib2.URLError: <urlopen error [Errno -2] Name or service not known> import urllib2, urlparse, random, time, socket, json, re from collections import namedtuple, deque from copy import deepcopy from datetime import datetime from urllib2 import HTTPError, URLError from cookielib import CookieJar from socket import timeout as Timeout #from lxml.html.clean import Cleaner -- might be good for HTML sanitization (no scritps, styles, frames, ...), but not for general HTML tag filering if __name__ != "__main__": from .util import islinux, isint, islist, isnumber, isstring, JsonDict, mnoise, unique, classname, noLogger, defaultLogger, Object from .text import regex, xbasestring, HTML, Plain from . import util else: from nifty.util import islinux, isint, islist, isnumber, isstring, JsonDict, mnoise, unique, classname, noLogger, defaultLogger, Object from nifty.text import regex, xbasestring, HTML, Plain from nifty import util now = time.time # shorthand for calling now() function, for process-local time measurement ######################################################################################################################################################################## ### ### UTILITIES ### ### URLs ### def fix_url(url): """Add 'http' at the beginning of a URL if doesn't exist. Can be extended to provide character encoding, see werkzeug and: http://stackoverflow.com/a/121017/1202674 """ if "://" not in url[:12]: return "http://" + url return url def urljoin(base, url, allow_fragments=True, empty=False): """" Extended and slightly modified version of original urlparse.urljoin, in that: (1) url can be a list of URL fragments; then all of them are appended independently to the same base and a list of results is returned; (2) if empty=False (default!), every empty or None fragment yields None as a result instead of 'base'; incompatible with HTML standard, but convenient in crawling """ if islist(url): if empty: return [urlparse.urljoin(base, u, allow_fragments) for u in url] else: return [urlparse.urljoin(base, u, allow_fragments) if u else None for u in url] if empty: return urlparse.urljoin(base, url, allow_fragments) else: return urlparse.urljoin(base, url, allow_fragments) if url else None class ShortURL(object): """Encodes integers (IDs of objects in DB) as short strings: something like base-XX encoding of a number, with XX ~= 60. Code derived from stackoverflow: http://stackoverflow.com/questions/1119722/base-62-conversion-in-python""" BASE_LIST = "123456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" # confusing characters left out: 0OolI BASE_DICT = dict((c, i) for i, c in enumerate(BASE_LIST)) @staticmethod def encode(integer, base = BASE_LIST, degree = len(BASE_LIST)): ret = '' while integer != 0: ret = base[integer % degree] + ret integer /= degree return ret @staticmethod def decode(string, reverse_base = BASE_DICT, degree = len(BASE_DICT)): ret = 0 for i, c in enumerate(string[::-1]): ret += (degree ** i) * reverse_base[c] return ret ### Errors ### # HTTPError, URLError, Timeout -- standard exception classes that can all be imported from this module def failedToConnect(ex): "True if exception 'ex' indicates initial connection (not server) error: no internet connection, service unknown etc." # recognized two types of URLError exceptions: <urlopen error [Errno -2] Name or service not known> and <urlopen error timed out> return isinstance(ex, URLError) and hasattr(ex, 'reason') and (ex.reason[0] == -2 or str(ex.reason) == "timed out") ### HTML ### def noscript(html, pat1 = re.compile(r"<script", re.IGNORECASE), pat2 = re.compile(r"</script>", re.IGNORECASE)): "Comment out all <script.../script> blocks in a given HTML text. In rare cases may break consistency, e.g., when '<script' or '/script>' text occurs inside a comment or string" html = pat1.sub(r'<!--<script', html) html = pat2.sub(r'</script>-->', html) return html def striptags(html, norm = True): """Parses HTML snippet with libxml2 and extracts text contents using XPath. Decodes entities. If norm=True, strips and normalizes spaces. HTML comments ignored, <script> <style> contents included. >>> striptags("<i>one</i><u>two</u><p>three</p><div>four</div>") u'onetwothreefour' """ return xdoc(html).text(norm = norm) ### Other ### def readsocket(sock): """Reads ALL contents from the socket. Workaround for the known problem of library sockets (also in urllib2): that read() may sometimes return only a part of the contents and it must be called again and again, until empty result, to read everything. Should always be used in place of .read(). Closes the socket at the end.""" content = [] while True: cont = sock.read() if cont: content.append(cont) else: sock.close() return ''.join(content) # list from: http://techblog.willshouse.com/2012/01/03/most-common-user-agents/ common_user_agents = \ """ Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11 Mozilla/5.0 (Windows NT 5.1; rv:13.0) Gecko/20100101 Firefox/13.0.1 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5 Mozilla/5.0 (Windows NT 6.1; rv:13.0) Gecko/20100101 Firefox/13.0.1 Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11 Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11 Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11 Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5 Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11 Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5; Windows NT 5.0) Opera 7.02 Bork-edition [en] Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; FunWebProducts; .NET CLR 1.1.4322; PeoplePal 6.2) Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1 Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0 Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5 Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727) Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322) Mozilla/5.0 (Windows NT 5.1; rv:5.0.1) Gecko/20100101 Firefox/5.0.1 Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.02 Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 3.5.30729) Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1 Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:13.0) Gecko/20100101 Firefox/13.0.1 Mozilla/5.0 (Windows NT 6.1; rv:2.0b7pre) Gecko/20100921 Firefox/4.0b7pre Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0) Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0 Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:13.0) Gecko/20100101 Firefox/13.0.1 Mozilla/5.0 (Windows NT 6.0; rv:13.0) Gecko/20100101 Firefox/13.0.1 """.strip().split("\n") def webpage_simple(url): "Get HTML page from the web (simple variant)" url = fix_url(url) return readsocket(urllib2.urlopen(url)) def webpage(url, timeout = None, identity = None, agent = 0, referer = None, header = None, opener = urllib2.build_opener()): #mechanize.Browser()): """ Get HTML page from the web. Headers are set to enable robust scraping. Follows redirects, but there is no way for the client to detect this. """ url = fix_url(url) # create header; overwrite values in 'header' if more specific settings are given if not header: header = { 'Accept':'*/*' } if identity: header.update(identity.header()) elif not 'user-agent' in [k.lower() for k in header.keys()]: if agent is None: agent = random.choice(common_user_agents) elif isinstance(agent, int): agent = common_user_agents[agent] header['User-Agent'] = agent if referer is not None: header['Referer'] = referer # download page req = urllib2.Request(url, None, header) if timeout: stream = opener.open(req, timeout = timeout) else: stream = opener.open(req) page = readsocket(stream) stream.close() if identity: identity.update(url, page) return page def _webpage(url, timeout = None, identity = None, agent = 0, referer = None, client = None): "Get HTML page from the web. Headers are set to enable robust scraping." client = client or WebClient() return client().open(url) def checkMyIP(web = None, test = 1): """Check what external IP of mine will be visible for servers when I connect via a given web client. Disables cache beforehand if needed (re-enables after check). See also test=2 and proxy detection: > print web.open("http://www.iprivacytools.com/proxy-checker-anonymity-test/") """ web = web or WebClient(tor=True) def test1(): "Fast and simple, based on public high-load API. See: http://www.exip.org/api" return web.open("http://api-ams01.exip.org/?call=ip") def test2(): "Tries to detect proxies, too; returns a *list* of all IPs that can be detected" page = web.open("http://www.cloakfish.com/?tab=proxy-analysis") ips = xbasestring(page).re(regex.ip, True) return unique(ips) cache = web._cache.enabled if cache: web._cache.disable() tests = {1:test1, 2:test2} ip = tests[test]() if cache: web._cache.enable() return ip ################################################################################################################################################ ### ### REQUEST, RESPONSE, WEBHANDLER - base classes ### class Request(urllib2.Request): """ When setting headers (self.headers from base class), all keys are capitalized by urllib2 (!) to avoid duplicates. To assign individual items in the header, use add_header() instead of manual modification of self.headers! """ def __init__(self, url, data = None, headers = {}, timeout = None): urllib2.Request.__init__(self, url = url, data = data, headers = headers) self.url = url self.timeout = timeout class Response(): redirect = url = request = info = headers = status = time = None content = None # string with all contents of the page, loaded in a lazy way: on explicit client's request fromCache = False def __init__(self, resp = None, url = None, read = True): "resp: open file (socket) returned by urllib2 (type: urllib2.addinfourl) or None. url: optionally the original URL of the request (before any redirection)" if not resp: return self.resp = resp # keep original urllib response self.redirect = resp.geturl() # if redirect happened, contains final URL (after all redirections) of the contents; None if no redirect self.url = self.redirect or url # final URL of the contents: either the redirected URL or the original one if no redirection happened self.request = url # original URL of the request, before redirections self.info = resp.info() self.headers = dict(self.info) # HTTP headers as a plain dictionary, all keys lower-case, e.g.: content-type, content-length, last-modified, server, date, ... self.status = self.code = resp.getcode() # HTTP response status code; self.code is deprecated, use self.status instead self.time = datetime.now() # timestamp when the page was originally retrieved; can be overriden, e.g., by cache handler when an older version is loaded from disk if read: self.read() def __deepcopy__(self, memo): "Custom implementation of deepcopy(). Makes shallow copy of self.resp and deep copy of all other properties." dup = Response() for key, val in self.__dict__.iteritems(): if key == 'resp': dup.resp = val else: setattr(dup, key, deepcopy(val, memo)) return dup def read(self): if self.content is None and self.resp: self.content = readsocket(self.resp) # the socket is closed afterwards, by readsocket() return self.content class WebHandler(Object): """ Base class for handlers of web requests & responses, which handle different atomic aspects of web access. Handlers can be chained together to provide flexible and configurable behavior when accessing the web. The concept is similar to urllib2's BaseHandler and OpenerDirector, only done much better, with wider range of tasks that can be handled by WebHandlers (e.g., page caching can't be implemented in urllib2's framework). """ # fall-back properties for reading, in case if __init__ wasn't invoked in the subclass next = None enabled = True log = noLogger # logger to be used by handlers for printing messages and errors __shared__ = 'log' def __init__(self, nextHandler = None): self.next = nextHandler self.enabled = True @classmethod def chain(cls, listOfHandlers): "Connects given handlers into a chain using their .next fields. Automatically filters out None items. The list can contain nested sublists (will be flattened). Returns head of the chain" listOfHandlers = filter(None, util.flatten(listOfHandlers)) if not listOfHandlers: return None for i in range(len(listOfHandlers) - 1): prev, next = listOfHandlers[i:i+2] prev.next = next return listOfHandlers[0] @classmethod def unchain(cls, firstHandler): "Disconnects the chain and returns all handlers as a plain list" h = firstHandler l = [] while h: l.append(h) h = h.next h.next = None return l def list(self): "List of all handlers of the chain that starts at 'self' as a head." l = []; cur = self while cur: #and isinstance(cur, WebHandler): l.append(cur) cur = cur.next return l def handle(self, req): """Handles Request 'req' using the chain of handlers headed by self. Should return Response, or exception in case of error.""" raise Exception("Method WebHandler.handle() is abstract") def disable(self): "Substitutes 'handle' method of 'self' with a mock-up that passes all requests down the chain unmodified. Call enable() to recover original handler" self.handle = self.mockup self.enabled = False def enable(self): "Reverses the effect of disable()" del self.handle self.enabled = True def mockup(self, req): return self.next.handle(req) ################################################################################################################################################ ### ### WEB HANDLERS - concrete classes for different tasks ### class StandardClient(WebHandler): "Returns a web page using standard urllib2 access. Custom urllib2 handlers can be added upon initialization" def __init__(self, addHandlers = [], cj = None): "cj - a cookiejar if cookies handled" self.opener = urllib2.build_opener(*addHandlers) self.added = [h.__class__.__name__ for h in addHandlers] self.cj = cj # we need to keep CookieJar in order to clean cookies def handle(self, req): assert isinstance(req, Request) #self.log.info("StandardClient, downloading page. Request & handlers: " + jsondump([req, self.added])) self.log.info("StandardClient, downloading", req.url) try: if req.timeout: stream = self.opener.open(req, timeout = req.timeout) else: stream = self.opener.open(req) except HTTPError, e: e.msg += ", " + req.url raise try: # clean cookies between requests, this is not a browser, it does # not need to remember them self.cj.clear() except KeyError: pass # if there was no cookie, KeyError is risen, skip return Response(stream, req.url) class FixURL(WebHandler): def handle(self, req): req.url = fix_url(req.url) return self.next.handle(req) class Delay(WebHandler): "Delays web requests so that they are separated by at least 'delay' seconds (but possibly no more than this); 'delay' is slightly randomly disturbed each time" def __init__(self, delay = 1.5): self.last = now() - delay self.delay = delay def handle(self, req): delay = self.delay * (random.random()/5 + 0.9) t = delay - (now() - self.last) if t > 0: time.sleep(t) self.last = now() return self.next.handle(req) class Timeout(WebHandler): "Add timeout value to every request" def __init__(self, timeout = 10): self.timeout = timeout def handle(self, req): req.timeout = self.timeout return self.next.handle(req) class RetryOnError(WebHandler): """In case of an exception of a given class retries the request a given number of times, only then forwards to the caller. Default exception class: Exception. Default excludes: 'timeout', HTTPError 403 (Forbidden), HTTPError 404 (Not Found)""" def __init__(self, attempts = 3, delay = 5, exception = Exception, exclude = [Timeout, 403, 404]): self.attempts = attempts self.delay = delay self.exception = exception self.exclude = [cls for cls in exclude if not isint(cls)] self.excludeHTTP = [code for code in exclude if isint(code)] def handle(self, req): for i in range(self.attempts + 1): try: _req = deepcopy(req) # we may need original 'req' again in the future, thus copying return self.next.handle(_req) except self.exception, e: for x in self.exclude: if isinstance(e,x): raise if isinstance(e, HTTPError): if e.getcode() in self.excludeHTTP: raise self.log.warning("%s, attempt #%d, %s trying again... Caught '%s'" % (classname(self,False), i+1, req.url, e)) time.sleep(self.delay * mnoise(1.1)) return self.next.handle(req) class RetryOnTimeout(RetryOnError): """In case of timeout error, retry the request a given number of times, only then forward Timeout exception to the caller. Only for response timeout (!), NOT for connection opening timeout (that's a different class: URLError 'timed out' not Timeout).""" def __init__(self, attempts = 3, delay = 5): handlers.RetryOnError.__init__(self, attempts, delay, exception = Timeout, exclude = []) class RetryCustom(WebHandler): "Uses client-provided function 'test' for analyzing errors (exceptions) and deciding whether to retry (return False if not), and with what delay (return >0)" def __init__(self, test): "'test' is a function of 2 arguments: exception and the no. of attempts done so far, returning new delay or None for stop. See exampleTest() below." self.test = test def exampleTest(ex, attempt): "attempt: no. of attempts done so far, always >= 1" if isinstance(ex, Timeout): return 5.0 if attempt < 3 else False if isinstance(ex, HTTPError): status = ex.getcode() if status != 404: return 1.0 return False # forward other exceptions def handle(self, req): attempt = 0 while True: try: attempt += 1 _req = deepcopy(req) # we may need original 'req' again in the future, thus copying return self.next.handle(_req) except Exception, e: delay = self.test(e, attempt) if not delay: raise delay *= mnoise(1.1) self.log.warning("RetryCustom, attempt #%d, trying again after %d seconds... Caught %s" % (attempt, delay, e)) time.sleep(delay) return self.next.handle(req) class UserAgent(WebHandler): def __init__(self, agent = None, change = None): """agent: predefined User-Agent (string) to be used; or None to pick User-Agent randomly from a list of most common ones. change: time (in minutes) how often UA should be randomly changed; or None if no changes should be done. """ if agent: self.agent = agent else: self.agent = random.choice(common_user_agents) self.change = change * 60 if change else None # convert minutes to seconds self.lastChange = now() def handle(self, req): req.add_header('User-Agent', self.agent) if self.change and (now() - self.lastChange > self.change): self.agent = random.choice(common_user_agents) self.lastChange = now() return self.next.handle(req) class History(WebHandler): Event = namedtuple('Event', 'req resp') def __init__(self, maxlen = None): "maxlen: must be >= 1, or None (no limit)" self.events = [] # a list of "back" and "forward" events, as (request,response) pairs self.current = 0 # no. of "back" events in self.events (remaining events are "forward") if maxlen and (not isnumber(maxlen) or maxlen < 1): maxlen = 1 self.maxlen = maxlen def handle(self, req): _req = deepcopy(req) resp = self.next.handle(req) self.events = self.events[:self.current] # we're moving forward, so forget all "forward" events, if present M = self.maxlen if M and len(self.events) >= M: self.events = self.events[-(M-1):] if M > 1 else [] # create space for new event self.events.append(self.Event(_req, deepcopy(resp))) # must perform deepcopies because req/resp objects are modified down and up the handlers chain self.current = len(self.events) return resp def last(self): "Return last (request,response) if present; otherwise None. Don't move history pointer" if self.current > 0: return self.events[self.current - 1] return None def back(self): "If possible, move history pointer 1 step back and return that response object again; otherwise None" if self.current > 1: self.current -= 1 return self.last() return None def forward(self): "If possible, move history pointer 1 step forward and return that response object again; otherwise None" if self.current < len(self.events): self.current += 1 return self.last() return None def reset(self): "Clear history entirely" self.events = [] self.current = 0 class Referer(WebHandler): def __init__(self, history): "history: the History handler instance which will be used to get info about last webpage visited" self.history = history def handle(self, req): last = self.history.last() if last: lasturl = last.resp.url or last.req.url # better to take url from response, but if missing we must use url from request if lasturl: prefix = os.path.commonprefix([lasturl, req.url]) suffix = req.url[len(prefix):-1] #print repr(suffix) #print repr(last.resp.content) if str(suffix) in last.resp.content: # suffix - simple heuristic to check if the new URL really occured in the previous page; str() to handle URL being unicode object req.add_header('Referer', lasturl) return self.next.handle(req) class Cache(WebHandler): """Web caching: enables repeated access to the same www page without its reloading. Cache is located on disk, in a folder given as parameter; pages stored in separate files named after their URLs. When redirection occurs, a special type of file (*.redirect) is created pointing to the new URL, so that the returned response can have final URL set correctly. https://pypi.python.org/pypi/pyxattr/0.5.2 - module for Extended File Attributes (might be needed) """ DEFAULT_PATH = ".webcache/" # default folder where cached pages are stored (will be created if doesn't exist) STATE_FILE = ".state.json" def __init__(self, path = DEFAULT_PATH, refresh = 1.0, retain = 30): """refresh: how often pages in cache should be refreshed, in days; default: 1 day retain: for how long pages should be kept in cache even after refresh period (for safety); default: 30 days; not less than 'refresh' (increased up to 'refresh' if necessary) """ if not isstring(path): path = self.DEFAULT_PATH if path[-1] != '/': path += '/' if not os.path.exists(path): os.makedirs(path) self.path = path if not refresh: refresh = 1.0 self.refresh = refresh * 24*60*60 # refresh copies after this time, in seconds self.retain = max(retain, refresh) * 24*60*60 # keep copies in cache for this long, in seconds self.clean = self.refresh / 10.0 # how often to clean the cache: on every startup + 50 times over 'refresh' period self.clean = max(self.clean, 60*60) # ...but not more often than every hour self.state = JsonDict(path + self.STATE_FILE, indent = 4) self.state.setdefault('lastClean') def _clean_cache(self): if self.state['lastClean'] and (now() - self.state['lastClean']) < self.clean: return self.state['lastClean'] = now() self.state.sync() self.log.warn("Cache, cleaning of the cache started in a separate thread...") if islinux(): # on Linux, use faster shell command (find) to find and remove old files, in one step retain = self.retain / (24*60*60) + 1 # retension time in days, for 'find' command subprocess.call("find '%s' -maxdepth 1 -type f -mtime +%d -exec rm '{}' \;" % (self.path, retain), shell=True) else: MAX_CLEAN = 10000 # for performance reasons, if there are many files in cache check only a random subset of MAX_CLEAN ones for removal _now = now() files = os.listdir(self.path) self.log.info("Cache, cleaning, got file list...") if len(files) > MAX_CLEAN: files = random.sample(files, MAX_CLEAN) for f in files: f = self.path + f created = os.path.getmtime(f) if (_now - created) > self.retain: os.remove(f) self.log.info("Cache, cleaning completed.") def _url2file_old(self, url, ext = "html"): # Deprecated safeurl = url.replace('/', '\\') filename = safeurl + " " + str(hash(url)) return self.path + filename + "." + ext def _url2file(self, url, ext = "html", pat = re.compile(r"""[/"'!?\\&=:]"""), maxlen = 60): "Encode URL to obtain a correct file name, preceeded by cache path" safeurl = pat.sub('_', url.replace('://', '_'))[:maxlen] filename = safeurl + "_" + str(hash(url)) return self.path + filename + "." + ext def _cachedFile(self, url, ext = "html"): "if possible, return cached copy and its file modification time, otherwise (None,None)" filename = self._url2file(url, ext) if not os.path.exists(filename): filename = self._url2file_old(url, ext) if not os.path.exists(filename): return None, None created = os.path.getmtime(filename) if now() - created > self.refresh: return None, None # we have a copy, but time to refresh (don't delete instantly for safety, if web access fails) with open(filename) as f: time = util.filedatetime(filename) return f.read(), time def _cachedResponse(self, req): # is there a .redirect file? url = req.url content, time1 = self._cachedFile(url, 'redirect') if content: url = content # .redirect file contains just the target URL in plain text form # now check the actual .html file content, time2 = self._cachedFile(url) if content == None: return None # found in cache; return a Response() object resp = Response() resp.content = content resp.fromCache = True resp.url = url resp.time = min(time1 or time2, time2 or time1) self.log.info("Cache, loaded from cache: " + req.url + (" -> " + url if url != req.url else "")) return resp def handle(self, req): # page in cache? resp = self._cachedResponse(req) if resp != None: return resp # download page and save in cache under final URL resp = self.next.handle(req) url = resp.url filename = self._url2file(url) with open(filename, 'wt') as f: f.write(resp.content) # redirection occured? create a .redirect file under original URL to indicate this fact if url != req.url: filename = self._url2file(req.url, 'redirect') with open(filename, 'wt') as f: f.write(url) # .redirect file contains only the target URL in plain text form self.log.info("Cache, downloaded from web: " + req.url + (" -> " + url if url != req.url else "")) lastClean = self.state['lastClean'] if not lastClean or (now() - lastClean) > self.clean: # remove old files from the cache before proceeding threading.Thread(target = self._clean_cache).start() # we'll not join this thread, but application will not terminate until this thread ends (!); set .deamon=True otherwise return resp class CustomTransform(WebHandler): "Base class for any handler that performs simple 1-1 transformation of either the request or/and the response object." def handle(self, req): req = self.preprocess(req) resp = self.next.handle(req) resp = self.postprocess(resp) return resp def preprocess(self, req): "Override in subclasses" return req def postprocess(self, resp): "Override in subclasses" return resp class Callback(WebHandler): """Call predefined external functions on forward and backward passes, with Request or Request+Response objects as arguments. Typically, the functions should only perform monitoring and reporting, but it's also technically possible that they modify the internals of Request/Response objects. """ def __init__(self, onRequest = None, onResponse = None): self.onRequest = onRequest self.onResponse = onResponse def handle(self, req): if self.onRequest is not None: self.onRequest(req) resp = self.next.handle(req) if self.onResponse is not None: self.onResponse(req, resp) return resp class handlers(object): "Legacy." # TODO: remove! StandardClient = StandardClient FixURL = FixURL Delay = Delay Timeout = Timeout RetryOnError = RetryOnError RetryOnTimeout = RetryOnTimeout RetryCustom = RetryCustom UserAgent = UserAgent History = History Referer = Referer Cache = Cache ########################################################################################################################################## ### ### WEB CLIENT ### class WebClient(Object): """ >>> w1 = WebClient() >>> w2 = w1.copy() >>> id(w1.logger) == id(w2.logger) True >>> id(w1.handlers) <> id(w2.handlers) and id(w1.handlers.log) == id(w2.handlers.log) True """ __shared__ = 'logger' # atomic handlers that comprise the 'handlers' chain, in the same order; # _head and _tail are lists of custom handlers that go at the beginning or at the end of all handlers list _history = _head = _cache = _useragent = _referer = _timeout = _retryCustom = _retryOnError = _retryOnTimeout = _delay = _tail = _client = None _tor = False # self._tor is a read-only attr., changing it does NOT influence whether Tor is used or not, this is decided in __init__ and can't be changed handlers = None # head (only!) of the chain of handlers logger = None # the logger that was passed down to all handlers in setLogger() def __init__(self, timeout = None, identity = True, referer = True, cache = None, cacheRefresh = None, tor = False, history = 5, delay = None, retryOnTimeout = None, retryOnError = None, retryCustom = None, head = [], tail = [], logger = None, cookies = False, proxyAddr = None): """ :param identity: how to set User-Agent. Can be either: None/False (no custom identity); or True (identity will be selected randomly once and never changed); or <str> (string to be used as User-Agent); or <number> X (identity will be picked randomly and changed to another random one after every 'X' minutes) :param history: if number, maximum num of extract to be kept in web history; if True, history with no limit; otherwise (None, <1), limit=1 :param cacheRefresh: either None, or a number (refresh == retain), or a pair (refresh, retain); typically refresh <= retain :param proxy: if string with proxy address (as adress:port) then connections will be proxies via this address or None """ H = handlers # create cookiejar, which handles cookies while requesting # unfortunately cj is required for cleaning cookies cj = CookieJar() if cookies: urllib2hand = [urllib2.HTTPCookieProcessor(cj)] else: urllib2hand = [] self.logger = logger if isnumber(history): histLimit = max(history, 1) # always keep at least 1 history item elif history is True: histLimit = None else: histLimit = 1 self._history = H.History(histLimit) if timeout: self._timeout = H.Timeout(timeout) if identity: self._useragent = H.UserAgent(identity if isstring(identity) else None, identity if isnumber(identity) else None) if referer: self._referer = H.Referer(self._history) if cache: self.setCache(cache, cacheRefresh) if delay: self._delay = H.Delay(delay) if retryOnError: self._retryOnError = H.RetryOnError(retryOnError) if retryOnTimeout: self._retryOnTimeout = H.RetryOnTimeout(retryOnTimeout) if retryCustom: self.setRetryCustom(retryCustom) if tor: self._tor = True; urllib2hand.append(urllib2.ProxyHandler({'http': '127.0.0.1:8118'})) if proxyAddr and not tor: # either tor, or proxy, not both, tor is cheaper so has priority self._proxy = True handler = urllib2.ProxyHandler({'http': proxyAddr, 'https': proxyAddr}) # TODO maybe some checking correctness of proxy string? urllib2hand.append(handler) self._head = head if islist(head) else [head] self._tail = tail if islist(tail) else [tail] self._client = H.StandardClient(urllib2hand, cj) self._rebuild() # connect all the handlers into a chain self.url_now = None # URL being processed now (started but not finished); for debugging purposes, when exception occurs inside open() def copy(self): return deepcopy(self) def setCache(self, path, refresh = None, retain = None): "Default retain period = 1 year. 'refresh' can hold a pair: (refresh, retain), then 'retain' is not used." if islist(refresh) and len(refresh) >= 2: refresh, retain = refresh[:2] if not retain: retain = refresh self._cache = handlers.Cache(path, refresh, retain) def setRetryCustom(self, retryCustom): self._retryCustom = handlers.RetryCustom(retryCustom) def setLogger(self, logger): if logger is True: logger = defaultLogger elif not logger: logger = noLogger self.logger = logger if not self.handlers: return for h in self.handlers.list(): h.log = self.logger def addHandler(self, handler, location = 'head'): """Add custom handler, either at the beginning of _head if location='head' (default); or at the end of _tail, as the deepest handler that will directly connect to the actual client (StandardClient), if location='tail'.""" if location == 'head': self._head = [handler] + self._head else: self._tail.append(handler) self._rebuild() return self # chaining the calls is possible: return client.addHandler(...).addHandler(...) def removeHandler(self, handler): """Remove a handler that was added with addHandler(), either to the head or tail of the handlers list. If the same handler has been added multiple times, its first occurence is removed. ValueError is raised if the handler is not present in the list. """ if handler in self._head: self._head.remove(handler) elif handler in self._tail: self._tail.remove(handler) else: raise ValueError("WebClient.removeHandler: handler (%s) not in list" % handler) self._rebuild() return self # chaining the calls is possible: return client.removeHandler(...).removeHandler(...) def _rebuild(self): "Rearrange handlers into a chain once again." self.handlers = WebHandler.chain([self._history, self._head, self._cache, self._useragent, self._referer, self._timeout, self._retryCustom, self._retryOnError, self._retryOnTimeout, self._delay, self._tail, self._client]) self.setLogger(self.logger) def response(self, url = None, data = None, headers = {}): """Return current (last) response object if url=None, or make a new request like open() and return full response object. The method is aware of movements along history: back(), forward(), ...""" if not url: last = self._history.last() return last.resp if last else None # new request... self.url_now = url url = fix_url(url) req = Request(url = url, data = data, headers = headers) resp = self.handlers.handle(req) self.url_now = None return resp # implicitly, the 'resp' object is remembered in browsing history, too open = response #@ReservedAssignment def get(self, url = None): """Main method for downloading pages. Calls response() and returns all contents of the page as string (without metadata). If url=None, loads and returns the contents of the last accessed URL - which typically was only opened with open() or response(), but not fully loaded.""" return self.response(url).read() #open = get # TODO: change open() API to only initiate the connection but not read the data def download(self, filename, url = None): "Download a page and save in file. The file will be overriden if exists. If url=None, the last accessed page is downloaded (or just saved if already retrieved)." # TODO: transform to stream not batch download, to handle pages of arbitrary size page = self.get(url) with open(filename, 'wt') as f: f.write(page) def url(self): "Return requested URL of the last web access. (Use response() to get last response object.)" last = self._history.last() return last.req.url if last else None def final(self): "Return final URL of the last web access, after all redirections." last = self._history.last() return last.resp.url if last else None def redirect(self): "Return final URL of the last web access, but only if redirection happened. None otherwise." last = self._history.last() return last.resp.redirect if last else None def back(self): "Move 1 step back in history" return self._history.back() def forward(self): "Move 1 step forward in history" return self._history.forward() def reset(self): "Clear history" self._history.reset() def publicIP(self, api = "http://icanhazip.com"): """Connects with a public API that returns our current public IP number. Returns this number in text form, as received from the API, only stripped of spaces. Skips all handlers, uses only the last one: self._client.""" req = Request(fix_url(api)) resp = self._client.handle(req) return resp.read().strip() ######################################################################################################################################################################## ### ### Crawler (draft) ### class Crawler(object): client = WebClient(timeout = 60, retryOnTimeout = 2, history = 1) start = [] # list of start URLs domains = None # list of domain names to crawl (others will be ignored), case insensitive, implicitly includes all subdomains; None if all domains to be included url_include = None # if not-None, every visited URL must match this pattern or function url_exclude = None # if not-None, every visited URL must NOT match this pattern or function pages_limit = None # max. number of pages to visit links_limit = None # max. no. of URLs extracted from a single page; if more links are present, only the first 'limit_page' are used random = False # if True, URLs will be visited in random order and not strictly breadth-first, rather than in their order on page def __init__(self, **kwargs): self.__dict__.update(kwargs) self.urls = deque(self.start) # queue of pending URLs (pages not downloaded yet) self.visited = set() # combine filtering patterns into one regex self.url_filter def pages(self): """Generator that yields consecutive URLs and pages visited, as pairs (url, page_content, response_object), starting URLs included; 'url' and 'page' are strings, 'response' is an http Response object, with fields like status code, headers etc. At the end (when all urls processed or terminated by client) the final state of crawling process is still present in self.urls and self.visited. Invoking the crawler again will start from the point where previous call has finished! """ def nexturl(self): if not self.urls: return None if random: i = random.randint(0, len(self.urls)-1) url = self.urls[i] self.urls[i] = self.urls.popright() return url return self.urls.popleft() def skip(url): if not self.allowed(url) or url in self.visited: return True return False while True: url = nexturl() if url is None: break # no more pages to visit if skip(url): continue self.visited.add(url) try: page = self.client.get(url) except: continue # failed to open the page? ignore yield url, page self.urls += self.process(page, url) def allowed(self, url): "Check if this url is allowed to visit." @staticmethod def extractUrls(page, parsehtml = False): #if self.nofollow(url): continue # filter out non-HTML contents return [] def process(self, page, url): "Called in crawler loop. Can be overriden in subclasses to provide custom processing of pages. extraction of URLs and/or custom data collection from visited pages." return self.extractUrls(page, url) ######################################################################################################################################################################## ### ### XML/HTML processing, XDoc ### ### Classes from Scrapy for XPath selections: HtmlXPathSelector, ... - monkey-patched to add several useful methods. ### Scrapy's XPath is just a wrapper for libxml2, perhaps slightly easier to use than raw libxml2, ### but should be replaced in the future with reference to underlying basic implementation to remove dependency on Scrapy. ### Scrapy home: http://scrapy.org/ ### ### Example use: ### page = xdoc(URL) ### node = page['xpath...'] ### print node.text() ### ### Methods (some of them from Scrapy): ### css, css1, xpath, node, nodes, html, text, texts, anchor ### nodeWithID, nodeOfClass, nodesOfClass, nodeAfter, textAfter ### [], ... in ### try: # newer versions of Scrapy from scrapy.selector.unified import SelectorList as XPathSelectorList try: from scrapy.selector import Selector # newer except: from scrapy import Selector # older HtmlXPathSelector = XmlXPathSelector = XPathSelector = Selector OLD_SCRAPY = False except ImportError: # older versions of Scrapy; TODO: drop entirely from scrapy.selector.list import XPathSelectorList from scrapy.selector import HtmlXPathSelector, XmlXPathSelector, XPathSelector OLD_SCRAPY = True def xpath_escape(s): """Utility function that works around XPath's lack of escape character and converts given string (if necessary) into concat(...) expression, so that all characters can be used. Returns either a quoted string or concat(..) expression (as a string)""" if "'" not in s: return "'%s'" % s if '"' not in s: return '"%s"' % s return "concat('%s')" % s.replace("'", "',\"'\",'") def xdoc(text, mode = "html"): "Wrap up the 'text' in a XPathSelector object of appropriate type (xml/html). If 'text' is already an X, return unchanged." if isinstance(text, XPathSelector): return text return XmlXPathSelector(text=text) if mode.lower() == 'xml' else HtmlXPathSelector(text=text) def isxdoc(obj): "In the future we might use custom XDoc class instead of XPathSelector. Use this function rather than directly isinstance(XPathSelector)" return isinstance(obj, XPathSelector) # XNone: analog of None returned by default from all node*() operators instead of None (to get None use none=True parameter); # like None evaluates to False, but at the same time is a regular X node and thus has all XPath methods defined (they return empty strings or XNone's). # Useful when more operations are to be executed on the result node, to prevent exceptions of access to non-existing methods. class XNoneType(HtmlXPathSelector): """ >>> bool(XNone) False """ def __init__(self): HtmlXPathSelector.__init__(self, text = "<_XNone_></_XNone_>") def __bool__(self): return False __nonzero__ = __bool__ @staticmethod def text(*a, **kw): return Plain('') def extract(self): return HTML('') html = __unicode__ = extract XNone = XNoneType() _XPathSelector_extract = XPathSelector.extract # must keep original extract() on aside to still call it after monkey patching class XDoc(object): """ All the methods and properties below will be copied subsequently to XPathSelector (monkey patching). @staticmethod is necessary for this, as a workaround, and its use is only technical, all the methods below are non-static actually. """ nodes = xpath = XPathSelector.select if OLD_SCRAPY else Selector.xpath # nodes() and xpath() will be aliases for select/xpath() # html = __unicode__ = XPathSelector.extract @staticmethod def extract(self): return HTML(_XPathSelector_extract(self)) html = __unicode__ = extract @staticmethod def css1(self, css, none = False): "Similar to css() but returns always 1 node rather than a list of nodes. None or XNone if no node has been found" l = self.css(css) if l: return l[0] return None if none else XNone @staticmethod def node(self, xpath = None, css = None, none = False): "Similar to nodes() but returns always 1 node rather than a list of nodes. None or XNone if no node has been found" l = self.css(css) if css != None else self.xpath(xpath) if l: return l[0] return None if none else XNone @staticmethod def text(self, xpath = ".", norm = True): """ Returns all text contained in the 1st node selected by 'xpath', as a list of x-strings (xbasestring) with tags stripped out and entities decoded. Empty string if 'xpath' doesn't select any node. If norm=True, whitespaces are normalized: multiple spaces merged, leading/trailing spaces stripped out. WARNING: doesn't work for an HTML text (untagged) node, use extract() instead. """ xpath = "string(" + xpath + ")" if norm: xpath = "normalize-space(" + xpath + ")" l = self.nodes(xpath) return Plain(l[0].extract() if l else '') @staticmethod def texts(self, xpath, norm = True): """ Returns all texts selected by given 'xpath', as a list of x-strings (xbasestring), with tags stripped out and entities decoded. Empty list if 'xpath' doesn't select any node. If norm=True, whitespaces are normalized: multiple spaces merged, leading/trailing spaces stripped out. WARNING: doesn't work for HTML text (untagged) nodes, use extract() instead. """ nodes = self.nodes(xpath) return [n.text(".", norm) for n in nodes] _path_anchor = "(self::node()[name()='a']|.//a)/@href" _path_class = ".//%s[contains(concat(' ', @class, ' '), ' %s ')]" _path_id = ".//%s[@id='%s']" _path_after = "(.//th|.//td)[contains(.,%s)]/following-sibling::td[1]" _path_after_exact = "(.//th|.//td)[.=%s]/following-sibling::td[1]" @staticmethod def anchor(self, xpath = None, none = False): "Extracts href attribute from self (if <a>) or from the 1st <a> descendant. If 'xpath' can't be found and none=False (default), returns '', else None" node = self.node(xpath) if xpath else self if not node: return None if none else '' return node.text(self._path_anchor) @staticmethod def nodeWithID(self, cls, tag = "*", none=False): return self.node(self._path_id % (tag,cls), none) @staticmethod def nodeOfClass(self, cls, tag = "*", none=False): "Checks for inclusion of 'cls' in the class list, rather than strict equality." return self.node(self._path_class % (tag,cls), none) @staticmethod def nodesOfClass(self, cls, tag = "*"): "Checks for inclusion of 'cls' in the class list, rather than strict equality." return self.nodes(self._path_class % (tag,cls)) @staticmethod def nodeAfter(self, title = None, exact = None, none=False): """Returns first (only 1) <TD> element that follows <TD>...[title]...</TD> or <TH>. If 'title' is None, 'exact' is matched instead, using equality match rather than contains(). Usually used to extract contents of a table cell given title of the row""" if title is not None: return self.node(self._path_after % xpath_escape(title), none) return self.node(self._path_after_exact % xpath_escape(exact), none) @staticmethod def textAfter(self, title = None, exact = None, norm = True): "Like nodeAfter(), but returns text of the node" if title is not None: return self.text(self._path_after % xpath_escape(title), norm) return self.text(self._path_after_exact % xpath_escape(exact), norm) @staticmethod def reText(self, regex, multi = False, norm = True): "Call text() followed by xbasestring.re(regex, multi). Space normalization performed by default." return self.text(norm = norm).re(regex, multi = multi) @staticmethod def reHtml(self, regex, multi = False): "Call html() followed by xbasestring.re(regex, multi)." return self.html().re(regex, multi = multi) @staticmethod def __getitem__(self, path): """For convenient [...] selection of subnodes and attributes: node['subnode'] or node['@attr'] or node['any_XPath']. If the path contains '@' character anywhere, text() is returned, as for an attribute. A node() otherwise.""" if '@' in path: return self.text(path) return self.node(path) # @staticmethod # def html(self): # "'print xnode' will print FULL original html/xml code of the node" # return self.extract() # @staticmethod # def __unicode__(self): # "'print xnode' will print FULL original html/xml code of the node" # return self.extract() @staticmethod def __str__(self): return self.extract().encode('utf-8') # no HTML() wrapper, use only for print out not data storage @staticmethod def __contains__(self, s): "Checks for occurence of a given plain text in the document (tags stripped out). Shorthand for 's in x.text()'." return s in self.text() def monkeyPatch(): # copy methods and properties to XPathSelector (monkey patching): methods = filter(lambda k: not k.startswith('__'), XDoc.__dict__.keys()) # all properties with standard names (no __*__) methods += "__unicode__ __str__ __contains__ __getitem__".split() # additionally these special names for name in methods: method = getattr(XDoc, name) # here, MUST use getattr not __dict__[name] - they give different results!!! <unbound method> vs <function>! setattr(XPathSelector, name, method) # additional patches... def XPathSelectorList_text(self, xpath = ".", norm = True): "Run text() method on all selectors in this list and return as a list of Text strings." return [x.text(xpath, norm) for x in self] def XPathSelectorList_html(self): "Run html() method on all selectors in this list and return as a list of Text strings." return [x.html() for x in self] XPathSelectorList.text = XPathSelectorList_text XPathSelectorList.html = XPathSelectorList_html monkeyPatch() #class XDoc(object): # "Currently just a wrapper for scrapy's HtmlXPathSelector/XmlXPathSelector" # def __init__(self, text, mode = "html"): # "'text' is either raw text (string/unicode), or XPathSelector. 'mode' can be either 'html' or 'xml'" # if isinstance(text, XPathSelector): # self.selector = text # else: # self.selector = xdoc(text) # def select(self, xpath): # return self.selector.select(xpath) # def text(self, xpath='.', norm=True): # return self.selector.text(xpath, norm) # def nodeAfter(self, title): # return self.selector.nodeAfter(title) # def textAfter(self, title, norm=True): # return self.selector.textAfter(title, norm) # def re(self, regex): # return self.selector.re(regex) # def __unicode__(self): # return unicode(self.selector) # def __str__(self): # return str(self.selector) # if False: # just a draft # class XDoc(object): # """XML or HTML document represented as a tree; or a part of it (subtree, node).""" # def __init__(self): # self.items = [] # XString's and XTag's that constitute content (children) of this XDoc # # def text(self): # "Raw text of this XDoc, with all tags stripped and entities decoded" # return "" # # def xml(self, compact = False): # "This XDoc in text form: XMl or HTML, with all tags preserved" # # def html(self): # "Alias for xml()" # return self.xml() # # # class XTag(XDoc): # "XML/HTML element: a tag with XDoc inside" # # def __init__(self): # self.tag = None # [str] name of the tag that encloses entire content of this XDoc # self.attr = [] # list of attributes: (attribute,value) pairs # self.orig_opening = "" # opening tag in its original form, as occured in source text # self.orig_closing = "" # closing --- "" --- # # class XString(XDoc): # "XML/HTML string node (raw text between or inside tags)" # class XComment(XDoc): # "XML/HTML comment node (<!-- ... -->)" """ DRAFT... from lxml import etree html = "<html>ala < a attr='cos' >ma< /a > kota</i> <I><script> shittttt</script> &amp; <!-- <style> css </style> --></html>" root = etree.fromstring(html, etree.HTMLParser()) tree = lxml.html.fromstring(html) tree.text_content for e in tree.iter() : print e.tag # see: http://shallowsky.com/blog/programming/parsing-html-python.html # for using lxml.html # converting Element to DOM: from xml.dom.pulldom import SAX2DOM from lxml.sax import saxify handler = SAX2DOM() saxify(tree, handler) dom = handler.document dom.childNodes[0].childNodes[0].childNodes[0].childNodes >>> [<DOM Text node "'ala ma kot'...">, <DOM Element: i at 0x97c6aac>] dom.toxml() # converting from DOM back to Element, via parsing (watch for appended enclosing <?xml> and <p> tags): tree = lxml.html.fromstring(dom.toxml()) """ if __name__ == "__main__": import doctest print doctest.testmod()
bfirsh/django-old
refs/heads/master
django/conf/locale/it/formats.py
80
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # DATE_FORMAT = 'd F Y' # 25 Ottobre 2006 TIME_FORMAT = 'H:i:s' # 14:30:59 DATETIME_FORMAT = 'l d F Y H:i:s' # Mercoledì 25 Ottobre 2006 14:30:59 YEAR_MONTH_FORMAT = 'F Y' # Ottobre 2006 MONTH_DAY_FORMAT = 'j/F' # 10/2006 SHORT_DATE_FORMAT = 'd/M/Y' # 25/12/2009 SHORT_DATETIME_FORMAT = 'd/M/Y H:i:s' # 25/10/2009 14:30:59 FIRST_DAY_OF_WEEK = 1 # Lunedì DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%Y/%m/%d', # '2008-10-25', '2008/10/25' '%d-%m-%Y', '%d/%m/%Y', # '25-10-2006', '25/10/2006' '%d-%m-%y', '%d/%m/%y', # '25-10-06', '25/10/06' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%d-%m-%Y %H:%M:%S', # '25-10-2006 14:30:59' '%d-%m-%Y %H:%M', # '25-10-2006 14:30' '%d-%m-%Y', # '25-10-2006' '%d-%m-%y %H:%M:%S', # '25-10-06 14:30:59' '%d-%m-%y %H:%M', # '25-10-06 14:30' '%d-%m-%y', # '25-10-06' '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%d/%m/%y', # '25/10/06' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
rupakc/Kaggle-Compendium
refs/heads/master
Photo Quality Prediction/photo-baseline.py
1
import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import ExtraTreesClassifier from sklearn.neural_network import MLPClassifier from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import BernoulliNB from sklearn.naive_bayes import MultinomialNB from sklearn import metrics from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import Imputer from sklearn.model_selection import train_test_split import numpy as np import operator import hashfeatures def get_naive_bayes_models(): gnb = GaussianNB() mnb = MultinomialNB() bnb = BernoulliNB() classifier_list = [gnb,mnb,bnb] classifier_name_list = ['Gaussian NB','Multinomial NB','Bernoulli NB'] return classifier_list,classifier_name_list def get_neural_network(hidden_layer_size=50): mlp = MLPClassifier(hidden_layer_sizes=hidden_layer_size) return [mlp], ['MultiLayer Perceptron'] def get_ensemble_models(): rf = RandomForestClassifier(n_estimators=51,min_samples_leaf=5,min_samples_split=3) bagg = BaggingClassifier(n_estimators=71,random_state=42) extra = ExtraTreesClassifier(n_estimators=57,random_state=42) ada = AdaBoostClassifier(n_estimators=51,random_state=42) grad = GradientBoostingClassifier(n_estimators=101,random_state=42) classifier_list = [rf,bagg,extra,ada,grad] classifier_name_list = ['Random Forests','Bagging','Extra Trees','AdaBoost','Gradient Boost'] return classifier_list,classifier_name_list def print_evaluation_metrics(trained_model,trained_model_name,X_test,y_test): print '--------- For Model : ', trained_model_name, ' ----------------' predicted_values = trained_model.predict(X_test) print metrics.classification_report(y_test,predicted_values) print "Accuracy Score : ",metrics.accuracy_score(y_test,predicted_values) print "---------------------------------------\n" def get_word_count(list_of_words): count_dict = dict({}) for word in list_of_words: if word in count_dict.keys(): count_dict[word] += 1 else: count_dict[word] = 1 return count_dict def get_word_list_from_string(string_list): total_word_list = list([]) for number_string in string_list: if number_string is not np.nan: count_list = number_string.split() total_word_list.extend(count_list) return total_word_list def get_top_n_dict_keys(dictionary,top_n=1): sorted_x = sorted(dictionary.items(), key=operator.itemgetter(1), reverse=True) sorted_x = sorted_x[:top_n] key_list = list([]) for sort_value in sorted_x: key_list.append(sort_value[0]) return key_list def fill_nan_in_string(dataframe): for column in dataframe.columns: string_list = dataframe[column].values total_word_list = get_word_list_from_string(string_list) word_dict = get_word_count(total_word_list) top_keys = get_top_n_dict_keys(word_dict,top_n=7) top_key_string = " ".join(top_keys) dataframe[column] = map(lambda x:top_key_string if x is np.nan else x,dataframe[column].values) return dataframe filename = 'training.csv' train_frame = pd.read_csv(filename) name_desc_cap_frame = train_frame[['name','description','caption']] target_class_labels = train_frame['good'].values train_frame.drop(['name','description','caption','good'],axis=1,inplace=True) name_desc_cap_frame = fill_nan_in_string(name_desc_cap_frame) name_features = hashfeatures.FeatureHash(max_feature_num=100).get_feature_set(name_desc_cap_frame['name'].values) desc_features = hashfeatures.FeatureHash(max_feature_num=500).get_feature_set(name_desc_cap_frame['description'].values) caption_features = hashfeatures.FeatureHash(max_feature_num=200).get_feature_set(name_desc_cap_frame['caption'].values) train_features = Imputer().fit_transform(train_frame.values) final_features = np.hstack((name_features,desc_features,caption_features,train_features)) X_train,X_test,y_train,y_test = train_test_split(final_features,target_class_labels,test_size=0.1,random_state=42) classifer_list, classifier_name_list = get_ensemble_models() for classifier,classifier_name in zip(classifer_list,classifier_name_list): classifier.fit(X_train,y_train) print_evaluation_metrics(classifier,classifier_name,X_test,y_test)
mrquim/repository.mrquim
refs/heads/master
repo/script.module.covenant/lib/resources/lib/modules/trakt.py
6
# -*- coding: utf-8 -*- """ Covenant Add-on This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import json import re import time import urllib import urlparse from resources.lib.modules import cache from resources.lib.modules import cleandate from resources.lib.modules import client from resources.lib.modules import control from resources.lib.modules import log_utils from resources.lib.modules import utils BASE_URL = 'http://api.trakt.tv' V2_API_KEY = 'acc97918ace2b0a211957d574e7cd7c7bc7a59b9c949df625077f1d5fb107082' CLIENT_SECRET = '0f3e0b9096477ee0d373d1d354700449bf0fa648bef33c191db5845b346f16ef' REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob' def __getTrakt(url, post=None): try: url = urlparse.urljoin(BASE_URL, url) post = json.dumps(post) if post else None headers = {'Content-Type': 'application/json', 'trakt-api-key': V2_API_KEY, 'trakt-api-version': 2} if getTraktCredentialsInfo(): headers.update({'Authorization': 'Bearer %s' % control.setting('trakt.token')}) result = client.request(url, post=post, headers=headers, output='extended', error=True) resp_code = result[1] resp_header = result[2] result = result[0] if resp_code in ['500', '502', '503', '504', '520', '521', '522', '524']: log_utils.log('Temporary Trakt Error: %s' % resp_code, log_utils.LOGWARNING) return elif resp_code in ['404']: log_utils.log('Object Not Found : %s' % resp_code, log_utils.LOGWARNING) return elif resp_code in ['429']: log_utils.log('Trakt Rate Limit Reached: %s' % resp_code, log_utils.LOGWARNING) return if resp_code not in ['401', '405']: return result, resp_header oauth = urlparse.urljoin(BASE_URL, '/oauth/token') opost = {'client_id': V2_API_KEY, 'client_secret': CLIENT_SECRET, 'redirect_uri': REDIRECT_URI, 'grant_type': 'refresh_token', 'refresh_token': control.setting('trakt.refresh')} result = client.request(oauth, post=json.dumps(opost), headers=headers) result = utils.json_loads_as_str(result) token, refresh = result['access_token'], result['refresh_token'] control.setSetting(id='trakt.token', value=token) control.setSetting(id='trakt.refresh', value=refresh) headers['Authorization'] = 'Bearer %s' % token result = client.request(url, post=post, headers=headers, output='extended', error=True) return result[0], result[2] except Exception as e: log_utils.log('Unknown Trakt Error: %s' % e, log_utils.LOGWARNING) pass def getTraktAsJson(url, post=None): try: r, res_headers = __getTrakt(url, post) r = utils.json_loads_as_str(r) if 'X-Sort-By' in res_headers and 'X-Sort-How' in res_headers: r = sort_list(res_headers['X-Sort-By'], res_headers['X-Sort-How'], r) return r except: pass def authTrakt(): try: if getTraktCredentialsInfo() == True: if control.yesnoDialog(control.lang(32511).encode('utf-8'), control.lang(32512).encode('utf-8'), '', 'Trakt'): control.setSetting(id='trakt.user', value='') control.setSetting(id='trakt.token', value='') control.setSetting(id='trakt.refresh', value='') raise Exception() result = getTraktAsJson('/oauth/device/code', {'client_id': V2_API_KEY}) verification_url = (control.lang(32513) % result['verification_url']).encode('utf-8') user_code = (control.lang(32514) % result['user_code']).encode('utf-8') expires_in = int(result['expires_in']) device_code = result['device_code'] interval = result['interval'] progressDialog = control.progressDialog progressDialog.create('Trakt', verification_url, user_code) for i in range(0, expires_in): try: if progressDialog.iscanceled(): break time.sleep(1) if not float(i) % interval == 0: raise Exception() r = getTraktAsJson('/oauth/device/token', {'client_id': V2_API_KEY, 'client_secret': CLIENT_SECRET, 'code': device_code}) if 'access_token' in r: break except: pass try: progressDialog.close() except: pass token, refresh = r['access_token'], r['refresh_token'] headers = {'Content-Type': 'application/json', 'trakt-api-key': V2_API_KEY, 'trakt-api-version': 2, 'Authorization': 'Bearer %s' % token} result = client.request(urlparse.urljoin(BASE_URL, '/users/me'), headers=headers) result = utils.json_loads_as_str(result) user = result['username'] control.setSetting(id='trakt.user', value=user) control.setSetting(id='trakt.token', value=token) control.setSetting(id='trakt.refresh', value=refresh) raise Exception() except: control.openSettings('3.1') def getTraktCredentialsInfo(): user = control.setting('trakt.user').strip() token = control.setting('trakt.token') refresh = control.setting('trakt.refresh') if (user == '' or token == '' or refresh == ''): return False return True def getTraktIndicatorsInfo(): indicators = control.setting('indicators') if getTraktCredentialsInfo() == False else control.setting('indicators.alt') indicators = True if indicators == '1' else False return indicators def getTraktAddonMovieInfo(): try: scrobble = control.addon('script.trakt').getSetting('scrobble_movie') except: scrobble = '' try: ExcludeHTTP = control.addon('script.trakt').getSetting('ExcludeHTTP') except: ExcludeHTTP = '' try: authorization = control.addon('script.trakt').getSetting('authorization') except: authorization = '' if scrobble == 'true' and ExcludeHTTP == 'false' and not authorization == '': return True else: return False def getTraktAddonEpisodeInfo(): try: scrobble = control.addon('script.trakt').getSetting('scrobble_episode') except: scrobble = '' try: ExcludeHTTP = control.addon('script.trakt').getSetting('ExcludeHTTP') except: ExcludeHTTP = '' try: authorization = control.addon('script.trakt').getSetting('authorization') except: authorization = '' if scrobble == 'true' and ExcludeHTTP == 'false' and not authorization == '': return True else: return False def manager(name, imdb, tvdb, content): try: post = {"movies": [{"ids": {"imdb": imdb}}]} if content == 'movie' else {"shows": [{"ids": {"tvdb": tvdb}}]} items = [(control.lang(32516).encode('utf-8'), '/sync/collection')] items += [(control.lang(32517).encode('utf-8'), '/sync/collection/remove')] items += [(control.lang(32518).encode('utf-8'), '/sync/watchlist')] items += [(control.lang(32519).encode('utf-8'), '/sync/watchlist/remove')] items += [(control.lang(32520).encode('utf-8'), '/users/me/lists/%s/items')] result = getTraktAsJson('/users/me/lists') lists = [(i['name'], i['ids']['slug']) for i in result] lists = [lists[i//2] for i in range(len(lists)*2)] for i in range(0, len(lists), 2): lists[i] = ((control.lang(32521) % lists[i][0]).encode('utf-8'), '/users/me/lists/%s/items' % lists[i][1]) for i in range(1, len(lists), 2): lists[i] = ((control.lang(32522) % lists[i][0]).encode('utf-8'), '/users/me/lists/%s/items/remove' % lists[i][1]) items += lists select = control.selectDialog([i[0] for i in items], control.lang(32515).encode('utf-8')) if select == -1: return elif select == 4: t = control.lang(32520).encode('utf-8') k = control.keyboard('', t) ; k.doModal() new = k.getText() if k.isConfirmed() else None if (new == None or new == ''): return result = __getTrakt('/users/me/lists', post={"name": new, "privacy": "private"})[0] try: slug = utils.json_loads_as_str(result)['ids']['slug'] except: return control.infoDialog(control.lang(32515).encode('utf-8'), heading=str(name), sound=True, icon='ERROR') result = __getTrakt(items[select][1] % slug, post=post)[0] else: result = __getTrakt(items[select][1], post=post)[0] icon = control.infoLabel('ListItem.Icon') if not result == None else 'ERROR' control.infoDialog(control.lang(32515).encode('utf-8'), heading=str(name), sound=True, icon=icon) except: return def slug(name): name = name.strip() name = name.lower() name = re.sub('[^a-z0-9_]', '-', name) name = re.sub('--+', '-', name) return name def sort_list(sort_key, sort_direction, list_data): reverse = False if sort_direction == 'asc' else True if sort_key == 'rank': return sorted(list_data, key=lambda x: x['rank'], reverse=reverse) elif sort_key == 'added': return sorted(list_data, key=lambda x: x['listed_at'], reverse=reverse) elif sort_key == 'title': return sorted(list_data, key=lambda x: utils.title_key(x[x['type']].get('title')), reverse=reverse) elif sort_key == 'released': return sorted(list_data, key=lambda x: _released_key(x[x['type']]), reverse=reverse) elif sort_key == 'runtime': return sorted(list_data, key=lambda x: x[x['type']].get('runtime', 0), reverse=reverse) elif sort_key == 'popularity': return sorted(list_data, key=lambda x: x[x['type']].get('votes', 0), reverse=reverse) elif sort_key == 'percentage': return sorted(list_data, key=lambda x: x[x['type']].get('rating', 0), reverse=reverse) elif sort_key == 'votes': return sorted(list_data, key=lambda x: x[x['type']].get('votes', 0), reverse=reverse) else: return list_data def _released_key(item): if 'released' in item: return item['released'] elif 'first_aired' in item: return item['first_aired'] else: return 0 def getActivity(): try: i = getTraktAsJson('/sync/last_activities') activity = [] activity.append(i['movies']['collected_at']) activity.append(i['episodes']['collected_at']) activity.append(i['movies']['watchlisted_at']) activity.append(i['shows']['watchlisted_at']) activity.append(i['seasons']['watchlisted_at']) activity.append(i['episodes']['watchlisted_at']) activity.append(i['lists']['updated_at']) activity.append(i['lists']['liked_at']) activity = [int(cleandate.iso_2_utc(i)) for i in activity] activity = sorted(activity, key=int)[-1] return activity except: pass def getWatchedActivity(): try: i = getTraktAsJson('/sync/last_activities') activity = [] activity.append(i['movies']['watched_at']) activity.append(i['episodes']['watched_at']) activity = [int(cleandate.iso_2_utc(i)) for i in activity] activity = sorted(activity, key=int)[-1] return activity except: pass def cachesyncMovies(timeout=0): indicators = cache.get(syncMovies, timeout, control.setting('trakt.user').strip()) return indicators def timeoutsyncMovies(): timeout = cache.timeout(syncMovies, control.setting('trakt.user').strip()) return timeout def syncMovies(user): try: if getTraktCredentialsInfo() == False: return indicators = getTraktAsJson('/users/me/watched/movies') indicators = [i['movie']['ids'] for i in indicators] indicators = [str(i['imdb']) for i in indicators if 'imdb' in i] return indicators except: pass def cachesyncTVShows(timeout=0): indicators = cache.get(syncTVShows, timeout, control.setting('trakt.user').strip()) return indicators def timeoutsyncTVShows(): timeout = cache.timeout(syncTVShows, control.setting('trakt.user').strip()) return timeout def syncTVShows(user): try: if getTraktCredentialsInfo() == False: return indicators = getTraktAsJson('/users/me/watched/shows?extended=full') indicators = [(i['show']['ids']['tvdb'], i['show']['aired_episodes'], sum([[(s['number'], e['number']) for e in s['episodes']] for s in i['seasons']], [])) for i in indicators] indicators = [(str(i[0]), int(i[1]), i[2]) for i in indicators] return indicators except: pass def syncSeason(imdb): try: if getTraktCredentialsInfo() == False: return indicators = getTraktAsJson('/shows/%s/progress/watched?specials=false&hidden=false' % imdb) indicators = indicators['seasons'] indicators = [(i['number'], [x['completed'] for x in i['episodes']]) for i in indicators] indicators = ['%01d' % int(i[0]) for i in indicators if not False in i[1]] return indicators except: pass def markMovieAsWatched(imdb): if not imdb.startswith('tt'): imdb = 'tt' + imdb return __getTrakt('/sync/history', {"movies": [{"ids": {"imdb": imdb}}]})[0] def markMovieAsNotWatched(imdb): if not imdb.startswith('tt'): imdb = 'tt' + imdb return __getTrakt('/sync/history/remove', {"movies": [{"ids": {"imdb": imdb}}]})[0] def markTVShowAsWatched(tvdb): return __getTrakt('/sync/history', {"shows": [{"ids": {"tvdb": tvdb}}]})[0] def markTVShowAsNotWatched(tvdb): return __getTrakt('/sync/history/remove', {"shows": [{"ids": {"tvdb": tvdb}}]})[0] def markEpisodeAsWatched(tvdb, season, episode): season, episode = int('%01d' % int(season)), int('%01d' % int(episode)) return __getTrakt('/sync/history', {"shows": [{"seasons": [{"episodes": [{"number": episode}], "number": season}], "ids": {"tvdb": tvdb}}]})[0] def markEpisodeAsNotWatched(tvdb, season, episode): season, episode = int('%01d' % int(season)), int('%01d' % int(episode)) return __getTrakt('/sync/history/remove', {"shows": [{"seasons": [{"episodes": [{"number": episode}], "number": season}], "ids": {"tvdb": tvdb}}]})[0] def getMovieTranslation(id, lang, full=False): url = '/movies/%s/translations/%s' % (id, lang) try: item = getTraktAsJson(url)[0] return item if full else item.get('title') except: pass def getTVShowTranslation(id, lang, season=None, episode=None, full=False): if season and episode: url = '/shows/%s/seasons/%s/episodes/%s/translations/%s' % (id, season, episode, lang) else: url = '/shows/%s/translations/%s' % (id, lang) try: item = getTraktAsJson(url)[0] return item if full else item.get('title') except: pass def getMovieAliases(id): try: return getTraktAsJson('/movies/%s/aliases' % id) except: return [] def getTVShowAliases(id): try: return getTraktAsJson('/shows/%s/aliases' % id) except: return [] def getMovieSummary(id, full=True): try: url = '/movies/%s' % id if full: url += '?extended=full' return getTraktAsJson(url) except: return def getTVShowSummary(id, full=True): try: url = '/shows/%s' % id if full: url += '?extended=full' return getTraktAsJson(url) except: return def getPeople(id, content_type, full=True): try: url = '/%s/%s/people' % (content_type, id) if full: url += '?extended=full' return getTraktAsJson(url) except: return def SearchAll(title, year, full=True): try: return SearchMovie(title, year, full) + SearchTVShow(title, year, full) except: return def SearchMovie(title, year, full=True): try: url = '/search/movie?query=%s' % urllib.quote_plus(title) if year: url += '&year=%s' % year if full: url += '&extended=full' return getTraktAsJson(url) except: return def SearchTVShow(title, year, full=True): try: url = '/search/show?query=%s' % urllib.quote_plus(title) if year: url += '&year=%s' % year if full: url += '&extended=full' return getTraktAsJson(url) except: return def IdLookup(content, type, type_id): try: r = getTraktAsJson('/search/%s/%s?type=%s' % (type, type_id, content)) return r[0].get(content, {}).get('ids', []) except: return {} def getGenre(content, type, type_id): try: r = '/search/%s/%s?type=%s&extended=full' % (type, type_id, content) r = getTraktAsJson(r) r = r[0].get(content, {}).get('genres', []) return r except: return []
craigulmer/gut-buster
refs/heads/master
squareplot.py
1
# Simple plotter for Gut books. # All this does is draw a sqare for every stat in the input # and color it based on the score. # # Another fine example of how Viz lies to you. You will # need to fudge the range by adjusting the clipping. import numpy as np import matplotlib.pyplot as plt import sys as sys if len(sys.argv) <2: print "Need an input file with many rows of 'id score'\n" sys.exit(1) fname = sys.argv[1] vals = np.loadtxt(fname) ids = vals[:,0] score = vals[:,1] score_max = 400; #max(score) #score_max = max(score) score = np.clip(score, 10, score_max) score = score/score_max # want 3x1 ratio, so 3n*n= 30824 (max entries), horiz=3n=300 NUM_COLS=300 fig = plt.figure(figsize=(12,9)) ax = fig.add_subplot(111) ax.set_axis_bgcolor('0.50') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) for i in range(len(vals)): #print i, ids[i] row = int(ids[i]) / NUM_COLS col = int(ids[i]) % NUM_COLS cval = score[i] #score[i]*score[i] # Square the values to drop the lower end cmap = plt.get_cmap('hot') val = cmap(cval) ax.add_patch(plt.Rectangle((col,row),1,1,color=val)); #, cmap=plt.cm.autumn)) ax.set_aspect('equal') print cmap(0.1) print cmap(0.9) plt.xlim([0,NUM_COLS]) plt.ylim([0,1+int(max(ids))/NUM_COLS]) plt.show()