code
stringlengths
3
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.05M
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2016, Adrian Sampson. # # 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. """This module provides the default commands for beets' command-line interface. """ from __future__ import division, absolute_import, print_function import os import re from platform import python_version from collections import namedtuple, Counter from itertools import chain import beets from beets import ui from beets.ui import print_, input_, decargs, show_path_changes from beets import autotag from beets.autotag import Recommendation from beets.autotag import hooks from beets import plugins from beets import importer from beets import util from beets.util import syspath, normpath, ancestry, displayable_path from beets import library from beets import config from beets import logging from beets.util.confit import _package_path import six VARIOUS_ARTISTS = u'Various Artists' PromptChoice = namedtuple('PromptChoice', ['short', 'long', 'callback']) # Global logger. log = logging.getLogger('beets') # The list of default subcommands. This is populated with Subcommand # objects that can be fed to a SubcommandsOptionParser. default_commands = [] # Utilities. def _do_query(lib, query, album, also_items=True): """For commands that operate on matched items, performs a query and returns a list of matching items and a list of matching albums. (The latter is only nonempty when album is True.) Raises a UserError if no items match. also_items controls whether, when fetching albums, the associated items should be fetched also. """ if album: albums = list(lib.albums(query)) items = [] if also_items: for al in albums: items += al.items() else: albums = [] items = list(lib.items(query)) if album and not albums: raise ui.UserError(u'No matching albums found.') elif not album and not items: raise ui.UserError(u'No matching items found.') return items, albums # fields: Shows a list of available fields for queries and format strings. def _print_keys(query): """Given a SQLite query result, print the `key` field of each returned row, with indentation of 2 spaces. """ for row in query: print_(u' ' * 2 + row['key']) def fields_func(lib, opts, args): def _print_rows(names): names.sort() print_(u' ' + u'\n '.join(names)) print_(u"Item fields:") _print_rows(library.Item.all_keys()) print_(u"Album fields:") _print_rows(library.Album.all_keys()) with lib.transaction() as tx: # The SQL uses the DISTINCT to get unique values from the query unique_fields = 'SELECT DISTINCT key FROM (%s)' print_(u"Item flexible attributes:") _print_keys(tx.query(unique_fields % library.Item._flex_table)) print_(u"Album flexible attributes:") _print_keys(tx.query(unique_fields % library.Album._flex_table)) fields_cmd = ui.Subcommand( 'fields', help=u'show fields available for queries and format strings' ) fields_cmd.func = fields_func default_commands.append(fields_cmd) # help: Print help text for commands class HelpCommand(ui.Subcommand): def __init__(self): super(HelpCommand, self).__init__( 'help', aliases=('?',), help=u'give detailed help on a specific sub-command', ) def func(self, lib, opts, args): if args: cmdname = args[0] helpcommand = self.root_parser._subcommand_for_name(cmdname) if not helpcommand: raise ui.UserError(u"unknown command '{0}'".format(cmdname)) helpcommand.print_help() else: self.root_parser.print_help() default_commands.append(HelpCommand()) # import: Autotagger and importer. # Importer utilities and support. def disambig_string(info): """Generate a string for an AlbumInfo or TrackInfo object that provides context that helps disambiguate similar-looking albums and tracks. """ disambig = [] if info.data_source and info.data_source != 'MusicBrainz': disambig.append(info.data_source) if isinstance(info, hooks.AlbumInfo): if info.media: if info.mediums and info.mediums > 1: disambig.append(u'{0}x{1}'.format( info.mediums, info.media )) else: disambig.append(info.media) if info.year: disambig.append(six.text_type(info.year)) if info.country: disambig.append(info.country) if info.label: disambig.append(info.label) if info.albumdisambig: disambig.append(info.albumdisambig) if disambig: return u', '.join(disambig) def dist_string(dist): """Formats a distance (a float) as a colorized similarity percentage string. """ out = u'%.1f%%' % ((1 - dist) * 100) if dist <= config['match']['strong_rec_thresh'].as_number(): out = ui.colorize('text_success', out) elif dist <= config['match']['medium_rec_thresh'].as_number(): out = ui.colorize('text_warning', out) else: out = ui.colorize('text_error', out) return out def penalty_string(distance, limit=None): """Returns a colorized string that indicates all the penalties applied to a distance object. """ penalties = [] for key in distance.keys(): key = key.replace('album_', '') key = key.replace('track_', '') key = key.replace('_', ' ') penalties.append(key) if penalties: if limit and len(penalties) > limit: penalties = penalties[:limit] + ['...'] return ui.colorize('text_warning', u'(%s)' % ', '.join(penalties)) def show_change(cur_artist, cur_album, match): """Print out a representation of the changes that will be made if an album's tags are changed according to `match`, which must be an AlbumMatch object. """ def show_album(artist, album): if artist: album_description = u' %s - %s' % (artist, album) elif album: album_description = u' %s' % album else: album_description = u' (unknown album)' print_(album_description) def format_index(track_info): """Return a string representing the track index of the given TrackInfo or Item object. """ if isinstance(track_info, hooks.TrackInfo): index = track_info.index medium_index = track_info.medium_index medium = track_info.medium mediums = match.info.mediums else: index = medium_index = track_info.track medium = track_info.disc mediums = track_info.disctotal if config['per_disc_numbering']: if mediums > 1: return u'{0}-{1}'.format(medium, medium_index) else: return six.text_type(medium_index or index) else: return six.text_type(index) # Identify the album in question. if cur_artist != match.info.artist or \ (cur_album != match.info.album and match.info.album != VARIOUS_ARTISTS): artist_l, artist_r = cur_artist or '', match.info.artist album_l, album_r = cur_album or '', match.info.album if artist_r == VARIOUS_ARTISTS: # Hide artists for VA releases. artist_l, artist_r = u'', u'' artist_l, artist_r = ui.colordiff(artist_l, artist_r) album_l, album_r = ui.colordiff(album_l, album_r) print_(u"Correcting tags from:") show_album(artist_l, album_l) print_(u"To:") show_album(artist_r, album_r) else: print_(u"Tagging:\n {0.artist} - {0.album}".format(match.info)) # Data URL. if match.info.data_url: print_(u'URL:\n %s' % match.info.data_url) # Info line. info = [] # Similarity. info.append(u'(Similarity: %s)' % dist_string(match.distance)) # Penalties. penalties = penalty_string(match.distance) if penalties: info.append(penalties) # Disambiguation. disambig = disambig_string(match.info) if disambig: info.append(ui.colorize('text_highlight_minor', u'(%s)' % disambig)) print_(' '.join(info)) # Tracks. pairs = list(match.mapping.items()) pairs.sort(key=lambda item_and_track_info: item_and_track_info[1].index) # Build up LHS and RHS for track difference display. The `lines` list # contains ``(lhs, rhs, width)`` tuples where `width` is the length (in # characters) of the uncolorized LHS. lines = [] medium = disctitle = None for item, track_info in pairs: # Medium number and title. if medium != track_info.medium or disctitle != track_info.disctitle: media = match.info.media or 'Media' if match.info.mediums > 1 and track_info.disctitle: lhs = u'%s %s: %s' % (media, track_info.medium, track_info.disctitle) elif match.info.mediums > 1: lhs = u'%s %s' % (media, track_info.medium) elif track_info.disctitle: lhs = u'%s: %s' % (media, track_info.disctitle) else: lhs = None if lhs: lines.append((lhs, u'', 0)) medium, disctitle = track_info.medium, track_info.disctitle # Titles. new_title = track_info.title if not item.title.strip(): # If there's no title, we use the filename. cur_title = displayable_path(os.path.basename(item.path)) lhs, rhs = cur_title, new_title else: cur_title = item.title.strip() lhs, rhs = ui.colordiff(cur_title, new_title) lhs_width = len(cur_title) # Track number change. cur_track, new_track = format_index(item), format_index(track_info) if cur_track != new_track: if item.track in (track_info.index, track_info.medium_index): color = 'text_highlight_minor' else: color = 'text_highlight' templ = ui.colorize(color, u' (#{0})') lhs += templ.format(cur_track) rhs += templ.format(new_track) lhs_width += len(cur_track) + 4 # Length change. if item.length and track_info.length and \ abs(item.length - track_info.length) > \ config['ui']['length_diff_thresh'].as_number(): cur_length = ui.human_seconds_short(item.length) new_length = ui.human_seconds_short(track_info.length) templ = ui.colorize('text_highlight', u' ({0})') lhs += templ.format(cur_length) rhs += templ.format(new_length) lhs_width += len(cur_length) + 3 # Penalties. penalties = penalty_string(match.distance.tracks[track_info]) if penalties: rhs += ' %s' % penalties if lhs != rhs: lines.append((u' * %s' % lhs, rhs, lhs_width)) elif config['import']['detail']: lines.append((u' * %s' % lhs, '', lhs_width)) # Print each track in two columns, or across two lines. col_width = (ui.term_width() - len(''.join([' * ', ' -> ']))) // 2 if lines: max_width = max(w for _, _, w in lines) for lhs, rhs, lhs_width in lines: if not rhs: print_(lhs) elif max_width > col_width: print_(u'%s ->\n %s' % (lhs, rhs)) else: pad = max_width - lhs_width print_(u'%s%s -> %s' % (lhs, ' ' * pad, rhs)) # Missing and unmatched tracks. if match.extra_tracks: print_(u'Missing tracks ({0}/{1} - {2:.1%}):'.format( len(match.extra_tracks), len(match.info.tracks), len(match.extra_tracks) / len(match.info.tracks) )) for track_info in match.extra_tracks: line = u' ! %s (#%s)' % (track_info.title, format_index(track_info)) if track_info.length: line += u' (%s)' % ui.human_seconds_short(track_info.length) print_(ui.colorize('text_warning', line)) if match.extra_items: print_(u'Unmatched tracks ({0}):'.format(len(match.extra_items))) for item in match.extra_items: line = u' ! %s (#%s)' % (item.title, format_index(item)) if item.length: line += u' (%s)' % ui.human_seconds_short(item.length) print_(ui.colorize('text_warning', line)) def show_item_change(item, match): """Print out the change that would occur by tagging `item` with the metadata from `match`, a TrackMatch object. """ cur_artist, new_artist = item.artist, match.info.artist cur_title, new_title = item.title, match.info.title if cur_artist != new_artist or cur_title != new_title: cur_artist, new_artist = ui.colordiff(cur_artist, new_artist) cur_title, new_title = ui.colordiff(cur_title, new_title) print_(u"Correcting track tags from:") print_(u" %s - %s" % (cur_artist, cur_title)) print_(u"To:") print_(u" %s - %s" % (new_artist, new_title)) else: print_(u"Tagging track: %s - %s" % (cur_artist, cur_title)) # Data URL. if match.info.data_url: print_(u'URL:\n %s' % match.info.data_url) # Info line. info = [] # Similarity. info.append(u'(Similarity: %s)' % dist_string(match.distance)) # Penalties. penalties = penalty_string(match.distance) if penalties: info.append(penalties) # Disambiguation. disambig = disambig_string(match.info) if disambig: info.append(ui.colorize('text_highlight_minor', u'(%s)' % disambig)) print_(' '.join(info)) def summarize_items(items, singleton): """Produces a brief summary line describing a set of items. Used for manually resolving duplicates during import. `items` is a list of `Item` objects. `singleton` indicates whether this is an album or single-item import (if the latter, them `items` should only have one element). """ summary_parts = [] if not singleton: summary_parts.append(u"{0} items".format(len(items))) format_counts = {} for item in items: format_counts[item.format] = format_counts.get(item.format, 0) + 1 if len(format_counts) == 1: # A single format. summary_parts.append(items[0].format) else: # Enumerate all the formats by decreasing frequencies: for fmt, count in sorted( format_counts.items(), key=lambda fmt_and_count: (-fmt_and_count[1], fmt_and_count[0]) ): summary_parts.append('{0} {1}'.format(fmt, count)) if items: average_bitrate = sum([item.bitrate for item in items]) / len(items) total_duration = sum([item.length for item in items]) total_filesize = sum([item.filesize for item in items]) summary_parts.append(u'{0}kbps'.format(int(average_bitrate / 1000))) summary_parts.append(ui.human_seconds_short(total_duration)) summary_parts.append(ui.human_bytes(total_filesize)) return u', '.join(summary_parts) def _summary_judgment(rec): """Determines whether a decision should be made without even asking the user. This occurs in quiet mode and when an action is chosen for NONE recommendations. Return an action or None if the user should be queried. May also print to the console if a summary judgment is made. """ if config['import']['quiet']: if rec == Recommendation.strong: return importer.action.APPLY else: action = config['import']['quiet_fallback'].as_choice({ 'skip': importer.action.SKIP, 'asis': importer.action.ASIS, }) elif rec == Recommendation.none: action = config['import']['none_rec_action'].as_choice({ 'skip': importer.action.SKIP, 'asis': importer.action.ASIS, 'ask': None, }) else: return None if action == importer.action.SKIP: print_(u'Skipping.') elif action == importer.action.ASIS: print_(u'Importing as-is.') return action def choose_candidate(candidates, singleton, rec, cur_artist=None, cur_album=None, item=None, itemcount=None, choices=[]): """Given a sorted list of candidates, ask the user for a selection of which candidate to use. Applies to both full albums and singletons (tracks). Candidates are either AlbumMatch or TrackMatch objects depending on `singleton`. for albums, `cur_artist`, `cur_album`, and `itemcount` must be provided. For singletons, `item` must be provided. `choices` is a list of `PromptChoice`s to be used in each prompt. Returns one of the following: * the result of the choice, which may be SKIP or ASIS * a candidate (an AlbumMatch/TrackMatch object) * a chosen `PromptChoice` from `choices` """ # Sanity check. if singleton: assert item is not None else: assert cur_artist is not None assert cur_album is not None # Build helper variables for the prompt choices. choice_opts = tuple(c.long for c in choices) choice_actions = {c.short: c for c in choices} # Zero candidates. if not candidates: if singleton: print_(u"No matching recordings found.") else: print_(u"No matching release found for {0} tracks." .format(itemcount)) print_(u'For help, see: ' u'http://beets.readthedocs.org/en/latest/faq.html#nomatch') sel = ui.input_options(choice_opts) if sel in choice_actions: return choice_actions[sel] else: assert False # Is the change good enough? bypass_candidates = False if rec != Recommendation.none: match = candidates[0] bypass_candidates = True while True: # Display and choose from candidates. require = rec <= Recommendation.low if not bypass_candidates: # Display list of candidates. print_(u'Finding tags for {0} "{1} - {2}".'.format( u'track' if singleton else u'album', item.artist if singleton else cur_artist, item.title if singleton else cur_album, )) print_(u'Candidates:') for i, match in enumerate(candidates): # Index, metadata, and distance. line = [ u'{0}.'.format(i + 1), u'{0} - {1}'.format( match.info.artist, match.info.title if singleton else match.info.album, ), u'({0})'.format(dist_string(match.distance)), ] # Penalties. penalties = penalty_string(match.distance, 3) if penalties: line.append(penalties) # Disambiguation disambig = disambig_string(match.info) if disambig: line.append(ui.colorize('text_highlight_minor', u'(%s)' % disambig)) print_(u' '.join(line)) # Ask the user for a choice. sel = ui.input_options(choice_opts, numrange=(1, len(candidates))) if sel == u'm': pass elif sel in choice_actions: return choice_actions[sel] else: # Numerical selection. match = candidates[sel - 1] if sel != 1: # When choosing anything but the first match, # disable the default action. require = True bypass_candidates = False # Show what we're about to do. if singleton: show_item_change(item, match) else: show_change(cur_artist, cur_album, match) # Exact match => tag automatically if we're not in timid mode. if rec == Recommendation.strong and not config['import']['timid']: return match # Ask for confirmation. default = config['import']['default_action'].as_choice({ u'apply': u'a', u'skip': u's', u'asis': u'u', u'none': None, }) if default is None: require = True # Bell ring when user interaction is needed. if config['import']['bell']: ui.print_(u'\a', end=u'') sel = ui.input_options((u'Apply', u'More candidates') + choice_opts, require=require, default=default) if sel == u'a': return match elif sel in choice_actions: return choice_actions[sel] def manual_search(session, task): """Get a new `Proposal` using manual search criteria. Input either an artist and album (for full albums) or artist and track name (for singletons) for manual search. """ artist = input_(u'Artist:').strip() name = input_(u'Album:' if task.is_album else u'Track:').strip() if task.is_album: _, _, prop = autotag.tag_album( task.items, artist, name ) return prop else: return autotag.tag_item(task.item, artist, name) def manual_id(session, task): """Get a new `Proposal` using a manually-entered ID. Input an ID, either for an album ("release") or a track ("recording"). """ prompt = u'Enter {0} ID:'.format(u'release' if task.is_album else u'recording') search_id = input_(prompt).strip() if task.is_album: _, _, prop = autotag.tag_album( task.items, search_ids=search_id.split() ) return prop else: return autotag.tag_item(task.item, search_ids=search_id.split()) def abort_action(session, task): """A prompt choice callback that aborts the importer. """ raise importer.ImportAbort() class TerminalImportSession(importer.ImportSession): """An import session that runs in a terminal. """ def choose_match(self, task): """Given an initial autotagging of items, go through an interactive dance with the user to ask for a choice of metadata. Returns an AlbumMatch object, ASIS, or SKIP. """ # Show what we're tagging. print_() print_(displayable_path(task.paths, u'\n') + u' ({0} items)'.format(len(task.items))) # Take immediate action if appropriate. action = _summary_judgment(task.rec) if action == importer.action.APPLY: match = task.candidates[0] show_change(task.cur_artist, task.cur_album, match) return match elif action is not None: return action # Loop until we have a choice. candidates, rec = task.candidates, task.rec while True: # Ask for a choice from the user. The result of # `choose_candidate` may be an `importer.action`, an # `AlbumMatch` object for a specific selection, or a # `PromptChoice`. choices = self._get_choices(task) choice = choose_candidate( candidates, False, rec, task.cur_artist, task.cur_album, itemcount=len(task.items), choices=choices ) # Basic choices that require no more action here. if choice in (importer.action.SKIP, importer.action.ASIS): # Pass selection to main control flow. return choice # Plugin-provided choices. We invoke the associated callback # function. elif choice in choices: post_choice = choice.callback(self, task) if isinstance(post_choice, importer.action): return post_choice elif isinstance(post_choice, autotag.Proposal): # Use the new candidates and continue around the loop. candidates = post_choice.candidates rec = post_choice.recommendation # Otherwise, we have a specific match selection. else: # We have a candidate! Finish tagging. Here, choice is an # AlbumMatch object. assert isinstance(choice, autotag.AlbumMatch) return choice def choose_item(self, task): """Ask the user for a choice about tagging a single item. Returns either an action constant or a TrackMatch object. """ print_() print_(displayable_path(task.item.path)) candidates, rec = task.candidates, task.rec # Take immediate action if appropriate. action = _summary_judgment(task.rec) if action == importer.action.APPLY: match = candidates[0] show_item_change(task.item, match) return match elif action is not None: return action while True: # Ask for a choice. choices = self._get_choices(task) choice = choose_candidate(candidates, True, rec, item=task.item, choices=choices) if choice in (importer.action.SKIP, importer.action.ASIS): return choice elif choice in choices: post_choice = choice.callback(self, task) if isinstance(post_choice, importer.action): return post_choice elif isinstance(post_choice, autotag.Proposal): candidates = post_choice.candidates rec = post_choice.recommendation else: # Chose a candidate. assert isinstance(choice, autotag.TrackMatch) return choice def resolve_duplicate(self, task, found_duplicates): """Decide what to do when a new album or item seems similar to one that's already in the library. """ log.warning(u"This {0} is already in the library!", (u"album" if task.is_album else u"item")) if config['import']['quiet']: # In quiet mode, don't prompt -- just skip. log.info(u'Skipping.') sel = u's' else: # Print some detail about the existing and new items so the # user can make an informed decision. for duplicate in found_duplicates: print_(u"Old: " + summarize_items( list(duplicate.items()) if task.is_album else [duplicate], not task.is_album, )) print_(u"New: " + summarize_items( task.imported_items(), not task.is_album, )) sel = ui.input_options( (u'Skip new', u'Keep both', u'Remove old') ) if sel == u's': # Skip new. task.set_choice(importer.action.SKIP) elif sel == u'k': # Keep both. Do nothing; leave the choice intact. pass elif sel == u'r': # Remove old. task.should_remove_duplicates = True else: assert False def should_resume(self, path): return ui.input_yn(u"Import of the directory:\n{0}\n" u"was interrupted. Resume (Y/n)?" .format(displayable_path(path))) def _get_choices(self, task): """Get the list of prompt choices that should be presented to the user. This consists of both built-in choices and ones provided by plugins. The `before_choose_candidate` event is sent to the plugins, with session and task as its parameters. Plugins are responsible for checking the right conditions and returning a list of `PromptChoice`s, which is flattened and checked for conflicts. If two or more choices have the same short letter, a warning is emitted and all but one choices are discarded, giving preference to the default importer choices. Returns a list of `PromptChoice`s. """ # Standard, built-in choices. choices = [ PromptChoice(u's', u'Skip', lambda s, t: importer.action.SKIP), PromptChoice(u'u', u'Use as-is', lambda s, t: importer.action.ASIS) ] if task.is_album: choices += [ PromptChoice(u't', u'as Tracks', lambda s, t: importer.action.TRACKS), PromptChoice(u'g', u'Group albums', lambda s, t: importer.action.ALBUMS), ] choices += [ PromptChoice(u'e', u'Enter search', manual_search), PromptChoice(u'i', u'enter Id', manual_id), PromptChoice(u'b', u'aBort', abort_action), ] # Send the before_choose_candidate event and flatten list. extra_choices = list(chain(*plugins.send('before_choose_candidate', session=self, task=task))) # Add a "dummy" choice for the other baked-in option, for # duplicate checking. all_choices = [ PromptChoice(u'a', u'Apply', None), ] + choices + extra_choices # Check for conflicts. short_letters = [c.short for c in all_choices] if len(short_letters) != len(set(short_letters)): # Duplicate short letter has been found. duplicates = [i for i, count in Counter(short_letters).items() if count > 1] for short in duplicates: # Keep the first of the choices, removing the rest. dup_choices = [c for c in all_choices if c.short == short] for c in dup_choices[1:]: log.warning(u"Prompt choice '{0}' removed due to conflict " u"with '{1}' (short letter: '{2}')", c.long, dup_choices[0].long, c.short) extra_choices.remove(c) return choices + extra_choices # The import command. def import_files(lib, paths, query): """Import the files in the given list of paths or matching the query. """ # Check the user-specified directories. for path in paths: if not os.path.exists(syspath(normpath(path))): raise ui.UserError(u'no such file or directory: {0}'.format( displayable_path(path))) # Check parameter consistency. if config['import']['quiet'] and config['import']['timid']: raise ui.UserError(u"can't be both quiet and timid") # Open the log. if config['import']['log'].get() is not None: logpath = syspath(config['import']['log'].as_filename()) try: loghandler = logging.FileHandler(logpath) except IOError: raise ui.UserError(u"could not open log file for writing: " u"{0}".format(displayable_path(logpath))) else: loghandler = None # Never ask for input in quiet mode. if config['import']['resume'].get() == 'ask' and \ config['import']['quiet']: config['import']['resume'] = False session = TerminalImportSession(lib, loghandler, paths, query) session.run() # Emit event. plugins.send('import', lib=lib, paths=paths) def import_func(lib, opts, args): config['import'].set_args(opts) # Special case: --copy flag suppresses import_move (which would # otherwise take precedence). if opts.copy: config['import']['move'] = False if opts.library: query = decargs(args) paths = [] else: query = None paths = args if not paths: raise ui.UserError(u'no path specified') import_files(lib, paths, query) import_cmd = ui.Subcommand( u'import', help=u'import new music', aliases=(u'imp', u'im') ) import_cmd.parser.add_option( u'-c', u'--copy', action='store_true', default=None, help=u"copy tracks into library directory (default)" ) import_cmd.parser.add_option( u'-C', u'--nocopy', action='store_false', dest='copy', help=u"don't copy tracks (opposite of -c)" ) import_cmd.parser.add_option( u'-m', u'--move', action='store_true', dest='move', help=u"move tracks into the library (overrides -c)" ) import_cmd.parser.add_option( u'-w', u'--write', action='store_true', default=None, help=u"write new metadata to files' tags (default)" ) import_cmd.parser.add_option( u'-W', u'--nowrite', action='store_false', dest='write', help=u"don't write metadata (opposite of -w)" ) import_cmd.parser.add_option( u'-a', u'--autotag', action='store_true', dest='autotag', help=u"infer tags for imported files (default)" ) import_cmd.parser.add_option( u'-A', u'--noautotag', action='store_false', dest='autotag', help=u"don't infer tags for imported files (opposite of -a)" ) import_cmd.parser.add_option( u'-p', u'--resume', action='store_true', default=None, help=u"resume importing if interrupted" ) import_cmd.parser.add_option( u'-P', u'--noresume', action='store_false', dest='resume', help=u"do not try to resume importing" ) import_cmd.parser.add_option( u'-q', u'--quiet', action='store_true', dest='quiet', help=u"never prompt for input: skip albums instead" ) import_cmd.parser.add_option( u'-l', u'--log', dest='log', help=u'file to log untaggable albums for later review' ) import_cmd.parser.add_option( u'-s', u'--singletons', action='store_true', help=u'import individual tracks instead of full albums' ) import_cmd.parser.add_option( u'-t', u'--timid', dest='timid', action='store_true', help=u'always confirm all actions' ) import_cmd.parser.add_option( u'-L', u'--library', dest='library', action='store_true', help=u'retag items matching a query' ) import_cmd.parser.add_option( u'-i', u'--incremental', dest='incremental', action='store_true', help=u'skip already-imported directories' ) import_cmd.parser.add_option( u'-I', u'--noincremental', dest='incremental', action='store_false', help=u'do not skip already-imported directories' ) import_cmd.parser.add_option( u'--flat', dest='flat', action='store_true', help=u'import an entire tree as a single album' ) import_cmd.parser.add_option( u'-g', u'--group-albums', dest='group_albums', action='store_true', help=u'group tracks in a folder into separate albums' ) import_cmd.parser.add_option( u'--pretend', dest='pretend', action='store_true', help=u'just print the files to import' ) import_cmd.parser.add_option( u'-S', u'--search-id', dest='search_ids', action='append', metavar='ID', help=u'restrict matching to a specific metadata backend ID' ) import_cmd.func = import_func default_commands.append(import_cmd) # list: Query and show library contents. def list_items(lib, query, album, fmt=u''): """Print out items in lib matching query. If album, then search for albums instead of single items. """ if album: for album in lib.albums(query): ui.print_(format(album, fmt)) else: for item in lib.items(query): ui.print_(format(item, fmt)) def list_func(lib, opts, args): list_items(lib, decargs(args), opts.album) list_cmd = ui.Subcommand(u'list', help=u'query the library', aliases=(u'ls',)) list_cmd.parser.usage += u"\n" \ u'Example: %prog -f \'$album: $title\' artist:beatles' list_cmd.parser.add_all_common_options() list_cmd.func = list_func default_commands.append(list_cmd) # update: Update library contents according to on-disk tags. def update_items(lib, query, album, move, pretend, fields): """For all the items matched by the query, update the library to reflect the item's embedded tags. :param fields: The fields to be stored. If not specified, all fields will be. """ with lib.transaction(): if move and fields is not None and 'path' not in fields: # Special case: if an item needs to be moved, the path field has to # updated; otherwise the new path will not be reflected in the # database. fields.append('path') items, _ = _do_query(lib, query, album) # Walk through the items and pick up their changes. affected_albums = set() for item in items: # Item deleted? if not os.path.exists(syspath(item.path)): ui.print_(format(item)) ui.print_(ui.colorize('text_error', u' deleted')) if not pretend: item.remove(True) affected_albums.add(item.album_id) continue # Did the item change since last checked? if item.current_mtime() <= item.mtime: log.debug(u'skipping {0} because mtime is up to date ({1})', displayable_path(item.path), item.mtime) continue # Read new data. try: item.read() except library.ReadError as exc: log.error(u'error reading {0}: {1}', displayable_path(item.path), exc) continue # Special-case album artist when it matches track artist. (Hacky # but necessary for preserving album-level metadata for non- # autotagged imports.) if not item.albumartist: old_item = lib.get_item(item.id) if old_item.albumartist == old_item.artist == item.artist: item.albumartist = old_item.albumartist item._dirty.discard(u'albumartist') # Check for and display changes. changed = ui.show_model_changes( item, fields=fields or library.Item._media_fields) # Save changes. if not pretend: if changed: # Move the item if it's in the library. if move and lib.directory in ancestry(item.path): item.move(store=False) item.store(fields=fields) affected_albums.add(item.album_id) else: # The file's mtime was different, but there were no # changes to the metadata. Store the new mtime, # which is set in the call to read(), so we don't # check this again in the future. item.store(fields=fields) # Skip album changes while pretending. if pretend: return # Modify affected albums to reflect changes in their items. for album_id in affected_albums: if album_id is None: # Singletons. continue album = lib.get_album(album_id) if not album: # Empty albums have already been removed. log.debug(u'emptied album {0}', album_id) continue first_item = album.items().get() # Update album structure to reflect an item in it. for key in library.Album.item_keys: album[key] = first_item[key] album.store(fields=fields) # Move album art (and any inconsistent items). if move and lib.directory in ancestry(first_item.path): log.debug(u'moving album {0}', album_id) # Manually moving and storing the album. items = list(album.items()) for item in items: item.move(store=False) item.store(fields=fields) album.move(store=False) album.store(fields=fields) def update_func(lib, opts, args): update_items(lib, decargs(args), opts.album, ui.should_move(opts.move), opts.pretend, opts.fields) update_cmd = ui.Subcommand( u'update', help=u'update the library', aliases=(u'upd', u'up',) ) update_cmd.parser.add_album_option() update_cmd.parser.add_format_option() update_cmd.parser.add_option( u'-m', u'--move', action='store_true', dest='move', help=u"move files in the library directory" ) update_cmd.parser.add_option( u'-M', u'--nomove', action='store_false', dest='move', help=u"don't move files in library" ) update_cmd.parser.add_option( u'-p', u'--pretend', action='store_true', help=u"show all changes but do nothing" ) update_cmd.parser.add_option( u'-F', u'--field', default=None, action='append', dest='fields', help=u'list of fields to update' ) update_cmd.func = update_func default_commands.append(update_cmd) # remove: Remove items from library, delete files. def remove_items(lib, query, album, delete, force): """Remove items matching query from lib. If album, then match and remove whole albums. If delete, also remove files from disk. """ # Get the matching items. items, albums = _do_query(lib, query, album) # Confirm file removal if not forcing removal. if not force: # Prepare confirmation with user. print_() if delete: fmt = u'$path - $title' prompt = u'Really DELETE %i file%s (y/n)?' % \ (len(items), 's' if len(items) > 1 else '') else: fmt = u'' prompt = u'Really remove %i item%s from the library (y/n)?' % \ (len(items), 's' if len(items) > 1 else '') # Show all the items. for item in items: ui.print_(format(item, fmt)) # Confirm with user. if not ui.input_yn(prompt, True): return # Remove (and possibly delete) items. with lib.transaction(): for obj in (albums if album else items): obj.remove(delete) def remove_func(lib, opts, args): remove_items(lib, decargs(args), opts.album, opts.delete, opts.force) remove_cmd = ui.Subcommand( u'remove', help=u'remove matching items from the library', aliases=(u'rm',) ) remove_cmd.parser.add_option( u"-d", u"--delete", action="store_true", help=u"also remove files from disk" ) remove_cmd.parser.add_option( u"-f", u"--force", action="store_true", help=u"do not ask when removing items" ) remove_cmd.parser.add_album_option() remove_cmd.func = remove_func default_commands.append(remove_cmd) # stats: Show library/query statistics. def show_stats(lib, query, exact): """Shows some statistics about the matched items.""" items = lib.items(query) total_size = 0 total_time = 0.0 total_items = 0 artists = set() albums = set() album_artists = set() for item in items: if exact: try: total_size += os.path.getsize(syspath(item.path)) except OSError as exc: log.info(u'could not get size of {}: {}', item.path, exc) else: total_size += int(item.length * item.bitrate / 8) total_time += item.length total_items += 1 artists.add(item.artist) album_artists.add(item.albumartist) if item.album_id: albums.add(item.album_id) size_str = u'' + ui.human_bytes(total_size) if exact: size_str += u' ({0} bytes)'.format(total_size) print_(u"""Tracks: {0} Total time: {1}{2} {3}: {4} Artists: {5} Albums: {6} Album artists: {7}""".format( total_items, ui.human_seconds(total_time), u' ({0:.2f} seconds)'.format(total_time) if exact else '', u'Total size' if exact else u'Approximate total size', size_str, len(artists), len(albums), len(album_artists)), ) def stats_func(lib, opts, args): show_stats(lib, decargs(args), opts.exact) stats_cmd = ui.Subcommand( u'stats', help=u'show statistics about the library or a query' ) stats_cmd.parser.add_option( u'-e', u'--exact', action='store_true', help=u'exact size and time' ) stats_cmd.func = stats_func default_commands.append(stats_cmd) # version: Show current beets version. def show_version(lib, opts, args): print_(u'beets version %s' % beets.__version__) print_(u'Python version {}'.format(python_version())) # Show plugins. names = sorted(p.name for p in plugins.find_plugins()) if names: print_(u'plugins:', ', '.join(names)) else: print_(u'no plugins loaded') version_cmd = ui.Subcommand( u'version', help=u'output version information' ) version_cmd.func = show_version default_commands.append(version_cmd) # modify: Declaratively change metadata. def modify_items(lib, mods, dels, query, write, move, album, confirm): """Modifies matching items according to user-specified assignments and deletions. `mods` is a dictionary of field and value pairse indicating assignments. `dels` is a list of fields to be deleted. """ # Parse key=value specifications into a dictionary. model_cls = library.Album if album else library.Item for key, value in mods.items(): mods[key] = model_cls._parse(key, value) # Get the items to modify. items, albums = _do_query(lib, query, album, False) objs = albums if album else items # Apply changes *temporarily*, preview them, and collect modified # objects. print_(u'Modifying {0} {1}s.' .format(len(objs), u'album' if album else u'item')) changed = set() for obj in objs: if print_and_modify(obj, mods, dels): changed.add(obj) # Still something to do? if not changed: print_(u'No changes to make.') return # Confirm action. if confirm: if write and move: extra = u', move and write tags' elif write: extra = u' and write tags' elif move: extra = u' and move' else: extra = u'' changed = ui.input_select_objects( u'Really modify%s' % extra, changed, lambda o: print_and_modify(o, mods, dels) ) # Apply changes to database and files with lib.transaction(): for obj in changed: obj.try_sync(write, move) def print_and_modify(obj, mods, dels): """Print the modifications to an item and return a bool indicating whether any changes were made. `mods` is a dictionary of fields and values to update on the object; `dels` is a sequence of fields to delete. """ obj.update(mods) for field in dels: try: del obj[field] except KeyError: pass return ui.show_model_changes(obj) def modify_parse_args(args): """Split the arguments for the modify subcommand into query parts, assignments (field=value), and deletions (field!). Returns the result as a three-tuple in that order. """ mods = {} dels = [] query = [] for arg in args: if arg.endswith('!') and '=' not in arg and ':' not in arg: dels.append(arg[:-1]) # Strip trailing !. elif '=' in arg and ':' not in arg.split('=', 1)[0]: key, val = arg.split('=', 1) mods[key] = val else: query.append(arg) return query, mods, dels def modify_func(lib, opts, args): query, mods, dels = modify_parse_args(decargs(args)) if not mods and not dels: raise ui.UserError(u'no modifications specified') modify_items(lib, mods, dels, query, ui.should_write(opts.write), ui.should_move(opts.move), opts.album, not opts.yes) modify_cmd = ui.Subcommand( u'modify', help=u'change metadata fields', aliases=(u'mod',) ) modify_cmd.parser.add_option( u'-m', u'--move', action='store_true', dest='move', help=u"move files in the library directory" ) modify_cmd.parser.add_option( u'-M', u'--nomove', action='store_false', dest='move', help=u"don't move files in library" ) modify_cmd.parser.add_option( u'-w', u'--write', action='store_true', default=None, help=u"write new metadata to files' tags (default)" ) modify_cmd.parser.add_option( u'-W', u'--nowrite', action='store_false', dest='write', help=u"don't write metadata (opposite of -w)" ) modify_cmd.parser.add_album_option() modify_cmd.parser.add_format_option(target='item') modify_cmd.parser.add_option( u'-y', u'--yes', action='store_true', help=u'skip confirmation' ) modify_cmd.func = modify_func default_commands.append(modify_cmd) # move: Move/copy files to the library or a new base directory. def move_items(lib, dest, query, copy, album, pretend, confirm=False): """Moves or copies items to a new base directory, given by dest. If dest is None, then the library's base directory is used, making the command "consolidate" files. """ items, albums = _do_query(lib, query, album, False) objs = albums if album else items # Filter out files that don't need to be moved. isitemmoved = lambda item: item.path != item.destination(basedir=dest) isalbummoved = lambda album: any(isitemmoved(i) for i in album.items()) objs = [o for o in objs if (isalbummoved if album else isitemmoved)(o)] action = u'Copying' if copy else u'Moving' act = u'copy' if copy else u'move' entity = u'album' if album else u'item' log.info(u'{0} {1} {2}{3}.', action, len(objs), entity, u's' if len(objs) != 1 else u'') if not objs: return if pretend: if album: show_path_changes([(item.path, item.destination(basedir=dest)) for obj in objs for item in obj.items()]) else: show_path_changes([(obj.path, obj.destination(basedir=dest)) for obj in objs]) else: if confirm: objs = ui.input_select_objects( u'Really %s' % act, objs, lambda o: show_path_changes( [(o.path, o.destination(basedir=dest))])) for obj in objs: log.debug(u'moving: {0}', util.displayable_path(obj.path)) obj.move(copy, basedir=dest) obj.store() def move_func(lib, opts, args): dest = opts.dest if dest is not None: dest = normpath(dest) if not os.path.isdir(dest): raise ui.UserError(u'no such directory: %s' % dest) move_items(lib, dest, decargs(args), opts.copy, opts.album, opts.pretend, opts.timid) move_cmd = ui.Subcommand( u'move', help=u'move or copy items', aliases=(u'mv',) ) move_cmd.parser.add_option( u'-d', u'--dest', metavar='DIR', dest='dest', help=u'destination directory' ) move_cmd.parser.add_option( u'-c', u'--copy', default=False, action='store_true', help=u'copy instead of moving' ) move_cmd.parser.add_option( u'-p', u'--pretend', default=False, action='store_true', help=u'show how files would be moved, but don\'t touch anything' ) move_cmd.parser.add_option( u'-t', u'--timid', dest='timid', action='store_true', help=u'always confirm all actions' ) move_cmd.parser.add_album_option() move_cmd.func = move_func default_commands.append(move_cmd) # write: Write tags into files. def write_items(lib, query, pretend, force): """Write tag information from the database to the respective files in the filesystem. """ items, albums = _do_query(lib, query, False, False) for item in items: # Item deleted? if not os.path.exists(syspath(item.path)): log.info(u'missing file: {0}', util.displayable_path(item.path)) continue # Get an Item object reflecting the "clean" (on-disk) state. try: clean_item = library.Item.from_path(item.path) except library.ReadError as exc: log.error(u'error reading {0}: {1}', displayable_path(item.path), exc) continue # Check for and display changes. changed = ui.show_model_changes(item, clean_item, library.Item._media_tag_fields, force) if (changed or force) and not pretend: # We use `try_sync` here to keep the mtime up to date in the # database. item.try_sync(True, False) def write_func(lib, opts, args): write_items(lib, decargs(args), opts.pretend, opts.force) write_cmd = ui.Subcommand(u'write', help=u'write tag information to files') write_cmd.parser.add_option( u'-p', u'--pretend', action='store_true', help=u"show all changes but do nothing" ) write_cmd.parser.add_option( u'-f', u'--force', action='store_true', help=u"write tags even if the existing tags match the database" ) write_cmd.func = write_func default_commands.append(write_cmd) # config: Show and edit user configuration. def config_func(lib, opts, args): # Make sure lazy configuration is loaded config.resolve() # Print paths. if opts.paths: filenames = [] for source in config.sources: if not opts.defaults and source.default: continue if source.filename: filenames.append(source.filename) # In case the user config file does not exist, prepend it to the # list. user_path = config.user_config_path() if user_path not in filenames: filenames.insert(0, user_path) for filename in filenames: print_(displayable_path(filename)) # Open in editor. elif opts.edit: config_edit() # Dump configuration. else: config_out = config.dump(full=opts.defaults, redact=opts.redact) print_(util.text_string(config_out)) def config_edit(): """Open a program to edit the user configuration. An empty config file is created if no existing config file exists. """ path = config.user_config_path() editor = util.editor_command() try: if not os.path.isfile(path): open(path, 'w+').close() util.interactive_open([path], editor) except OSError as exc: message = u"Could not edit configuration: {0}".format(exc) if not editor: message += u". Please set the EDITOR environment variable" raise ui.UserError(message) config_cmd = ui.Subcommand(u'config', help=u'show or edit the user configuration') config_cmd.parser.add_option( u'-p', u'--paths', action='store_true', help=u'show files that configuration was loaded from' ) config_cmd.parser.add_option( u'-e', u'--edit', action='store_true', help=u'edit user configuration with $EDITOR' ) config_cmd.parser.add_option( u'-d', u'--defaults', action='store_true', help=u'include the default configuration' ) config_cmd.parser.add_option( u'-c', u'--clear', action='store_false', dest='redact', default=True, help=u'do not redact sensitive fields' ) config_cmd.func = config_func default_commands.append(config_cmd) # completion: print completion script def print_completion(*args): for line in completion_script(default_commands + plugins.commands()): print_(line, end=u'') if not any(map(os.path.isfile, BASH_COMPLETION_PATHS)): log.warning(u'Warning: Unable to find the bash-completion package. ' u'Command line completion might not work.') BASH_COMPLETION_PATHS = map(syspath, [ u'/etc/bash_completion', u'/usr/share/bash-completion/bash_completion', u'/usr/local/share/bash-completion/bash_completion', # SmartOS u'/opt/local/share/bash-completion/bash_completion', # Homebrew (before bash-completion2) u'/usr/local/etc/bash_completion', ]) def completion_script(commands): """Yield the full completion shell script as strings. ``commands`` is alist of ``ui.Subcommand`` instances to generate completion data for. """ base_script = os.path.join(_package_path('beets.ui'), 'completion_base.sh') with open(base_script, 'r') as base_script: yield util.text_string(base_script.read()) options = {} aliases = {} command_names = [] # Collect subcommands for cmd in commands: name = cmd.name command_names.append(name) for alias in cmd.aliases: if re.match(r'^\w+$', alias): aliases[alias] = name options[name] = {u'flags': [], u'opts': []} for opts in cmd.parser._get_all_options()[1:]: if opts.action in ('store_true', 'store_false'): option_type = u'flags' else: option_type = u'opts' options[name][option_type].extend( opts._short_opts + opts._long_opts ) # Add global options options['_global'] = { u'flags': [u'-v', u'--verbose'], u'opts': u'-l --library -c --config -d --directory -h --help'.split(u' ') } # Add flags common to all commands options['_common'] = { u'flags': [u'-h', u'--help'] } # Start generating the script yield u"_beet() {\n" # Command names yield u" local commands='%s'\n" % ' '.join(command_names) yield u"\n" # Command aliases yield u" local aliases='%s'\n" % ' '.join(aliases.keys()) for alias, cmd in aliases.items(): yield u" local alias__%s=%s\n" % (alias, cmd) yield u'\n' # Fields yield u" fields='%s'\n" % ' '.join( set( list(library.Item._fields.keys()) + list(library.Album._fields.keys()) ) ) # Command options for cmd, opts in options.items(): for option_type, option_list in opts.items(): if option_list: option_list = u' '.join(option_list) yield u" local %s__%s='%s'\n" % ( option_type, cmd, option_list) yield u' _beet_dispatch\n' yield u'}\n' completion_cmd = ui.Subcommand( 'completion', help=u'print shell script that provides command line completion' ) completion_cmd.func = print_completion completion_cmd.hide = True default_commands.append(completion_cmd)
Kraymer/beets
beets/ui/commands.py
Python
mit
59,450
#========================================================================== # Copyright 2012 Lucidel, Inc., 2013 Cloudoscope Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this work except in compliance with the License. # You may obtain a copy of the License in the LICENSE file, or 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. #==========================================================================
gadio/moma-django
moma_example/testing/views.py
Python
apache-2.0
772
from mongoengine import * from django.utils.hashcompat import md5_constructor, sha_constructor from django.utils.encoding import smart_str from django.contrib.auth.models import AnonymousUser from django.utils.translation import ugettext_lazy as _ import datetime REDIRECT_FIELD_NAME = 'next' def get_hexdigest(algorithm, salt, raw_password): raw_password, salt = smart_str(raw_password), smart_str(salt) if algorithm == 'md5': return md5_constructor(salt + raw_password).hexdigest() elif algorithm == 'sha1': return sha_constructor(salt + raw_password).hexdigest() raise ValueError('Got unknown password algorithm type in password') class User(Document): """A User document that aims to mirror most of the API specified by Django at http://docs.djangoproject.com/en/dev/topics/auth/#users """ username = StringField(max_length=30, required=True, verbose_name=_('username'), help_text=_("Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters")) first_name = StringField(max_length=30, verbose_name=_('first name')) last_name = StringField(max_length=30, verbose_name=_('last name')) email = EmailField(verbose_name=_('e-mail address')) password = StringField(max_length=128, verbose_name=_('password'), help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>.")) is_staff = BooleanField(default=False, verbose_name=_('staff status'), help_text=_("Designates whether the user can log into this admin site.")) is_active = BooleanField(default=True, verbose_name=_('active'), help_text=_("Designates whether this user should be treated as active. Unselect this instead of deleting accounts.")) is_superuser = BooleanField(default=False, verbose_name=_('superuser status'), help_text=_("Designates that this user has all permissions without explicitly assigning them.")) last_login = DateTimeField(default=datetime.datetime.now, verbose_name=_('last login')) date_joined = DateTimeField(default=datetime.datetime.now, verbose_name=_('date joined')) meta = { 'indexes': [ {'fields': ['username'], 'unique': True} ] } def __unicode__(self): return self.username def get_full_name(self): """Returns the users first and last names, separated by a space. """ full_name = u'%s %s' % (self.first_name or '', self.last_name or '') return full_name.strip() def is_anonymous(self): return False def is_authenticated(self): return True def set_password(self, raw_password): """Sets the user's password - always use this rather than directly assigning to :attr:`~mongoengine.django.auth.User.password` as the password is hashed before storage. """ from random import random algo = 'sha1' salt = get_hexdigest(algo, str(random()), str(random()))[:5] hash = get_hexdigest(algo, salt, raw_password) self.password = '%s$%s$%s' % (algo, salt, hash) self.save() return self def check_password(self, raw_password): """Checks the user's password against a provided password - always use this rather than directly comparing to :attr:`~mongoengine.django.auth.User.password` as the password is hashed before storage. """ algo, salt, hash = self.password.split('$') return hash == get_hexdigest(algo, salt, raw_password) @classmethod def create_user(cls, username, password, email=None): """Create (and save) a new user with the given username, password and email address. """ now = datetime.datetime.now() # Normalize the address by lowercasing the domain part of the email # address. if email is not None: try: email_name, domain_part = email.strip().split('@', 1) except ValueError: pass else: email = '@'.join([email_name, domain_part.lower()]) user = cls(username=username, email=email, date_joined=now) user.set_password(password) user.save() return user def get_and_delete_messages(self): return [] class MongoEngineBackend(object): """Authenticate using MongoEngine and mongoengine.django.auth.User. """ supports_object_permissions = False supports_anonymous_user = False supports_inactive_user = False def authenticate(self, username=None, password=None): user = User.objects(username=username).first() if user: if password and user.check_password(password): return user return None def get_user(self, user_id): return User.objects.with_id(user_id) def get_user(userid): """Returns a User object from an id (User.id). Django's equivalent takes request, but taking an id instead leaves it up to the developer to store the id in any way they want (session, signed cookie, etc.) """ if not userid: return AnonymousUser() return MongoEngineBackend().get_user(userid) or AnonymousUser()
KarimAllah/mongoengine
mongoengine/django/auth.py
Python
mit
5,621
#coding: utf-8 from __future__ import unicode_literals import codecs from pymorphy.backends.base import DictDataSource from pymorphy.constants import PRODUCTIVE_CLASSES class MrdDataSource(DictDataSource): """ Источник данных для морфологического анализатора pymorphy, берущий информацию из оригинальных mrd-файлов (в которых кодировка была изменена с 1251 на utf-8). Используется для конвертации оригинальных данных в простые для обработки ShelveDict или PickledDict. """ def __init__(self, dict_name, gramtab_name, strip_EE=True): super(MrdDataSource, self).__init__() self.dict_name = dict_name self.gramtab_name = gramtab_name self.strip_EE = strip_EE def load(self): self._load(self.dict_name, self.gramtab_name) self.calculate_rule_freq() self._calculate_endings() self._cleanup_endings() #----------- protected methods ------------- def _section_lines(self, file): """ Прочитать все строки в секции mrd-файла, заменяя Ё на Е, если установлен параметр strip_EE """ lines_count = int(file.readline()) for i in xrange(0, lines_count): if self.strip_EE: yield file.readline().replace('Ё','Е') else: yield file.readline() def _pass_lines(self, file): """ Пропустить секцию """ for line in self._section_lines(file): pass def _load_rules(self, file): """ Загрузить все парадигмы слов""" for paradigm_id, line in enumerate(self._section_lines(file)): line_rules = line.strip().split('%') index = 0 # не enumerate, чтоб не считать пустые строки for rule in line_rules: if not rule: continue parts = rule.split('*') if len(parts)==2: parts.append('') suffix, ancode, prefix = parts ancode = ancode[:2] if paradigm_id not in self.rules: self.rules[paradigm_id] = {} # первое встреченное правило считаем за нормальную форму self.normal_forms[paradigm_id] = parts paradigm = self.rules[paradigm_id] if suffix not in paradigm: paradigm[suffix] = [] paradigm[suffix].append((ancode, prefix, index)) if prefix: self.possible_rule_prefixes.add(prefix) index += 1 def _load_lemmas(self, file): """ Загрузить текущую секцию как секцию с леммами """ for line in self._section_lines(file): record = line.split() base, paradigm_id = record[0], record[1] # Информацию об ударениях, пользовательских сессиях, # общий для всех парадигм анкод и наборы префиксов мы тут не # учитываем. # Сессии - специфичная для aot-редактора информация, # анкод можно получить из парадигмы, префикс все равно # дублирует "префиксы" self.prefixes (?). # accent_model_no, session_no, type_ancode, prefix_set_no = record[2:] if base not in self.lemmas: self.lemmas[base] = [] self.rule_freq[paradigm_id] = self.rule_freq.get(paradigm_id, 0) + 1 # FIXME: т.к. мы отбрасываем анкод, у нас тут могут быть # дубликаты парадигм (и будут, для ДУМА, например). self.lemmas[base].append(int(paradigm_id)) def _load_accents(self, file): return self._pass_lines(file) def _load_logs(self, file): """ Загрузить текущую секцию как секцию с логами (бесполезная штука) """ for line in self._section_lines(file): self.logs.append(line.strip()) def _load_prefixes(self, file): """ Загрузить текущую секцию как секцию с префиксами """ for line in self._section_lines(file): self.prefixes.add(line.strip()) def _load_gramtab(self, file): """ Загрузить грамматическую информацию из файла """ for line in file: line=line.strip() if line.startswith('//') or line == '': continue g = line.split() if len(g)==3: g.append('') ancode, letter, type, info = g[0:4] self.gramtab[ancode] = (type, info, letter,) def _load(self, filename, gramfile): with codecs.open(filename, 'r', 'utf8') as dict_file: self._load_rules(dict_file) self._load_accents(dict_file) self._load_logs(dict_file) self._load_prefixes(dict_file) self._load_lemmas(dict_file) with codecs.open(gramfile, 'r', 'utf8') as gram_file: self._load_gramtab(gram_file) def _calculate_endings(self): """ Подсчитать все возможные 5-буквенные окончания слов. Перебирает все возможные формы всех слов по словарю, смотрит окончание и добавляет его в словарь. """ # перебираем все слова for lemma in self.lemmas: # берем все возможные парадигмы for paradigm_id in self.lemmas[lemma]: paradigm = self.rules[paradigm_id] for suffix in paradigm: for ancode, prefix, index in paradigm[suffix]: # формируем слово word = ''.join((prefix, lemma, suffix)) # добавляем окончания и номера правил их получения в словарь for i in 1,2,3,4,5: word_end = word[-i:] if word_end: if word_end not in self.endings: self.endings[word_end] = {} ending = self.endings[word_end] if paradigm_id not in ending: ending[paradigm_id]=set() ending[paradigm_id].add((suffix, ancode, prefix)) def _cleanup_endings(self): """ Очистка правил в словаре возможных окончаний. Правил получается много, оставляем только те, которые относятся к продуктивным частям речи + для каждого окончания оставляем только по 1 самому популярному правилу на каждую часть речи. """ for word_end in self.endings: ending_info = self.endings[word_end] result_info = {} best_paradigms = {} for paradigm_id in ending_info: base_suffix, base_ancode, base_prefix = self.normal_forms[paradigm_id] base_gram = self.gramtab[base_ancode] word_class = base_gram[0] if word_class not in PRODUCTIVE_CLASSES: continue if word_class not in best_paradigms: best_paradigms[word_class] = paradigm_id else: new_freq = self.rule_freq[paradigm_id] old_freq = self.rule_freq[best_paradigms[word_class]] if new_freq > old_freq: best_paradigms[word_class] = paradigm_id for word_class in best_paradigms: paradigm_id = best_paradigms[word_class] # приводим к tuple, т.к. set плохо сериализуется result_info[paradigm_id] = tuple(ending_info[paradigm_id]) self.endings[word_end] = result_info @staticmethod def setup_psyco(): """ Оптимизировать узкие места в MrdDataSource с помощью psyco """ try: import psyco psyco.bind(MrdDataSource._calculate_endings) psyco.bind(MrdDataSource._load_lemmas) psyco.bind(MrdDataSource._cleanup_endings) psyco.bind(MrdDataSource._section_lines) psyco.bind(DictDataSource.calculate_rule_freq) except ImportError: pass
kmike/pymorphy
pymorphy/backends/mrd_source.py
Python
mit
9,408
from django.core.urlresolvers import reverse from django.test import TestCase from mock import patch, Mock from silk.config import SilkyConfig from silk.middleware import SilkyMiddleware, _should_intercept from silk.models import Request from .util import mock_data_collector class TestApplyDynamicMappings(TestCase): def test_dynamic_decorator(self): middleware = SilkyMiddleware() SilkyConfig().SILKY_DYNAMIC_PROFILING = [ { 'module': 'tests.data.dynamic', 'function': 'foo' } ] middleware._apply_dynamic_mappings() from .data.dynamic import foo mock = mock_data_collector() with patch('silk.profiling.profiler.DataCollector', return_value=mock) as mock_DataCollector: foo() # Should be wrapped in a decorator self.assertTrue(mock_DataCollector.return_value.register_profile.call_count) def test_dynamic_context_manager(self): middleware = SilkyMiddleware() SilkyConfig().SILKY_DYNAMIC_PROFILING = [ { 'module': 'tests.data.dynamic', 'function': 'foo', 'start_line': 1, 'end_line': 2, } ] middleware._apply_dynamic_mappings() from .data.dynamic import foo mock = mock_data_collector() with patch('silk.profiling.profiler.DataCollector', return_value=mock) as mock_DataCollector: foo() self.assertTrue(mock_DataCollector.return_value.register_profile.call_count) def test_invalid_dynamic_context_manager(self): middleware = SilkyMiddleware() SilkyConfig().SILKY_DYNAMIC_PROFILING = [ { 'module': 'tests.data.dynamic', 'function': 'foo2', 'start_line': 1, 'end_line': 7, } ] self.assertRaises(IndexError, middleware._apply_dynamic_mappings) def test_invalid_dynamic_decorator_module(self): middleware = SilkyMiddleware() SilkyConfig().SILKY_DYNAMIC_PROFILING = [ { 'module': 'tests.data.dfsdf', 'function': 'foo' } ] self.assertRaises(AttributeError, middleware._apply_dynamic_mappings) def test_invalid_dynamic_decorator_function_name(self): middleware = SilkyMiddleware() SilkyConfig().SILKY_DYNAMIC_PROFILING = [ { 'module': 'tests.data.dynamic', 'function': 'bar' } ] self.assertRaises(AttributeError, middleware._apply_dynamic_mappings) def test_invalid_dynamic_mapping(self): middleware = SilkyMiddleware() SilkyConfig().SILKY_DYNAMIC_PROFILING = [ { 'dfgdf': 'tests.data.dynamic', 'funcgdfgtion': 'bar' } ] self.assertRaises(KeyError, middleware._apply_dynamic_mappings) def test_no_mappings(self): middleware = SilkyMiddleware() SilkyConfig().SILKY_DYNAMIC_PROFILING = [ ] middleware._apply_dynamic_mappings() # Just checking no crash class TestShouldIntercept(TestCase): def test_should_intercept_non_silk_request(self): request = Request() request.path = '/myapp/foo' should_intercept = _should_intercept(request) self.assertTrue(should_intercept) def test_should_intercept_silk_request(self): request = Request() request.path = reverse('silk:summary') should_intercept = _should_intercept(request) self.assertFalse(should_intercept) def test_should_intercept_ignore_paths(self): SilkyConfig().SILKY_IGNORE_PATHS = [ '/ignorethis' ] request = Request() request.path = '/ignorethis' should_intercept = _should_intercept(request) self.assertFalse(should_intercept)
ruhan/django-silk-mongoengine
project/tests/test_silky_middleware.py
Python
mit
3,980
# Copyright (c) 2012 ARM Limited # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # Copyright (c) 2007 The Regents of The University of Michigan # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Nathan Binkert from m5.params import * from BaseSimpleCPU import BaseSimpleCPU class AtomicSimpleCPU(BaseSimpleCPU): type = 'AtomicSimpleCPU' width = Param.Int(1, "CPU width") simulate_data_stalls = Param.Bool(False, "Simulate dcache stall cycles") simulate_inst_stalls = Param.Bool(False, "Simulate icache stall cycles") fastmem = Param.Bool(False, "Access memory directly")
xiaoyaozi5566/GEM5_DRAMSim2
src/cpu/simple/AtomicSimpleCPU.py
Python
bsd-3-clause
2,568
__author__ = 'WylYeak'
wylyeak/verify_zip_file
gui/__init__.py
Python
gpl-2.0
23
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('store', '0011_remove_cloud_users_email'), ] operations = [ migrations.RemoveField( model_name='cloud_users', name='id', ), migrations.AlterField( model_name='cloud_users', name='cloud_user', field=models.CharField(max_length=50, serialize=False, primary_key=True), ), ]
cparawhore/ProyectoSubastas
store/migrations/0012_auto_20140920_1900.py
Python
mit
554
# -*- coding: utf-8 -*- # Copyright 2017, Digital Reasoning # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import unicode_literals import logging import os import zipfile from collections import OrderedDict import envoy from actstream import action from django.contrib.auth.models import Group from django.contrib.contenttypes.models import ContentType from guardian.shortcuts import assign_perm from rest_framework import generics, status from rest_framework.filters import DjangoFilterBackend, DjangoObjectPermissionsFilter from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework.serializers import ValidationError from six import StringIO from stackdio.api.cloud.filters import SecurityGroupFilter from stackdio.api.formulas.models import FormulaVersion from stackdio.api.formulas.serializers import FormulaVersionSerializer from stackdio.api.stacks import filters, mixins, models, serializers, utils, workflows from stackdio.api.volumes.serializers import VolumeSerializer from stackdio.core.constants import Activity from stackdio.core.notifications.serializers import ( UserSubscriberNotificationChannelSerializer, GroupSubscriberNotificationChannelSerializer, ) from stackdio.core.permissions import StackdioModelPermissions, StackdioObjectPermissions from stackdio.core.renderers import PlainTextRenderer, ZipRenderer from stackdio.core.serializers import ObjectPropertiesSerializer from stackdio.core.viewsets import ( StackdioModelUserPermissionsViewSet, StackdioModelGroupPermissionsViewSet, StackdioObjectUserPermissionsViewSet, StackdioObjectGroupPermissionsViewSet, ) logger = logging.getLogger(__name__) class StackListAPIView(generics.ListCreateAPIView): """ Displays a list of all stacks visible to you. """ queryset = models.Stack.objects.all() permission_classes = (StackdioModelPermissions,) filter_backends = (DjangoObjectPermissionsFilter, DjangoFilterBackend) filter_class = filters.StackFilter def get_serializer_class(self): if self.request.method == 'POST': return serializers.FullStackSerializer else: return serializers.StackSerializer def perform_create(self, serializer): stack = serializer.save() for perm in models.Stack.object_permissions: assign_perm('stacks.%s_stack' % perm, self.request.user, stack) stack.labels.create(key='owner', value=self.request.user.username) # Create all the formula versions from the blueprint for formula_version in stack.blueprint.formula_versions.all(): # Make sure the version doesn't already exist (could have been created in # the serializer.save() call) try: stack.formula_versions.get(formula=formula_version.formula) except FormulaVersion.DoesNotExist: stack.formula_versions.create(formula=formula_version.formula, version=formula_version.version) class StackDetailAPIView(generics.RetrieveUpdateDestroyAPIView): queryset = models.Stack.objects.all() serializer_class = serializers.StackSerializer permission_classes = (StackdioObjectPermissions,) def destroy(self, request, *args, **kwargs): """ Overriding the delete method to make sure the stack is taken offline before being deleted. The default delete method returns a 204 status and we want to return a 202 with the serialized object """ instance = self.get_object() self.perform_destroy(instance) serializer = self.get_serializer(instance) return Response(serializer.data, status=status.HTTP_202_ACCEPTED) def perform_destroy(self, instance): stack = instance # Check the activity if stack.activity not in Activity.can_delete: err_msg = ('You may not delete this stack in its current state. Please wait until ' 'it is finished with the current action.') raise ValidationError({ 'detail': [err_msg] }) # Update the status stack.set_activity(Activity.QUEUED) action.send(self.request.user, verb='deleted', action_object=instance) # Execute the workflow to delete the infrastructure workflow = workflows.DestroyStackWorkflow(stack, opts=self.request.data) workflow.execute() class StackPropertiesAPIView(generics.RetrieveUpdateAPIView): queryset = models.Stack.objects.all() serializer_class = ObjectPropertiesSerializer permission_classes = (StackdioObjectPermissions,) class StackHistoryAPIView(mixins.StackRelatedMixin, generics.ListAPIView): serializer_class = serializers.StackHistorySerializer def get_queryset(self): stack = self.get_stack() return stack.history.all() class StackActionAPIView(mixins.StackRelatedMixin, generics.GenericAPIView): serializer_class = serializers.StackActionSerializer def get(self, request, *args, **kwargs): stack = self.get_stack() # Grab the list of available actions for the current stack activity available_actions = Activity.action_map.get(stack.activity, []) # Filter them based on permissions available_actions = utils.filter_actions(request.user, stack, available_actions) return Response({ 'available_actions': sorted(available_actions), }) def post(self, request, *args, **kwargs): """ POST request allows RPC-like actions to be called to interact with the stack. Request contains JSON with an `action` parameter and optional `args` depending on the action being executed. """ stack = self.get_stack() serializer = self.get_serializer(stack, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) class StackCommandListAPIView(mixins.StackRelatedMixin, generics.ListCreateAPIView): serializer_class = serializers.StackCommandSerializer def get_queryset(self): stack = self.get_stack() return stack.commands.all() def perform_create(self, serializer): serializer.save(stack=self.get_stack()) class StackCommandDetailAPIView(mixins.StackRelatedMixin, generics.RetrieveDestroyAPIView): serializer_class = serializers.StackCommandSerializer def get_queryset(self): stack = self.get_stack() return stack.commands.all() class StackCommandZipAPIView(mixins.StackRelatedMixin, generics.GenericAPIView): renderer_classes = (ZipRenderer,) def get_queryset(self): stack = self.get_stack() return stack.commands.all() def get(self, request, *args, **kwargs): command = self.get_object() filename = 'command_output_' + command.submit_time.strftime('%Y%m%d_%H%M%S') file_buffer = StringIO.StringIO() with zipfile.ZipFile(file_buffer, 'w') as command_zip: # Write out all the contents command_zip.writestr( str('{0}/__command'.format(filename)), str(command.command) ) for output in command.std_out: command_zip.writestr( str('{0}/{1}.txt'.format(filename, output['host'])), str(output['output']) ) # Give browsers a reasonable filename to save this as headers = { 'Content-Disposition': 'attachment; filename={0}.zip'.format(filename) } return Response(file_buffer.getvalue(), headers=headers) class StackLabelListAPIView(mixins.StackRelatedMixin, generics.ListCreateAPIView): serializer_class = serializers.StackLabelSerializer def get_queryset(self): stack = self.get_stack() return stack.labels.all() def get_serializer_context(self): context = super(StackLabelListAPIView, self).get_serializer_context() context['content_object'] = self.get_stack() return context def perform_create(self, serializer): serializer.save(content_object=self.get_stack()) class StackLabelDetailAPIView(mixins.StackRelatedMixin, generics.RetrieveUpdateDestroyAPIView): serializer_class = serializers.StackLabelSerializer lookup_field = 'key' lookup_url_kwarg = 'label_name' def get_queryset(self): stack = self.get_stack() return stack.labels.all() def get_serializer_context(self): context = super(StackLabelDetailAPIView, self).get_serializer_context() context['content_object'] = self.get_stack() return context class StackComponentListAPIView(mixins.StackRelatedMixin, generics.ListAPIView): serializer_class = serializers.StackComponentSerializer def get_queryset(self): stack = self.get_stack() return stack.get_components() class StackUserChannelsListAPIView(mixins.StackRelatedMixin, generics.ListCreateAPIView): serializer_class = UserSubscriberNotificationChannelSerializer def get_queryset(self): stack = self.get_stack() return stack.subscribed_channels.filter(auth_object=self.request.user) def get_serializer_context(self): context = super(StackUserChannelsListAPIView, self).get_serializer_context() context['auth_object'] = self.request.user return context def perform_create(self, serializer): serializer.save(auth_object=self.request.user, subscribed_object=self.get_stack()) class StackGroupChannelsListAPIView(mixins.StackRelatedMixin, generics.ListCreateAPIView): serializer_class = GroupSubscriberNotificationChannelSerializer def get_queryset(self): stack = self.get_stack() group_ctype = ContentType.objects.get_for_model(Group) # We want all the subscribed channels that are associated with groups return stack.subscribed_channels.filter(auth_object_content_type=group_ctype) def perform_create(self, serializer): serializer.save(subscribed_object=self.get_stack()) class StackHostListAPIView(mixins.StackRelatedMixin, generics.ListCreateAPIView): """ Lists all hosts for the associated stack. #### POST /api/stacks/<stack_id>/hosts/ Allows users to add or remove hosts from a running stack. { "action": "add", "host_definition": "<slug>", "count": <int>, "backfill": <bool> } OR { "action": "remove", "host_definition": "<slug>", "count": <int> } where: `action` (string) REQUIRED -- either add or remove `count` (int) REQUIRED -- how many additional hosts to add / remove `host_definition` (string) REQUIRED -- the id of a blueprint host definition that is part of the blueprint the stack was initially launched from `backfill` (bool) OPTIONAL, DEFAULT=false -- if true, the hostnames will be generated in a way to fill in any gaps in the existing hostnames of the stack. For example, if your stack has a host list [foo-1, foo-3, foo-4] and you ask for three additional hosts, the resulting set of hosts is [foo-1, foo-2, foo-3, foo4, foo-5, foo-6] """ serializer_class = serializers.HostSerializer filter_class = filters.HostFilter def get_queryset(self): stack = self.get_stack() return stack.hosts.all() def get_serializer_context(self): """ We need the stack during serializer validation - so we'll throw it in the context """ context = super(StackHostListAPIView, self).get_serializer_context() context['stack'] = self.get_stack() return context class StackHostDetailAPIView(mixins.StackRelatedMixin, generics.RetrieveDestroyAPIView): serializer_class = serializers.HostSerializer def get_queryset(self): stack = self.get_stack() return stack.hosts.all() def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) # Return the host while its deleting serializer = self.get_serializer(instance) return Response(serializer.data, status=status.HTTP_202_ACCEPTED) def perform_destroy(self, instance): stack = instance.stack if stack.activity not in Activity.can_delete: err_msg = 'You may not delete hosts on this stack in its current state: {0}' raise ValidationError({ 'stack': [err_msg.format(stack.activity)] }) instance.set_activity(Activity.QUEUED) action.send(self.request.user, verb='deleted', action_object=instance) host_ids = [instance.id] # unregister DNS and destroy the host workflows.DestroyHostsWorkflow(stack, host_ids).execute() class StackVolumeListAPIView(mixins.StackRelatedMixin, generics.ListAPIView): serializer_class = VolumeSerializer def get_queryset(self): stack = self.get_stack() return stack.volumes.all() class StackLogsAPIView(mixins.StackRelatedMixin, generics.GenericAPIView): log_types = ( 'launch', 'provisioning', 'provisioning-error', 'global_orchestration', 'global_orchestration-error', 'orchestration', 'orchestration-error', ) def get(self, request, *args, **kwargs): stack = self.get_stack() root_dir = stack.get_root_directory() log_dir = stack.get_log_directory() latest = OrderedDict() for log_type in self.log_types: spl = log_type.split('-') if len(spl) > 1 and spl[1] == 'error': log_file = '%s.err.latest' % spl[0] else: log_file = '%s.log.latest' % log_type if os.path.isfile(os.path.join(root_dir, log_file)): latest[log_type] = reverse( 'api:stacks:stack-logs-detail', kwargs={'parent_pk': stack.pk, 'log': log_file}, request=request, ) historical = [ reverse('api:stacks:stack-logs-detail', kwargs={'parent_pk': stack.pk, 'log': log}, request=request) for log in sorted(os.listdir(log_dir)) ] ret = OrderedDict(( ('latest', latest), ('historical', historical), )) return Response(ret) class StackLogsDetailAPIView(mixins.StackRelatedMixin, generics.GenericAPIView): renderer_classes = (PlainTextRenderer,) def get(self, request, *args, **kwargs): stack = self.get_stack() log_file = self.kwargs.get('log', '') try: tail = int(request.query_params.get('tail', 0)) except ValueError: tail = None try: head = int(request.query_params.get('head', 0)) except ValueError: head = None if head and tail: return Response('Both head and tail may not be used.', status=status.HTTP_400_BAD_REQUEST) if log_file.endswith('.latest'): log = os.path.join(stack.get_root_directory(), log_file) elif log_file.endswith('.log') or log_file.endswith('.err'): log = os.path.join(stack.get_log_directory(), log_file) else: log = None if not log or not os.path.isfile(log): raise ValidationError({ 'log_file': ['Log file does not exist: {0}.'.format(log_file)] }) if tail: ret = envoy.run('tail -{0} {1}'.format(tail, log)).std_out elif head: ret = envoy.run('head -{0} {1}'.format(head, log)).std_out else: with open(log, 'r') as f: ret = f.read() return Response(ret) class StackSecurityGroupsAPIView(mixins.StackRelatedMixin, generics.ListAPIView): serializer_class = serializers.StackSecurityGroupSerializer filter_class = SecurityGroupFilter def get_queryset(self): stack = self.get_stack() return stack.get_security_groups() class StackFormulaVersionsAPIView(mixins.StackRelatedMixin, generics.ListCreateAPIView): serializer_class = FormulaVersionSerializer def get_queryset(self): stack = self.get_stack() return stack.formula_versions.all() def perform_create(self, serializer): serializer.save(content_object=self.get_stack()) class StackModelUserPermissionsViewSet(StackdioModelUserPermissionsViewSet): model_cls = models.Stack class StackModelGroupPermissionsViewSet(StackdioModelGroupPermissionsViewSet): model_cls = models.Stack class StackObjectUserPermissionsViewSet(mixins.StackPermissionsMixin, StackdioObjectUserPermissionsViewSet): pass class StackObjectGroupPermissionsViewSet(mixins.StackPermissionsMixin, StackdioObjectGroupPermissionsViewSet): pass
clarkperkins/stackdio
stackdio/api/stacks/api.py
Python
apache-2.0
17,778
#!/usr/bin/python # # Copyright 2011 Thomas Bollmeier # # This file is part of GObjectCreator2. # # GObjectCreator2 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. # # GObjectCreator2 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 GObjectCreator2. If not, see <http://www.gnu.org/licenses/>. # import sys from optparse import OptionParser import os from gobjcreator2.input.goc_recognizer import GOCRecognizer from gobjcreator2.metadef.package import Package from gobjcreator2.metadef.gobject import GObject from gobjcreator2.metadef.ginterface import GInterface from gobjcreator2.metadef.genum import GEnum from gobjcreator2.metadef.gflags import GFlags from gobjcreator2.metadef.error_domain import ErrorDomain from gobjcreator2.output.writer import FileOut from gobjcreator2.output.gobject_writer import GObjectWriter from gobjcreator2.output.ginterface_writer import GInterfaceWriter from gobjcreator2.output.genum_writer import GEnumWriter from gobjcreator2.output.gflags_writer import GFlagsWriter from gobjcreator2.output.error_domain_writer import ErrorDomainWriter from gobjcreator2.output.marshaller_generator import MarshallerGenerator from gobjcreator2.output.file_name_manager import get_file_name_manager, FileNameStyle from gobjcreator2 import VERSION def _create_option_parser(): res = OptionParser(usage = "usage: %prog [options] <goc_file>", version = "%%prog, Version: %s, Author: Thomas Bollmeier" % \ VERSION ) res.add_option("-d", "--dir", dest = "outdir", default = os.curdir, metavar = "DIR", help = "generate files in directory DIR" ) res.add_option("-r", "--root", dest = "root", default = "", metavar = "ROOT_NAME", help = "generate objects of subtree ROOT_NAME only" ) res.add_option("-I", "--include", action = "append", dest = "include_paths", default = [], metavar = "DIR", help = "add DIR to search path for definition files" ) res.add_option("-v", action = "store_true", dest = "verbose", default = False, help = "write generation info to standard output" ) res.add_option("", "--header-comment", dest = "header_comment_file", default = "", metavar = "FILE", help = "add header comment from FILE to generated code" ) res.add_option("", "--filename-style", dest = "filename_style", default = "underscore", metavar = "STYLE", help = "set STYLE for names of generated files (values: underscore (=default), hyphen)" ) return res class CodeGenerator(object): def __init__(self): self._outdir = os.curdir self._comment_lines = [] self._file_name_manager = get_file_name_manager() self.verbose = False def set_output_dir(self, outdir): self._outdir = outdir def set_header_comment_from_file(self, file_path): f = open(file_path, "r") self._comment_lines = [] for line in f.readlines(): self._comment_lines.append(line.strip("\n")) f.close() def set_file_name_manager(self, file_name_manager): self._file_name_manager = file_name_manager def _init_writer(self, writer): if self._comment_lines: writer.set_header_comment(self._comment_lines) writer.set_file_name_manager(self._file_name_manager) def create_code(self, elem): if not os.path.exists(self._outdir): os.mkdir(self._outdir) self._create_code(elem) def _create_code(self, elem): if isinstance(elem, Package): for el in elem.elements.values(): self._create_code(el) else: # skip elements from included goc files: if elem.is_external: return if isinstance(elem, GObject): self._create_code_object(elem) elif isinstance(elem, GInterface): self._create_code_interface(elem) elif isinstance(elem, GEnum): self._create_code_enumeration(elem) elif isinstance(elem, GFlags): self._create_code_flags(elem) elif isinstance(elem, ErrorDomain): self._create_code_error_domain(elem) def _create_code_object(self, elem): gobj = elem writer = GObjectWriter(gobj) self._init_writer(writer) self._write_header(writer, gobj) if not gobj.final: self._write_protected_header(writer, gobj) self._write_source(writer, gobj) if gobj.signals: self._write_marshaller_code(writer, gobj, for_header = True) self._write_marshaller_code(writer, gobj, for_header = False) def _create_code_interface(self, elem): writer = GInterfaceWriter(elem) self._init_writer(writer) self._write_header(writer, elem) self._write_source(writer, elem) if elem.signals: self._write_marshaller_code(writer, elem, for_header = True) self._write_marshaller_code(writer, elem, for_header = False) def _create_code_enumeration(self, elem): writer = GEnumWriter(elem) self._init_writer(writer) self._write_header(writer, elem) self._write_source(writer, elem) def _create_code_flags(self, elem): writer = GFlagsWriter(elem) self._init_writer(writer) self._write_header(writer, elem) def _create_code_error_domain(self, elem): writer = ErrorDomainWriter(elem) self._init_writer(writer) self._write_header(writer, elem) def _write_header(self, writer, elem): file_name = self._file_name_manager.get_header_name(elem) file_path = self._outdir + os.sep + file_name if self.verbose: print "generating file %s..." % file_path, writer.set_user_content(file_path) file_out = FileOut(file_path) saved_out = writer.get_output() writer.set_output(file_out) file_out.open() writer.write_header() file_out.close() writer.set_output(saved_out) if self.verbose: print "done" def _write_protected_header(self, writer, elem): file_name = self._file_name_manager.get_protected_header_name(elem) file_path = self._outdir + os.sep + file_name if self.verbose: print "generating file %s..." % file_path, writer.set_user_content(file_path) file_out = FileOut(file_path) saved_out = writer.get_output() writer.set_output(file_out) file_out.open() writer.write_header_protected() file_out.close() writer.set_output(saved_out) if self.verbose: print "done" def _write_source(self, writer, elem): file_name = self._file_name_manager.get_source_name(elem) file_path = self._outdir + os.sep + file_name if self.verbose: print "generating file %s..." % file_path, writer.set_user_content(file_path) if isinstance(writer, GObjectWriter) or isinstance(writer, GInterfaceWriter): writer.annotations.load_from_file(file_path) file_out = FileOut(file_path) saved_out = writer.get_output() writer.set_output(file_out) file_out.open() writer.write_source() file_out.close() writer.set_output(saved_out) if self.verbose: print "done" def _write_marshaller_code(self, writer, elem, for_header): if for_header: file_name = self._file_name_manager.get_marshaller_header_name(elem) else: file_name = self._file_name_manager.get_marshaller_source_name(elem) file_path = self._outdir + os.sep + file_name file_out = FileOut(file_path) if self.verbose: print "generating file %s..." % file_path, saved_out = writer.get_output() writer.set_output(file_out) file_out.open() marshaller_gen = MarshallerGenerator(elem) lines = marshaller_gen.get_code(for_header) for line in lines: writer.writeln(line) writer.writeln() file_out.close() writer.set_output(saved_out) if self.verbose: print "done" ##### main ##### parser = _create_option_parser() options, args = parser.parse_args() if not len(args) == 1: exit(1) goc_file = args[0] recognizer = GOCRecognizer() for path in options.include_paths: recognizer.add_include_path(path) top_package = recognizer.process_file(goc_file) if not options.root: root_elem = top_package else: root_elem = top_package[options.root] code_gen = CodeGenerator() code_gen.set_output_dir(options.outdir) code_gen.verbose = options.verbose if options.header_comment_file: code_gen.set_header_comment_from_file(options.header_comment_file) if options.filename_style == "underscore": code_gen.set_file_name_manager(get_file_name_manager(FileNameStyle.UNDERSCORE)) elif options.filename_style == "hyphen": code_gen.set_file_name_manager(get_file_name_manager(FileNameStyle.HYPHEN)) code_gen.create_code(root_elem) exit(0)
ThomasBollmeier/GObjectCreator2
src/bin/gobject_creator2.py
Python
gpl-3.0
10,957
import json import os import random import string import time from datetime import datetime from tempfile import TemporaryDirectory from django.test import testcases from rest_framework import status from desecapi.replication import Repository from desecapi.tests.base import DesecTestCase class ReplicationTest(DesecTestCase): def test_serials(self): url = self.reverse('v1:serial') zones = [ {'name': 'test.example.', 'edited_serial': 12345}, {'name': 'example.org.', 'edited_serial': 54321}, ] serials = {zone['name']: zone['edited_serial'] for zone in zones} pdns_requests = [{ 'method': 'GET', 'uri': self.get_full_pdns_url(r'/zones', ns='MASTER'), 'status': 200, 'body': json.dumps(zones), }] # Run twice to make sure cache output varies on remote address for i in range(2): response = self.client.get(path=url, REMOTE_ADDR='123.8.0.2') self.assertStatus(response, status.HTTP_401_UNAUTHORIZED) with self.assertPdnsRequests(pdns_requests): response = self.client.get(path=url, REMOTE_ADDR='10.8.0.2') self.assertStatus(response, status.HTTP_200_OK) self.assertEqual(response.data, serials) # Do not expect pdns request in next iteration (result will be cached) pdns_requests = [] class RepositoryTest(testcases.TestCase): def assertGit(self, path): self.assertTrue( os.path.exists(os.path.join(path, '.git')), f'Expected a git repository at {path} but did not find .git subdirectory.' ) def assertHead(self, repo, message=None, sha=None): actual_sha, actual_message = repo.get_head() if actual_sha is None: self.fail(f'Expected HEAD to have commit message "{message}" and hash "{sha}", but repository has no ' f'commits.') if sha: self.assertEqual(actual_sha, sha, f'Expected HEAD to have hash "{sha}" but had "{actual_sha}".') if message: self.assertIn( message, actual_message, f'Expected "{message}" to appear in the last commit message, but only found "{actual_message}".', ) def assertHasCommit(self, repo: Repository, commit_id): self.assertIsNotNone( repo.get_commit(commit_id)[0], f'Expected repository to have commit {commit_id}, but it had not.' ) def assertHasCommits(self, repo: Repository, commit_id_list): for commit in commit_id_list: self.assertHasCommit(repo, commit) def assertHasNotCommit(self, repo: Repository, commit_id): self.assertIsNone( repo.get_commit(commit_id)[0], f'Expected repository to not have commit {commit_id}, but it had.' ) def assertHasNotCommits(self, repo: Repository, commit_id_list): for commit in commit_id_list: self.assertHasNotCommit(repo, commit) def assertNoCommits(self, repo: Repository): head = repo.get_head() self.assertEqual(head, (None, None), f'Expected that repository has no commits, but HEAD was {head}.') @staticmethod def _random_string(length): return ''.join(random.choices(string.ascii_lowercase, k=length)) def _random_commit(self, repo: Repository, message=''): with open(os.path.join(repo.path, self._random_string(16)), 'w') as f: f.write(self._random_string(500)) repo.commit_all(message) return repo.get_head()[0] def _random_commits(self, num, repo: Repository, message=''): return [self._random_commit(repo, message) for _ in range(num)] def test_init(self): with TemporaryDirectory() as path: repo = Repository(path) repo.init() self.assertGit(path) def test_commit(self): with TemporaryDirectory() as path: repo = Repository(path) repo.init() repo.commit_all('commit1') self.assertNoCommits(repo) with open(os.path.join(path, 'test_commit'), 'w') as f: f.write('foo') repo.commit_all('commit2') self.assertHead(repo, message='commit2') def test_remove_history(self): with TemporaryDirectory() as path: repo = Repository(path) repo.init() remove = self._random_commits(5, repo, 'to be removed') # we're going to remove these 'old' commits keep = self._random_commits(1, repo, 'anchor to be kept') # as sync anchor, the last 'old' commit is kept cutoff = datetime.now() time.sleep(1) keep += self._random_commits(5, repo, 'to be kept') # we're going to keep these 'new' commits self.assertHasCommits(repo, remove + keep) repo.remove_history(before=cutoff) self.assertHasCommits(repo, keep) self.assertHasNotCommits(repo, remove)
desec-io/desec-stack
api/desecapi/tests/test_replication.py
Python
mit
5,066
#!/usr/bin/env python # -*- coding: utf-8 -*- import Folder def dup_filter(children): # childrenと同じ物だけを集めるフィルタ def _filter(item): return set(item['children']) == set(children) return _filter def find_duplicates(needle, list): # listからneedle(フォルダ)の子供と同じ子供をもつフォルダを集める # 子供と一致するかを判断するフィルタを作る child_filter = dup_filter(Folder.getChildren(needle)) # 一覧から一致する物だけを集める filtered = filter(child_filter, list) # pathだけをdupに格納する dup = map(Folder.getPath, filtered) needle['dup'] = dup return needle def collect_duplicates(list, all): # 各フォルダに対し,重複するフォルダを集める def find_duplicate(item): return find_duplicates(item, all) found = map(find_duplicate, list) return found
peccu/find-duplicates-from-bookmarks.plist
findDuplicator.py
Python
mit
902
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'GraphType' db.create_table('skwissh_graphtype', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)), ('options', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('date_created', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2012, 9, 9, 0, 0), auto_now_add=True, null=True, blank=True)), ('date_modified', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2012, 9, 9, 0, 0), auto_now=True, null=True, blank=True)), )) db.send_create_signal('skwissh', ['GraphType']) # Adding model 'Probe' db.create_table('skwissh_probe', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('display_name', self.gf('django.db.models.fields.CharField')(max_length=255)), ('addon_name', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)), ('ssh_command', self.gf('django.db.models.fields.TextField')()), ('use_sudo', self.gf('django.db.models.fields.BooleanField')(default=False)), ('python_parse', self.gf('django.db.models.fields.TextField')(default='output = output', null=True, blank=True)), ('graph_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['skwissh.GraphType'])), ('probe_unit', self.gf('django.db.models.fields.CharField')(max_length=10, null=True, blank=True)), ('probe_labels', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)), ('date_created', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2012, 9, 9, 0, 0), auto_now_add=True, null=True, blank=True)), ('date_modified', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2012, 9, 9, 0, 0), auto_now=True, null=True, blank=True)), )) db.send_create_signal('skwissh', ['Probe']) # Adding model 'Server' db.create_table('skwissh_server', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('hostname', self.gf('django.db.models.fields.CharField')(max_length=255)), ('ip', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)), ('state', self.gf('django.db.models.fields.BooleanField')(default=False)), ('is_measuring', self.gf('django.db.models.fields.BooleanField')(default=False)), ('username', self.gf('django.db.models.fields.CharField')(default='', max_length=50, blank=True)), ('password', self.gf('skwissh.fields.EncryptedCharField')(default='', max_length=50, blank=True)), ('date_created', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2012, 9, 9, 0, 0), auto_now_add=True, null=True, blank=True)), ('date_modified', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2012, 9, 9, 0, 0), auto_now=True, null=True, blank=True)), )) db.send_create_signal('skwissh', ['Server']) # Adding M2M table for field probes on 'Server' db.create_table('skwissh_server_probes', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('server', models.ForeignKey(orm['skwissh.server'], null=False)), ('probe', models.ForeignKey(orm['skwissh.probe'], null=False)) )) db.create_unique('skwissh_server_probes', ['server_id', 'probe_id']) # Adding model 'ServerGroup' db.create_table('skwissh_servergroup', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=255)), ('date_created', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2012, 9, 9, 0, 0), auto_now_add=True, null=True, blank=True)), ('date_modified', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2012, 9, 9, 0, 0), auto_now=True, null=True, blank=True)), )) db.send_create_signal('skwissh', ['ServerGroup']) # Adding M2M table for field servers on 'ServerGroup' db.create_table('skwissh_servergroup_servers', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('servergroup', models.ForeignKey(orm['skwissh.servergroup'], null=False)), ('server', models.ForeignKey(orm['skwissh.server'], null=False)) )) db.create_unique('skwissh_servergroup_servers', ['servergroup_id', 'server_id']) # Adding model 'Measure' db.create_table('skwissh_measure', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('timestamp', self.gf('django.db.models.fields.DateTimeField')()), ('server', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['skwissh.Server'])), ('probe', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['skwissh.Probe'])), ('value', self.gf('django.db.models.fields.CharField')(max_length=4096)), )) db.send_create_signal('skwissh', ['Measure']) # Adding model 'MeasureDay' db.create_table('skwissh_measureday', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('timestamp', self.gf('django.db.models.fields.DateTimeField')()), ('server', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['skwissh.Server'])), ('probe', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['skwissh.Probe'])), ('value', self.gf('django.db.models.fields.CharField')(max_length=4096)), )) db.send_create_signal('skwissh', ['MeasureDay']) # Adding model 'MeasureWeek' db.create_table('skwissh_measureweek', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('timestamp', self.gf('django.db.models.fields.DateTimeField')()), ('server', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['skwissh.Server'])), ('probe', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['skwissh.Probe'])), ('value', self.gf('django.db.models.fields.CharField')(max_length=4096)), )) db.send_create_signal('skwissh', ['MeasureWeek']) # Adding model 'MeasureMonth' db.create_table('skwissh_measuremonth', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('timestamp', self.gf('django.db.models.fields.DateTimeField')()), ('server', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['skwissh.Server'])), ('probe', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['skwissh.Probe'])), ('value', self.gf('django.db.models.fields.CharField')(max_length=4096)), )) db.send_create_signal('skwissh', ['MeasureMonth']) # Adding model 'CronLog' db.create_table('skwissh_cronlog', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('timestamp', self.gf('django.db.models.fields.DateTimeField')()), ('action', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)), ('server', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['skwissh.Server'], null=True)), ('success', self.gf('django.db.models.fields.BooleanField')(default=False)), ('message', self.gf('django.db.models.fields.TextField')(default='', null=True)), ('duration', self.gf('django.db.models.fields.FloatField')(default=0)), )) db.send_create_signal('skwissh', ['CronLog']) def backwards(self, orm): # Deleting model 'GraphType' db.delete_table('skwissh_graphtype') # Deleting model 'Probe' db.delete_table('skwissh_probe') # Deleting model 'Server' db.delete_table('skwissh_server') # Removing M2M table for field probes on 'Server' db.delete_table('skwissh_server_probes') # Deleting model 'ServerGroup' db.delete_table('skwissh_servergroup') # Removing M2M table for field servers on 'ServerGroup' db.delete_table('skwissh_servergroup_servers') # Deleting model 'Measure' db.delete_table('skwissh_measure') # Deleting model 'MeasureDay' db.delete_table('skwissh_measureday') # Deleting model 'MeasureWeek' db.delete_table('skwissh_measureweek') # Deleting model 'MeasureMonth' db.delete_table('skwissh_measuremonth') # Deleting model 'CronLog' db.delete_table('skwissh_cronlog') models = { 'skwissh.cronlog': { 'Meta': {'ordering': "['-timestamp', '-server', '-action']", 'object_name': 'CronLog'}, 'action': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'duration': ('django.db.models.fields.FloatField', [], {'default': '0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.TextField', [], {'default': "''", 'null': 'True'}), 'server': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['skwissh.Server']", 'null': 'True'}), 'success': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {}) }, 'skwissh.graphtype': { 'Meta': {'ordering': "['name']", 'object_name': 'GraphType'}, 'date_created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 9, 9, 0, 0)', 'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'date_modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 9, 9, 0, 0)', 'auto_now': 'True', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'options': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}) }, 'skwissh.measure': { 'Meta': {'ordering': "['-timestamp', 'server', 'probe']", 'object_name': 'Measure'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'probe': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['skwissh.Probe']"}), 'server': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['skwissh.Server']"}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '4096'}) }, 'skwissh.measureday': { 'Meta': {'ordering': "['-timestamp', 'server', 'probe']", 'object_name': 'MeasureDay'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'probe': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['skwissh.Probe']"}), 'server': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['skwissh.Server']"}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '4096'}) }, 'skwissh.measuremonth': { 'Meta': {'ordering': "['-timestamp', 'server', 'probe']", 'object_name': 'MeasureMonth'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'probe': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['skwissh.Probe']"}), 'server': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['skwissh.Server']"}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '4096'}) }, 'skwissh.measureweek': { 'Meta': {'ordering': "['-timestamp', 'server', 'probe']", 'object_name': 'MeasureWeek'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'probe': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['skwissh.Probe']"}), 'server': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['skwissh.Server']"}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {}), 'value': ('django.db.models.fields.CharField', [], {'max_length': '4096'}) }, 'skwissh.probe': { 'Meta': {'ordering': "['display_name', 'addon_name']", 'object_name': 'Probe'}, 'addon_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'date_created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 9, 9, 0, 0)', 'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'date_modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 9, 9, 0, 0)', 'auto_now': 'True', 'null': 'True', 'blank': 'True'}), 'display_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'graph_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['skwissh.GraphType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'probe_labels': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'probe_unit': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'python_parse': ('django.db.models.fields.TextField', [], {'default': "'output = output'", 'null': 'True', 'blank': 'True'}), 'ssh_command': ('django.db.models.fields.TextField', [], {}), 'use_sudo': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, 'skwissh.server': { 'Meta': {'ordering': "['hostname', 'ip']", 'object_name': 'Server'}, 'date_created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 9, 9, 0, 0)', 'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'date_modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 9, 9, 0, 0)', 'auto_now': 'True', 'null': 'True', 'blank': 'True'}), 'hostname': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'is_measuring': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'password': ('skwissh.fields.EncryptedCharField', [], {'default': "''", 'max_length': '50', 'blank': 'True'}), 'probes': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['skwissh.Probe']", 'null': 'True', 'blank': 'True'}), 'state': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'username': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '50', 'blank': 'True'}) }, 'skwissh.servergroup': { 'Meta': {'ordering': "['name']", 'object_name': 'ServerGroup'}, 'date_created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 9, 9, 0, 0)', 'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'date_modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 9, 9, 0, 0)', 'auto_now': 'True', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'servers': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['skwissh.Server']", 'null': 'True', 'blank': 'True'}) } } complete_apps = ['skwissh']
weijia/django-skwissh
skwissh/migrations/0001_initial.py
Python
gpl-3.0
17,013
import re from .base import FIELD_TYPE from django.db.backends import BaseDatabaseIntrospection, FieldInfo foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)") class DatabaseIntrospection(BaseDatabaseIntrospection): data_types_reverse = { FIELD_TYPE.BLOB: 'TextField', FIELD_TYPE.CHAR: 'CharField', FIELD_TYPE.DECIMAL: 'DecimalField', FIELD_TYPE.NEWDECIMAL: 'DecimalField', FIELD_TYPE.DATE: 'DateField', FIELD_TYPE.DATETIME: 'DateTimeField', FIELD_TYPE.DOUBLE: 'FloatField', FIELD_TYPE.FLOAT: 'FloatField', FIELD_TYPE.INT24: 'IntegerField', FIELD_TYPE.LONG: 'IntegerField', FIELD_TYPE.LONGLONG: 'BigIntegerField', FIELD_TYPE.SHORT: 'IntegerField', FIELD_TYPE.STRING: 'CharField', FIELD_TYPE.TIME: 'TimeField', FIELD_TYPE.TIMESTAMP: 'DateTimeField', FIELD_TYPE.TINY: 'IntegerField', FIELD_TYPE.TINY_BLOB: 'TextField', FIELD_TYPE.MEDIUM_BLOB: 'TextField', FIELD_TYPE.LONG_BLOB: 'TextField', FIELD_TYPE.VAR_STRING: 'CharField', } def get_table_list(self, cursor): "Returns a list of table names in the current database." cursor.execute("SHOW TABLES") return [row[0] for row in cursor.fetchall()] def get_table_description(self, cursor, table_name): """ Returns a description of the table, with the DB-API cursor.description interface." """ # varchar length returned by cursor.description is an internal length, # not visible length (#5725), use information_schema database to fix this cursor.execute(""" SELECT column_name, character_maximum_length FROM information_schema.columns WHERE table_name = %s AND table_schema = DATABASE() AND character_maximum_length IS NOT NULL""", [table_name]) length_map = dict(cursor.fetchall()) cursor.execute("SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name)) return [FieldInfo(*(line[:3] + (length_map.get(line[0], line[3]),) + line[4:])) for line in cursor.description] def _name_to_index(self, cursor, table_name): """ Returns a dictionary of {field_name: field_index} for the given table. Indexes are 0-based. """ return dict([(d[0], i) for i, d in enumerate(self.get_table_description(cursor, table_name))]) def get_relations(self, cursor, table_name): """ Returns a dictionary of {field_index: (field_index_other_table, other_table)} representing all relationships to the given table. Indexes are 0-based. """ my_field_dict = self._name_to_index(cursor, table_name) constraints = self.get_key_columns(cursor, table_name) relations = {} for my_fieldname, other_table, other_field in constraints: other_field_index = self._name_to_index(cursor, other_table)[other_field] my_field_index = my_field_dict[my_fieldname] relations[my_field_index] = (other_field_index, other_table) return relations def get_key_columns(self, cursor, table_name): """ Returns a list of (column_name, referenced_table_name, referenced_column_name) for all key columns in given table. """ key_columns = [] cursor.execute(""" SELECT column_name, referenced_table_name, referenced_column_name FROM information_schema.key_column_usage WHERE table_name = %s AND table_schema = DATABASE() AND referenced_table_name IS NOT NULL AND referenced_column_name IS NOT NULL""", [table_name]) key_columns.extend(cursor.fetchall()) return key_columns def get_indexes(self, cursor, table_name): cursor.execute("SHOW INDEX FROM %s" % self.connection.ops.quote_name(table_name)) # Do a two-pass search for indexes: on first pass check which indexes # are multicolumn, on second pass check which single-column indexes # are present. rows = list(cursor.fetchall()) multicol_indexes = set() for row in rows: if row[3] > 1: multicol_indexes.add(row[2]) indexes = {} for row in rows: if row[2] in multicol_indexes: continue indexes[row[4]] = {'primary_key': (row[2] == 'PRIMARY'), 'unique': not bool(row[1])} return indexes
mammique/django
django/db/backends/mysql/introspection.py
Python
bsd-3-clause
4,591
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Portal Sale', 'version': '0.1', 'category': 'Tools', 'complexity': 'easy', 'description': """ This module adds a Sales menu to your portal as soon as sale and portal are installed. ====================================================================================== After installing this module, portal users will be able to access their own documents via the following menus: - Quotations - Sale Orders - Delivery Orders - Products (public ones) - Invoices - Payments/Refunds If online payment acquirers are configured, portal users will also be given the opportunity to pay online on their Sale Orders and Invoices that are not paid yet. Paypal is included by default, you simply need to configure a Paypal account in the Accounting/Invoicing settings. """, 'depends': ['sale', 'portal', 'payment'], 'data': [ 'security/portal_security.xml', 'portal_sale_view.xml', 'portal_sale_data.xml', 'security/ir.model.access.csv', ], 'auto_install': True, 'category': 'Hidden', }
minhphung171093/GreenERP_V9
openerp/addons/portal_sale/__openerp__.py
Python
gpl-3.0
1,178
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin class OpenCL(Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin): """OpenCL """ plugin_name = 'opencl' profiles = ('hardware', 'desktop', 'gpu') files = ('/usr/bin/clinfo',) def setup(self): self.add_cmd_output([ "clinfo", ]) # vim: set et ts=4 sw=4 :
pierg75/pier-sosreport
sos/plugins/opencl.py
Python
gpl-2.0
1,083
from Q5 import price2 """ " question 6 """ print("price2 = " + str(price2(3.0, +0.02, +0.05, -0.05, 100.0, lambda x : max(x - 95.0, 0))))
rpereira-dev/ENSIIE
UE/S2/Projet/Mathematiques/code/Q6.py
Python
gpl-3.0
140
d = { 'book': ['bouk', 'boook', 'boock'], 'apple': ['aple', 'appl'], } t = 'I and my brother, have a boook about appl.' t = t.replace(',', ' ') t = t.replace('.', ' ') t = t.replace('?', ' ') t = t.replace('!', ' ') words = t.split(' ') t2 = '' for w in words: # w in d # w in d.keys() if w == '': continue correct_word = w for k, v in d.items(): if w in v: correct_word = k t2 += correct_word + ' ' # a = [1, 23, 8, -1, 5] # minimum = a[0] # for x in a: # if x < minimum: # minimum = x
amiraliakbari/sharif-mabani-python
by-session/ta-932/j6/spell_checker.py
Python
mit
620
# Tuples - ordered set of data t1 = 'a', 'b', 'c' t2 = ('a', 'b', 'c') print(t1, t2) print(t1 == t2) # True - equals
matiishyn/py-learning
3-sequence-types/5-tuples.py
Python
mit
123
# -*- coding:utf-8 -*- # !/usr/bin/python2 #将得出的矩阵转化为topic import pandas as pd from MedicineSCI.InterfaceSQL import MSSQL def theta2subset(theta_path, topic_num): df = pd.read_csv(filepath_or_buffer=theta_path, sep='\t', header=None, names=range(1, topic_num+1), index_col=False) article_topic = df.idxmax(axis=1) # 每篇文献属于的主题 file = open("topic_doucment_list.txt",'w') for i in range(1, topic_num+1): lis = list(article_topic[article_topic == i].index + 1) new_lis = [lis[j]+7120 for j in range(0,lis.__len__())]#需要调整 file.write("topic"+str(i)+"="+str(new_lis)+"\n") def phi2subset(phi_path, topic_num): df = pd.read_csv(filepath_or_buffer=phi_path, sep='\t', header=None, index_col=False) df = df.T article_topic = df.idxmax(axis=1) # 每篇文献属于的主题 file = open("topic_word_list_in_word.txt", 'w') index_word_file = open("termList.txt") wordlist = [] #保存 index - word for line in index_word_file: word = line.strip().split(" [")[0] #只取word wordlist.append(word) print wordlist.__len__() # MH_file = open("MH_word.txt",'w') ms = MSSQL(host="localhost:59318", user="eachen", pwd="123456", db="mydata") resultList = ms.ExecQuery("SELECT MH FROM MeshStructure") word_in_list = [] for (MH,) in resultList: word_in_list.append(str(MH)) # MH_file.write(str(MH)+"\n") for i in range(0, topic_num): lis = list(article_topic[article_topic == i].index) lis_word = [wordlist[j] for j in lis] lis_in_word = list(set(lis_word).intersection(set(word_in_list))) # file.write("topic"+str(i+1)+":"+str(lis_word)+"\n") file.write("topic"+str(i+1)+"="+str(lis_in_word)+"\n") theta2subset("lda_1000.theta", 10) phi2subset("lda_1000.phi", 10)
EachenKuang/PythonRepository
MedicineSCI/Tools/matric2topic.py
Python
apache-2.0
1,870
#!/usr/bin/env python ## ## ari ## ## the realraum audience response indicator ## ## ## Copyright (C) 2015 Christian Pointner <[email protected]> ## ## This file is part of ari. ## ## ari 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 ## any later version. ## ## ari 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 ari. If not, see <http://www.gnu.org/licenses/>. ## import sys import getopt import gi gi.require_version('Gst', '1.0') from gi.repository import Gst, GObject class R3Ari(): def __init__(self): GObject.threads_init() Gst.init(None) self.mainloop_ = GObject.MainLoop() self.pipeline_ = None self.watch_id_ = None self.video_width_ = 640 self.video_height_ = 480 self.meter_width_ = 560 self.meter_height_ = 23 self.meter_spacing_ = 7 self.l = 0.3 self.r = 0.7 def error(self, message, arg=None): print "ERROR: %s (%s)" % (message, arg) def on_message(self, bus, message): s = message.get_structure() if s.get_name() == 'level': sys.stdout.write("\r") for i in range(0, len(s['peak'])): decay = clamp(s['decay'][i], -90.0, 0.0) peak = clamp(s['peak'][i], -90.0, 0.0) # if peak > decay: # print "ERROR: peak bigger than decay!" sys.stdout.write("channel %d: %3.2f / %3.2f, " % (i, decay, peak)) sys.stdout.flush() return True def run(self): try: s = 'videotestsrc is-live=true !xvimagesink' % () self.pipeline_ = Gst.Pipeline.new() source = Gst.ElementFactory.make("videotestsrc") source.set_property("is-live", True) self.pipeline_.add(source) filter = Gst.ElementFactory.make("capsfilter") caps = Gst.Caps.from_string("video/x-raw,format=I420,width=%i,height=%i,framerate=50/1" % (self.video_width_, self.video_height_)) filter.set_property("caps", caps) self.pipeline_.add(filter) conv1 = Gst.ElementFactory.make("videoconvert") self.pipeline_.add(conv1) q1 = Gst.ElementFactory.make("queue") self.pipeline_.add(q1) overlay = Gst.ElementFactory.make("rsvgoverlay") overlay.set_property("data", self.getVumeterSVG(0, 0, 0, 0)) self.pipeline_.add(overlay) GObject.timeout_add(20, self.updateMeter, overlay) conv2 = Gst.ElementFactory.make("videoconvert") self.pipeline_.add(conv2) sink = Gst.ElementFactory.make("xvimagesink") self.pipeline_.add(sink) source.link(filter) filter.link(q1) q1.link(conv1) conv1.link(overlay) overlay.link(conv2) conv2.link(sink) self.pipeline_.get_bus().add_signal_watch() self.watch_id_ = self.pipeline_.get_bus().connect('message::element', self.on_message) self.pipeline_.set_state(Gst.State.PLAYING) self.mainloop_.run() except GObject.GError, e: self.error('Could not create pipeline', e.message) except KeyboardInterrupt: pass finally: if self.pipeline_ and self.watch_id_: self.pipeline_.get_bus().disconnect(self.watch_id_) self.pipeline_.get_bus().remove_signal_watch() self.pipeline_.set_state(Gst.State.NULL) def getVumeterSVG(self, l, lp, r, rp): svg = "<svg>\n" svg += " <defs>\n" svg += " <linearGradient id='vumeter' x1='0%' y1='0%' x2='100%' y2='0%'>\n" svg += " <stop offset='0%' style='stop-color:rgb(0,255,0);stop-opacity:1' />\n" svg += " <stop offset='100%' style='stop-color:rgb(255,0,0);stop-opacity:1' />\n" svg += " </linearGradient>\n" svg += " </defs>\n" box_w = self.meter_width_ + 2*self.meter_spacing_ box_h = 2*self.meter_height_ + 3*self.meter_spacing_ box_x = (self.video_width_ - box_w)/2 box_y = self.meter_spacing_ svg += " <rect x='%i' y='%i' rx='%i' ry='%i' width='%i' height='%i' style='fill:black;opacity:0.3' />\n" %( box_x, box_y, self.meter_spacing_, self.meter_spacing_, box_w, box_h) svg += " <rect x='%i' y='%i' width='%i' height='%i' style='fill:url(#vumeter);opacity:0.9' />\n" %( box_x + self.meter_spacing_, box_y + self.meter_spacing_, self.meter_width_*l, self.meter_height_) svg += " <line x1='%i' y1='%i' x2='%i' y2='%i' style='stroke:rgb(255,0,0);stroke-width:3' />\n" %( box_x + self.meter_width_*lp, box_y + self.meter_spacing_, box_x + self.meter_width_*lp, box_y + self.meter_spacing_ + self.meter_height_) svg += " <rect x='%i' y='%i' width='%i' height='%i' style='fill:url(#vumeter);opacity:0.9' />\n" %( box_x + self.meter_spacing_, box_y + self.meter_height_ + 2*self.meter_spacing_, self.meter_width_*r, self.meter_height_) svg += " <line x1='%i' y1='%i' x2='%i' y2='%i' style='stroke:rgb(255,0,0);stroke-width:3' />\n" %( box_x + self.meter_width_*rp, box_y + self.meter_height_ + 2*self.meter_spacing_, box_x + self.meter_width_*rp, box_y + 2*self.meter_spacing_ + 2*self.meter_height_) svg += "</svg>\n" return svg def updateMeter(self, overlay): self.l += 0.01 if self.l > 0.9: self.l = 0.0 lp = self.l + 0.1 self.r += 0.01 if self.r > 0.9: self.r = 0.0 rp = self.r + 0.1 overlay.set_property("data", self.getVumeterSVG(self.l, lp, self.r, rp)) return True if __name__ == '__main__': a = R3Ari() a.run()
realraum/ari
test/overlay-test.py
Python
gpl-3.0
6,283
"""An image processing pipeline stage which divides the image into segments.""" import cv import itertools __author__ = "Nick Pascucci ([email protected])" class ShotgunSegmentationPipe: """An implementation of a simple flood fill image segmentor. This pipe can be used to simplify an image before other processing steps are applied; this is useful, for example, to improve the output of a detector. It works by initiating a flood fill at multiple points in the image, and filling those regions with the color of the starting pixel.""" def __init__(self, next_pipe): self.next_pipe = next_pipe def process(self, image, x_points=8, y_points=6, max_difference=(1, 3, 3, 0), passes=1): # First, select the points we want. We should have x_points*y_points of # them, as they're the cross product of the x and y values. x_vals = [int((i + 0.5) * (image.width/x_points)) for i in range(x_points)] y_vals = [int((i + 0.5) * (image.height/y_points)) for i in range(y_points)] coordinates = list(itertools.product(x_vals, y_vals)) for i in range(15): cv.Smooth(image, image) for i in range(passes): for coordinate in coordinates: x, y = coordinate # Remember, cv array access is wonky color = image[y, x] b, g, r = color cv.FloodFill(image, coordinate, color, max_difference, max_difference) if self.next_pipe: processed_image = self.next_pipe.process(image) return processed_image else: return image
nickpascucci/RobotCamera
src/driver/modules/pipelines/segmentationpipe.py
Python
gpl-3.0
1,719
# This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. from flask.globals import (_request_ctx_stack, current_app, # noqa request, session, g, LocalProxy, _find_app) from flask.ext.login import current_user # noqa def _find_cache(): """ The application context will be automatically handled by _find_app method in flask """ app = _find_app() return app.cache def _get_locale(): Locale = current_app.pool.get('nereid.website.locale') locale_id = getattr(_request_ctx_stack.top, 'locale', None) if locale_id is None: locale_id = _set_locale() return Locale(locale_id) def _set_locale(): website = _get_website() locale = website.get_current_locale(_request_ctx_stack.top.request) _request_ctx_stack.top.locale = locale.id return locale.id def _get_website(): Website = current_app.pool.get('nereid.website') website_id = getattr(_request_ctx_stack.top, 'website', None) if website_id is None: website_id = _set_website() return Website(website_id) def _set_website(): Website = current_app.pool.get('nereid.website') website = Website.get_from_host(_request_ctx_stack.top.request.host) _request_ctx_stack.top.website = website.id return website.id cache = LocalProxy(_find_cache) current_locale = LocalProxy(lambda: _get_locale()) current_website = LocalProxy(lambda: _get_website())
fulfilio/nereid
nereid/globals.py
Python
bsd-3-clause
1,520
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP # Copyright 2016 FUJITSU LIMITED # 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 import monascastatsd from monasca_common.simport import simport from monasca_notification.common.repositories import exceptions from monasca_notification.notification import Notification log = logging.getLogger(__name__) NOTIFICATION_DIMENSIONS = {'service': 'monitoring', 'component': 'monasca-notification'} def get_db_repo(config): if 'database' in config and 'repo_driver' in config['database']: return simport.load(config['database']['repo_driver'])(config) else: return simport.load('monasca_notification.common.repositories.mysql.mysql_repo:MysqlRepo')(config) def construct_notification_object(db_repo, notification_json): try: notification = Notification(notification_json['id'], notification_json['type'], notification_json['name'], notification_json['address'], notification_json['period'], notification_json['retry_count'], notification_json['raw_alarm']) # Grab notification method from database to see if it was changed stored_notification = grab_stored_notification_method(db_repo, notification.id) # Notification method was deleted if stored_notification is None: log.debug("Notification method {0} was deleted from database. " "Will stop sending.".format(notification.id)) return None # Update notification method with most up to date values else: notification.name = stored_notification[0] notification.type = stored_notification[1] notification.address = stored_notification[2] notification.period = stored_notification[3] return notification except exceptions.DatabaseException: log.warn("Error querying mysql for notification method. " "Using currently cached method.") return notification except Exception as e: log.warn("Error when attempting to construct notification {0}".format(e)) return None def grab_stored_notification_method(db_repo, notification_id): try: stored_notification = db_repo.get_notification(notification_id) except exceptions.DatabaseException: log.debug('Database Error. Attempting reconnect') stored_notification = db_repo.get_notification(notification_id) return stored_notification
sapcc/monasca-notification
monasca_notification/common/utils.py
Python
apache-2.0
3,246
import psycopg2 as dbapi2 import datetime from classes.model_config import dsn class project_operations: def __init__(self): self.last_key = None def add_project(self, Project): with dbapi2.connect(dsn) as connection: cursor = connection.cursor() cursor.execute( "INSERT INTO Project(Name, Description, ProjectTypeId, ProjectThesisTypeId, DepartmentId, ProjectStatusTypeId, StartDate, EndDate, MemberLimit, CreatedByPersonId, ProjectManagerId, Deleted) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, False )", (Project.title, Project.project_description, Project.project_type, Project.project_thesis_type, Project.department, Project.project_status_type, Project.start_date, Project.end_date, Project.member_limit, Project.created_by, Project.manager)) connection.commit() self.last_key = cursor.lastrowid def delete_project(self, key): with dbapi2.connect(dsn) as connection: cursor = connection.cursor() cursor.execute("""DELETE FROM Project WHERE (ObjectId=%s)""", (key,)) connection.commit() def update_project(self, key, title, project_description, end_date, member_limit, manager, deleted): with dbapi2.connect(dsn) as connection: cursor = connection.cursor() cursor.execute( """UPDATE Project SET Name = %s, Description = %s, EndDate = %s, MemberLimit = %s, ProjectManagerId = %s, Deleted = %s WHERE (ObjectId=%s)""", (title, project_description, end_date, member_limit, manager, deleted, key)) connection.commit() def get_project(self, key): with dbapi2.connect(dsn) as connection: cursor = connection.cursor() query = """SELECT Project.Name, Project.Description, ProjectType.Name, Department.Name, ProjectStatusType.Name, Person.FirstName, Person.LastName, Project.ObjectId, Project.CreatedByPersonId, Project.EndDate, Project.MemberLimit FROM Project JOIN ProjectType ON(Project.ProjectTypeId=ProjectType.ObjectId) JOIN Department ON(Project.DepartmentId = Department.ObjectId) JOIN ProjectStatusType ON(Project.ProjectStatusTypeId=ProjectStatusType.ObjectId) JOIN Person ON(Project.CreatedByPersonId=Person.ObjectId) WHERE (Project.ObjectID = %s)""" cursor.execute(query, (key,)) project = cursor.fetchone() connection.commit() return project def get_projects(self): with dbapi2.connect(dsn) as connection: cursor = connection.cursor() cursor.execute("""SELECT Project.ObjectId, Project.Name, Description, Department.Name, Person.FirstName, Person.LastName FROM Project JOIN Department ON(Project.DepartmentId = Department.ObjectId) JOIN Person ON(Person.ObjectId = Project.ProjectManagerId)""") projects = cursor.fetchall() connection.commit() return projects def get_project_member_limit(self, key): with dbapi2.connect(dsn) as connection: cursor = connection.cursor() cursor.execute("""SELECT MemberLimit FROM Project WHERE (ObjectId=%s)""", (key,)) projects = cursor.fetchall() connection.commit() return projects def get_the_projects_of_a_person(self, key): with dbapi2.connect(dsn) as connection: cursor = connection.cursor() query = """SELECT Project.Name, Project.Description, ProjectType.Name, Project.ObjectId FROM Project JOIN ProjectType ON(Project.ProjectTypeId=ProjectType.ObjectId) JOIN Team ON(Project.ObjectId = Team.ProjectId) WHERE (Team.MemberId = %s)""" cursor.execute(query, (key,)) project_ids = cursor.fetchall() connection.commit() return project_ids def get_last(self): with dbapi2.connect(dsn) as connection: cursor = connection.cursor() cursor.execute("""SELECT ObjectId FROM Project Order By ObjectId Desc LIMIT 1""") projectId = cursor.fetchone() connection.commit() return projectId
itucsdb1611/itucsdb1611
classes/operations/project_operations.py
Python
gpl-3.0
4,444
from textblob import TextBlob # From http://www.ling.upenn.edu/courses/Fall_2007/ling001/penn_treebank_pos.html def name_from_tag(tag): tags = { 'CC': 'Coordinating conjunction', 'CD': 'Cardinal number', 'DT': 'Determiner', 'EX': 'Existential there', 'FW': 'Foreign word', 'IN': 'Preposition or subordinating conjunction', 'JJ': 'Adjective', 'JJR': 'Adjective, comparative', 'JJS': 'Adjective, superlative', 'LS': 'List item marker', 'MD': 'Modal', 'NN': 'Noun, singular or mass', 'NNS': 'Noun, plural', 'NNP': 'Proper noun, singular', 'NNPS': 'Proper noun, plural', 'PDT': 'Predeterminer', 'POS': 'Possessive ending', 'PRP': 'Personal pronoun', 'PRP$': 'Possessive pronoun', 'RB': 'Adverb', 'RBR': 'Adverb, comparative', 'RBS': 'Adverb, superlative', 'RP': 'Particle', 'SYM': 'Symbol', 'TO': 'to', 'UH': 'Interjection', 'VB': 'Verb, base form', 'VBD': 'Verb, past tense', 'VBG': 'Verb, gerund or present participle', 'VBN': 'Verb, past participle', 'VBP': 'Verb, non-3rd person singular present', 'VBZ': 'Verb, 3rd person singular present', 'WDT': 'Wh-determiner', 'WP': 'Wh-pronoun', 'WP$': 'Possessive wh-pronoun', 'WRB': 'Wh-adverb', } return tags.get(tag, tag) phrase = raw_input('Enter a sentence: ') if not phrase: phrase = 'The red cars drove slowly down the street' tb = TextBlob(phrase) for word, tag in tb.tags: print "%10s: %s" % (word, name_from_tag(tag))
jaden/2014-hour-of-code
python/sentence_diagramming.py
Python
mit
1,684
# # build the opening book # import os import sysconfig import sys build_lib = "lib.%s-%s" % (sysconfig.get_platform(), sysconfig.get_python_version()) pypath = os.path.join("build", build_lib, "gshogi") sys.path.append(pypath) import engine text_opening_book = "data/gnushogi.tbk" bin_opening_book = "gshogi/data/opening.bbk" booksize = 8000 bookmaxply = 40 # check input file exists if (not os.path.exists(text_opening_book)): print("Input file", text_opening_book, "not found") sys.exit() # create data folder for bin book data_folder = os.path.dirname(bin_opening_book) if not os.path.exists(data_folder): try: os.makedirs(data_folder) except OSError as exc: print("Unable to create data folder", data_folder) sys.exit() # delete the output file if it exists try: os.remove(bin_opening_book) except OSError as oe: pass # initialise the engine verbose = False engine.init(bin_opening_book, verbose) # call engine function to generate book file engine.genbook(text_opening_book, bin_opening_book, booksize, bookmaxply)
johncheetham/gshogi
create_book.py
Python
gpl-3.0
1,078
# Copyright 2014 Rustici Software # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ .. module:: base :synopsis: A base object to provide a common initializer for objects to easily keep track of required and optional properties and their error checking """ class Base(object): _props = [] def __init__(self, *args, **kwargs): """Initializes an object by checking the provided arguments against lists defined in the individual class. If required properties are defined, this method will set them to None by default. Optional properties will be ignored if they are not provided. The class may provide custom setters for properties, in which case those setters (see __setattr__ below). """ if hasattr(self, '_props_req') and self._props_req: map(lambda (k): setattr(self, k, None), self._props_req) new_kwargs = {} for obj in args: new_kwargs.update(obj if isinstance(obj, dict) else vars(obj)) new_kwargs.update(kwargs) for key, value in new_kwargs.iteritems(): setattr(self, key, value) def __setattr__(self, attr, value): """Makes sure that only allowed properties are set. This method will call the proper attribute setter as defined in the class to provide additional error checking :param attr: the attribute being set :type attr: str :param value: the value to set """ if attr.startswith('_') and attr[1:] in self._props: super(Base, self).__setattr__(attr, value) elif attr not in self._props: raise AttributeError( "Property '%s' cannot be set on a 'tincan.%s' object. Allowed properties: %s" % ( attr, self.__class__.__name__, ', '.join(self._props) )) else: super(Base, self).__setattr__(attr, value) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
brianjmiller/TinCanPython
tincan/base.py
Python
apache-2.0
2,635
import glob import re import shutil import os os.putenv('PATH', '/Applications/Mauve.app/Contents/MacOS:' + os.getenv('PATH')) SAMPLES = "sample1 sample2 sample3 sample4".split() ROOT_FOLDER = "/path/to/root/dir" REF_NAME = "reference_strain" REF = os.path.join(ROOT_FOLDER, "fasta_genomes", REF_NAME + ".fasta") rule all: input: expand("velvet/{sample}/contigs.reordered.fasta", sample=SAMPLES) rule reorder_contigs: input: ref = REF, unordered_contig = "velvet/{sample}/contigs.fa" output: "velvet/{sample}/contigs.reordered.fasta" run: shell("java -Xmx500m -cp /Applications/Mauve.app/Contents/Resources/Java/Mauve.jar org.gel.mauve.contigs.ContigOrderer -output /tmp/MCM/{wildcards.sample} -ref {input.ref} -draft {input.unordered_contig}") alignments = glob.glob("/tmp/MCM/" + wildcards.sample + "/alignment*") alignment_numbers = [int(re.search('alignment(\d+)', alignment).group(1)) for alignment in alignments] alignment_numbers.sort() shutil.copyfile("/tmp/MCM/" + wildcards.sample + "/alignment%d/contigs.fa.fas" % alignment_numbers[-1], "velvet/" + wildcards.sample + "/contigs.reordered.fasta" )
jrherr/bioinformatics_scripts
manning_lab_scripts/reorder_contigs_with_MAUVE.py
Python
mit
1,163
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('tasks', '0010_exporttaskexception'), ] operations = [ migrations.AlterField( model_name='exporttaskexception', name='exception', field=models.CharField(max_length=5000, editable=False), ), ]
hotosm/osm-export-tool2
tasks/migrations/0011_auto_20150602_1914.py
Python
bsd-3-clause
435
# Copyright 2017 Priscilla Boyd. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """The Cleaner module cleans the data by: - Taking CSV files with stage/phase information and filtering them, leaving date, time, result and phase fields. - Taking individual files for stages (with data/time and result) and merging into a single file. - Removing duplicates from the files merged. """ import os import pandas as pd from pathlib import Path from tools.Utils import create_folder_if_not_exists, output_fields, \ raw_output_folder, results_folder def filter_phase_data(): """ Filter phase data for files in raw data folder to ensure only desired fields are taken. """ print("Filtering phase data...") # path to analyse path_list = Path(raw_output_folder).glob('**/*.csv') # loop through files in the given path and store desired fields as array for path in path_list: path_in_str = str(path) file_name = os.path.basename(path_in_str) full_path = results_folder + 'phases/raw/' + file_name data = pd.read_csv(full_path, header=0, skipinitialspace=True, usecols=output_fields) df = pd.DataFrame(data) # only output to CSV those which contain some data if df.shape[0] > 0: output_folder = results_folder + 'phases/processed/' file_name = 'clean_' + file_name # ensure folder exists before creating the file create_folder_if_not_exists(output_folder) # write output to a file df.to_csv(output_folder + file_name, sep=',') print("Phase data filtered!") def combine_phase_data(): """ Combine data from processed/filtered data to a single file. """ print("Combining phase data...") # create an empty data frame out_df = pd.DataFrame([]) # loop through files in the given path and store data in df path_list = Path(results_folder + 'phases/processed/').glob('**/*.csv') for path in path_list: path_in_str = str(path) file_name = os.path.basename(path_in_str) full_path = results_folder + 'phases/processed/' + file_name data = pd.read_csv(full_path, header=0, skipinitialspace=True, usecols=output_fields) df = pd.DataFrame(data) # append a df to contain only the relevant information in ascending order out_df = df.append(out_df) out_df = out_df.sort_values(['Date', 'Time', 'Phase'], ascending=[True, True, True]) out_df.to_csv(results_folder + 'phases/raw/merged_phases.csv', sep=',') print("Data combined!") def remove_duplicates_phase_data(): """ Remove duplicates from the file (i.e. ensuring only one record per second). """ print("Removing any duplicates...") merged_phases_data = pd.read_csv(results_folder + 'phases/raw/merged_phases.csv', header=0, skipinitialspace=True, usecols=output_fields) df = pd.DataFrame(merged_phases_data) clean_df = df.drop_duplicates() clean_df.to_csv(results_folder + 'phases/processed/clean_merged_phases.csv', sep=',', index=False) print("Duplicates removed!") def clean(): """ Run data cleaning processes. """ filter_phase_data() combine_phase_data() remove_duplicates_phase_data()
priscillaboyd/SPaT_Prediction
src/preprocessing/Cleaner.py
Python
apache-2.0
3,940
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = '[email protected]' import os import logging import tornado.httpserver import tornado.ioloop import tornado.web import tornado.wsgi import sockjs.tornado from django.core.handlers import wsgi import pusher import constraint import logging as _ SETTINGS_PATH="django_tornado.settings" _H = _.StreamHandler() _F = _.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') logging = _.getLogger('') logging.setLevel(_.DEBUG) logging.addHandler(_H) _H.setFormatter(_F) def main(): wsgi_app = tornado.wsgi.WSGIContainer(wsgi.WSGIHandler()) Router = sockjs.tornado.SockJSRouter(pusher.PushClient, '/stream') Router.urls.append((r'/static/(.*)$', tornado.web.StaticFileHandler, {'path': './static'})) Router.urls.append(('.*', tornado.web.FallbackHandler, dict(fallback=wsgi_app))) logging.debug("start") ping = pusher.Pinger() ping.start() tornado_app = tornado.web.Application(Router.urls) server = tornado.httpserver.HTTPServer(tornado_app) server.listen(address=constraint.HOST, port=constraint.PORT) tornado.ioloop.IOLoop.instance().start() if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", SETTINGS_PATH) main()
vane/django_tornado
django_tornado.py
Python
bsd-3-clause
1,266
from pprint import pformat import os import sys from difflib import SequenceMatcher from .. import logs, types, const from ..conf import settings from ..corrector import get_corrected_commands from ..exceptions import EmptyCommand from ..ui import select_command from ..utils import get_alias, get_all_executables def _get_raw_command(known_args): if known_args.force_command: return known_args.force_command elif not os.environ.get('TF_HISTORY'): return known_args.command else: history = os.environ['TF_HISTORY'].split('\n')[::-1] alias = get_alias() executables = get_all_executables() for command in history: diff = SequenceMatcher(a=alias, b=command).ratio() if diff < const.DIFF_WITH_ALIAS or command in executables: return [command] def fix_command(known_args): """Fixes previous command. Used when `thefuck` called without arguments.""" settings.init(known_args) with logs.debug_time('Total'): logs.debug(u'Run with settings: {}'.format(pformat(settings))) raw_command = _get_raw_command(known_args) try: command = types.Command.from_raw_script(raw_command) except EmptyCommand: logs.debug('Empty command, nothing to do') return corrected_commands = get_corrected_commands(command) selected_command = select_command(corrected_commands) if selected_command: selected_command.run(command) else: sys.exit(1)
SimenB/thefuck
thefuck/entrypoints/fix_command.py
Python
mit
1,556
"""Test the example module auth module.""" from homeassistant import auth, data_entry_flow from homeassistant.auth.mfa_modules import auth_mfa_module_from_config from homeassistant.auth.models import Credentials from tests.common import MockUser async def test_validate(hass): """Test validating pin.""" auth_module = await auth_mfa_module_from_config( hass, { "type": "insecure_example", "data": [{"user_id": "test-user", "pin": "123456"}], }, ) result = await auth_module.async_validate("test-user", {"pin": "123456"}) assert result is True result = await auth_module.async_validate("test-user", {"pin": "invalid"}) assert result is False result = await auth_module.async_validate("invalid-user", {"pin": "123456"}) assert result is False async def test_setup_user(hass): """Test setup user.""" auth_module = await auth_mfa_module_from_config( hass, {"type": "insecure_example", "data": []} ) await auth_module.async_setup_user("test-user", {"pin": "123456"}) assert len(auth_module._data) == 1 result = await auth_module.async_validate("test-user", {"pin": "123456"}) assert result is True async def test_depose_user(hass): """Test despose user.""" auth_module = await auth_mfa_module_from_config( hass, { "type": "insecure_example", "data": [{"user_id": "test-user", "pin": "123456"}], }, ) assert len(auth_module._data) == 1 await auth_module.async_depose_user("test-user") assert len(auth_module._data) == 0 async def test_is_user_setup(hass): """Test is user setup.""" auth_module = await auth_mfa_module_from_config( hass, { "type": "insecure_example", "data": [{"user_id": "test-user", "pin": "123456"}], }, ) assert await auth_module.async_is_user_setup("test-user") is True assert await auth_module.async_is_user_setup("invalid-user") is False async def test_login(hass): """Test login flow with auth module.""" hass.auth = await auth.auth_manager_from_config( hass, [ { "type": "insecure_example", "users": [{"username": "test-user", "password": "test-pass"}], } ], [ { "type": "insecure_example", "data": [{"user_id": "mock-user", "pin": "123456"}], } ], ) user = MockUser( id="mock-user", is_owner=False, is_active=False, name="Paulus" ).add_to_auth_manager(hass.auth) await hass.auth.async_link_user( user, Credentials( id="mock-id", auth_provider_type="insecure_example", auth_provider_id=None, data={"username": "test-user"}, is_new=False, ), ) provider = hass.auth.auth_providers[0] result = await hass.auth.login_flow.async_init((provider.type, provider.id)) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.auth.login_flow.async_configure( result["flow_id"], {"username": "incorrect-user", "password": "test-pass"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"]["base"] == "invalid_auth" result = await hass.auth.login_flow.async_configure( result["flow_id"], {"username": "test-user", "password": "incorrect-pass"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"]["base"] == "invalid_auth" result = await hass.auth.login_flow.async_configure( result["flow_id"], {"username": "test-user", "password": "test-pass"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mfa" assert result["data_schema"].schema.get("pin") == str result = await hass.auth.login_flow.async_configure( result["flow_id"], {"pin": "invalid-code"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"]["base"] == "invalid_code" result = await hass.auth.login_flow.async_configure( result["flow_id"], {"pin": "123456"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"].id == "mock-id" async def test_setup_flow(hass): """Test validating pin.""" auth_module = await auth_mfa_module_from_config( hass, { "type": "insecure_example", "data": [{"user_id": "test-user", "pin": "123456"}], }, ) flow = await auth_module.async_setup_flow("new-user") result = await flow.async_step_init() assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await flow.async_step_init({"pin": "abcdefg"}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert auth_module._data[1]["user_id"] == "new-user" assert auth_module._data[1]["pin"] == "abcdefg"
jawilson/home-assistant
tests/auth/mfa_modules/test_insecure_example.py
Python
apache-2.0
5,045
# Copyright (c) 2004 by Stingray Software # For license information, read file LICENSE in project top directory # # $Id: PDU.py 63 2004-12-30 22:02:55Z stingray $ # # SMPP Protocol parser and encoder library # Misc utilities import struct def ffNumber(x): """Convert freeform number to tuple""" if not isinstance(x, tuple): ton = 0 tpi = 1 if x[0] == "+": ton = 1 x = x[1:] return (tpi, ton, x) else: return x def nnNumber(x): if isinstance(x, tuple): r = "" if x[1] == 1: r = "+" r += str(x[2]) return r else: return x def unicodify(msg): s = "" for m in msg: s += struct.pack("!H", ord(m)) return s
theraphim/ota-configurator
src/smpputil.py
Python
gpl-2.0
683
#!/usr/bin/python # -*- coding: utf-8 -*- # # This is derived from a cadquery script for generating QFP/GullWings models in X3D format. # # from https://bitbucket.org/hyOzd/freecad-macros # author hyOzd # ## file of parametric definitions def reload_lib(lib): if (sys.version_info > (3, 0)): import importlib importlib.reload(lib) else: reload (lib) import collections from collections import namedtuple import FreeCAD, Draft, FreeCADGui import ImportGui import FreeCADGui as Gui import shaderColors import exportPartToVRML as expVRML ## base parametes & model import collections from collections import namedtuple # Import cad_tools import cq_cad_tools # Reload tools from cq_cad_tools import reload_lib reload_lib(cq_cad_tools) # Explicitly load all needed functions from cq_cad_tools import FuseObjs_wColors, GetListOfObjects, restore_Main_Tools, \ exportSTEP, close_CQ_Example, exportVRML, saveFCdoc, z_RotateObject, Color_Objects, \ CutObjs_wColors, checkRequirements # Sphinx workaround #1 try: QtGui except NameError: QtGui = None # try: # Gui.SendMsgToActiveView("Run") # from Gui.Command import * Gui.activateWorkbench("CadQueryWorkbench") import cadquery cq = cadquery from Helpers import show # CadQuery Gui except: # catch *all* exceptions msg = "missing CadQuery 0.3.0 or later Module!\r\n\r\n" msg += "https://github.com/jmwright/cadquery-freecad-module/wiki\n" if QtGui is not None: reply = QtGui.QMessageBox.information(None,"Info ...",msg) # maui end #checking requirements checkRequirements(cq) class ShapeOfTerminal: r"""A class for holding constants for Shape of terminal of part .. note:: will be changed to enum when Python version allows it """ JH = 'JH' r"""JH - J-hook """ GW = 'GW' r"""GW - Gull wing """ TH = 'TH' r"""TH - Through hole pin """ THC = 'THC' r"""THC - angled THT pin with asymetrical clamping bend """ THL = 'THL' r"""THL - angled THT pin with symetrical lambda shaped clamping bend """ class ButtonType: r"""A class for holding type of button of Omron tactile switch series .. note:: will be changed to enum when Python version allows it """ FLAT = 'FLAT' r"""FLAT: Normal round button """ PROJ = 'PROJ' r"""PROJ: Projected type (round knob on square shaft) """ class ButtonRing: r"""A class defining the type of an additional ring around the button. .. note:: will be changed to enum when Python version allows it """ NONE = 'NONE' r"""NONE: No additional button """ ROUND = 'ROUND' r"""ROUND: Round button ring """ OCTA = 'OCTA' r"""OCTA: Octagon button ring """ #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * #* * class partParamsTactSwitches (): r"""Class containing the parameter for building a 3D model of a tactile switch :param params: namedtuple containing the variable parameter for building the different 3D models. :type params: ``partsTactSwitches.Params`` """ def __init__(self, params): # get all entries of the params list as dictionary args = params._asdict() self.type = params.type if 'type' in args and params.type != None else "SMD" # Defining all dimensions needed to build the model. # If a dimension is part of the given params list, this value must be used # Dimensions of plastic body self.body_height = params.body_height if 'body_height' in args and params.body_height != None else 3.75 self.body_length = params.body_length if 'body_length' in args and params.body_length != None else 6.6 # side of part where the pins are self.body_width = params.body_width if 'body_width' in args and params.body_width != None else 6.0 self.body_height_with_button = params.body_height_with_button if 'body_height_with_button' in args and params.body_height_with_button != None else 5.0 # if no distance of body to board is given with params it is set to None and will be set depending on shape of terminals self.body_board_distance = params.body_board_distance if 'body_board_distance' in args and params.body_board_distance != None else None # if case has alignment pegs 'has_pegs' must be true self.has_pegs = params.has_pegs if 'has_pegs' in args and params.has_pegs != None else False self.pegs_pitch = params.pegs_pitch if 'pegs_pitch' in args and params.pegs_pitch != None else 9.0 self.pegs_radius = params.pegs_radius if 'pegs_radius' in args and params.pegs_radius != None else 1.0 self.pegs_heigth = params.pegs_heigth if 'pegs_heigth' in args and params.pegs_heigth != None else 1.5 # Dimesion of button self.button_dia = params.button_dia if 'button_dia' in args and params.button_dia != None else 3.5 self.button_ring = params.button_ring if 'button_ring' in args and params.button_ring != None else ButtonRing.NONE self.button_ring_radius = params.button_ring_radius if 'button_ring_radius' in args and params.button_ring_radius != None else 2.35 self.button_ring_heigth = params.button_ring_heigth if 'button_ring_heigth' in args and params.button_ring_heigth != None else 1.6 self.button_ring_length = params.button_ring_length if 'button_ring_length' in args and params.button_ring_length != None else 3.7 self.button_ring_width = params.button_ring_width if 'button_ring_width' in args and params.button_ring_width != None else 3.7 # dimension of pins self.num_pins = params.num_pins if 'num_pins' in args and params.num_pins != None else 4 self.pin_pitch = params.pin_pitch if 'pin_pitch' in args and params.pin_pitch != None else 2.54 self.pin_width = params.pin_width if 'pin_width' in args and params.pin_width != None else 0.6 self.pin_thickness = params.pin_thickness if 'pin_thickness' in args and params.pin_thickness != None else 0.2 self.distance_pinTip_rows = params.distance_pinTip_rows if 'distance_pinTip_rows' in args and params.distance_pinTip_rows != None else 10.0 # distance from tip of pin from row one to row two self.num_pin_rows = params.num_pin_rows if 'num_pin_rows' in args and params.num_pin_rows != None else 2 self.top_length = params.top_length if 'top_length' in args and params.top_length != None else 0.2 # only used for J-hook and angled THT pin self.pin_length_below_body = params.pin_length_below_body if 'pin_length_below_body' in args and params.pin_length_below_body != None else 3.5 # only used for THT pin # Model variants self.terminal_shape = params.terminal_shape if 'terminal_shape' in args and params.terminal_shape != None else ShapeOfTerminal.GW # Default dimensions. These dimensions Will normally be defined in the serie specific derived class # Dimensions of pockest at bottom of plastic body self.bottom_pocket_depth = 0.1 self.pin_pocket_edge_length = 1.6 self.pin_pocket_mid_length = 1.2 self.pin_pocket_edge_width = 1.3 # Dimension of metallic cover plate self.cover_thickness = params.cover_thickness if 'cover_thickness' in args and params.cover_thickness != None else 0.3 self.cover_side_height = 2.1 self.cover_plate_with_side_sheets = False # must be true if cover of switch has side clips # for side sheets with center pocket: self.cover_side_pocket_width = 4.0 self.cover_side_pocket_heigth = 1.3 # for solid side sheets: self.cover_solid_side_width = self.body_width / 2.0 self.button_has_base_plate = False; #self. = params. if '' in args and params. != None else # Dimensions of pockest at top of plastic body # self.pocket_turn_inset_top_depth: see derived dimensions self.pocket_top_side_width = 0.45 self.pocket_top_side_depth = 0.45 # Dimensions of plastic body side pads self.pad_side_height = self.cover_side_pocket_heigth self.pad_side_width = self.cover_side_pocket_width # derived dimensions. Some depend on cover thickness. If cover thickness must be changed by a in derived classes, # these dimensions have to be adapted to the new thickness. self.button_height = self.body_height_with_button - self.body_height + self.cover_thickness # the button heigth is measured from below cover to top self.body_height_plastic = self.body_height - self.cover_thickness self.pad_side_length = self.cover_thickness # for some switches the lower part of the side clamps are not closed (Omron B3S). For these models the following parameter must be > 0.0 self.button_hole_dia = self.button_dia * 1.04 # for projected button type some more dimensions are needed self.button_proj_length_top = self.button_dia / 1.42 # sqrt (2) self.button_proj_length_mid = self.button_proj_length_top / 1.42 # sqrt (2) self.button_proj_hight_bot = self.button_height / 4.0 self.button_proj_hight_mid = self.button_height / 4.0 self.button_proj_hight_top = self.button_height / 2.0 # Call of function defining dimensions depending on the shape of terminals paramFunction = self._TerminalShapeSwitcher.get(self.terminal_shape, None) if paramFunction == None: # not a valid terminal_shape FreeCAD.Console.PrintMessage(str(self.terminal_shape) + ' not a valid member of ' + str(ShapeOfTerminal)) self.make_me = False else: # Call the funktion paramFunction (self) def paramsForJh (self): r"""set the reqired dimensions for building J-hook pins """ self.pin_bottom_length = 1.0 self.pin_height = 1.2 self.pin_top_length = 1.0 self.pin_top_radius = self.pin_thickness / 2.0 # inner radius at top of j-hook pin if self.body_board_distance is None: self.body_board_distance = max (self.pin_thickness - self.bottom_pocket_depth, 0.0) self.first_pin_pos = (self.pin_pitch * (self.num_pins / 2.0 / self.num_pin_rows - 0.5), self.distance_pinTip_rows/2.0 - self.pin_thickness) self.rotation = 90.0 self.offsets = (0.0, 0.0, 0.0) def paramsForGw (self): r"""set the reqired dimensions for building gullwing pins """ self.pin_bottom_length = 1.3 self.pin_height = 0.7 if self.body_board_distance is None: self.body_board_distance = 0.0 # Sice the pins are hidden inside the body, we can make the pin length half the distance pin tip of both rows (distance_pinTip_rows) # In this case the y- part of the first pin pos can be 0.0 self.pin_length = self.distance_pinTip_rows / 2.0 # only used for gullwing self.first_pin_pos = (self.pin_pitch * (self.num_pins / 2.0 / self.num_pin_rows - 0.5), 0.0) self.rotation = 90.0 self.offsets = (0.0, 0.0, 0.0) def paramsForTh (self): r"""set the reqired dimensions for building through hole pins """ self.pin_height = self.pin_length_below_body + 1.1 if self.body_board_distance is None: self.body_board_distance = 0.0 # Sice the pins are hidden inside the body, we can make the pin top length half the distance pin tip of both rows (distance_pinTip_rows) # In this case the y- part of the first pin pos can be 0.0 self.pin_top_length = self.distance_pinTip_rows / 2.0 - self.pin_thickness self.first_pin_pos = (self.pin_pitch * (self.num_pins / 2.0 / self.num_pin_rows - 0.5), 0.0) # THT pins must be shifted upwards self.pin_z_shift = self.pin_height - self.pin_thickness/2.0 - self.pin_length_below_body self.rotation = 90.0 offsetX = (self.distance_pinTip_rows / 2.0) offsetY = (-self.first_pin_pos[0]) self.offsets = (offsetX, offsetY, 0.0) # dictionary assigning the parameter functions for setting the pin dimensions to ShapeOfTerminal keys _TerminalShapeSwitcher = { ShapeOfTerminal.GW: paramsForGw, ShapeOfTerminal.JH: paramsForJh, ShapeOfTerminal.TH: paramsForTh, ShapeOfTerminal.THC: paramsForTh, ShapeOfTerminal.THL: paramsForTh, }
easyw/kicad-3d-models-in-freecad
cadquery/FCAD_script_generator/Button_Switch_Tactile_SMD_THT/cq_parameters.py
Python
gpl-2.0
14,405
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 CERN. ## ## Invenio 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. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """BibFormat element - Prints comments posted for the record """ __revision__ = "$Id$" from invenio.webcomment import get_first_comments_or_remarks def format_element(bfo, nbReviews='all', nbComments='all'): """ Prints comments posted for the record. @param nbReviews: The max number of reviews to print @param nbComments: The max number of comments to print """ nb_reviews = nbReviews if nb_reviews.isdigit(): nb_reviews = int(nb_reviews) nb_comments = nbComments if nb_comments.isdigit(): nb_comments = int(nb_comments) (comments, reviews) = get_first_comments_or_remarks(recID=bfo.recID, ln=bfo.lang, nb_comments=nb_comments, nb_reviews=nb_reviews, voted=-1, reported=-1, user_info=bfo.user_info) return comments + reviews def escape_values(bfo): """ Called by BibFormat in order to check if output of this element should be escaped. """ return 0
pombredanne/invenio
modules/bibformat/lib/elements/bfe_comments.py
Python
gpl-2.0
2,111
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2015-03-03 01:36:47 # @Author : Robin from HttpHolder import HttpHolder import json class XBase(object): def __init__(self, username="nobody", password="nobody", app="app", apiurl="http://127.0.0.1:9999/api/"): super(XBase, self).__init__() self.username = username self.password = password self.baseurl = '%s%s'%(apiurl, app) def __gethttp__(self): import urllib au = '%s:%s'%(self.username, self.password) au = 'Basic %s'%urllib.base64.b64encode(au) return HttpHolder(headers={'Authorization':au}) def __getitem__(self, key): ''' 获取单个记录 ''' h = self.__gethttp__() url = '%s/%s'%(self.baseurl, key) return h.open_html(url) def __setitem__(self, key, value): ''' 设置单个记录 ''' if isinstance(value, unicode): value = value.encode('utf-8') elif not isinstance(value, str): value = str(value) if key!=None and not isinstance(key, str): key = str(key) h = self.__gethttp__() if key: url = '%s/%s'%(self.baseurl, key) else: url = self.baseurl h.open_html(url, data=value) def add(self, value): self.__setitem__(None, value) def items(self): ''' 获取所有记录元组 ''' h = self.__gethttp__() dic = json.loads(h.open_html(self.baseurl)) return dic.items() if __name__ == '__main__': xb = XBase() xb['t'] = u'中国' # print xb['t'] # print xb.items()
sintrb/XBase
sdk/XBase.py
Python
gpl-2.0
1,427
# 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 msrest.serialization import Model class ResourceCollection(Model): """ResourceCollection :param productresource: :type productresource: :class:`FlattenedProduct <fixtures.acceptancetestsmodelflattening.models.FlattenedProduct>` :param arrayofresources: :type arrayofresources: list of :class:`FlattenedProduct <fixtures.acceptancetestsmodelflattening.models.FlattenedProduct>` :param dictionaryofresources: :type dictionaryofresources: dict """ _attribute_map = { 'productresource': {'key': 'productresource', 'type': 'FlattenedProduct'}, 'arrayofresources': {'key': 'arrayofresources', 'type': '[FlattenedProduct]'}, 'dictionaryofresources': {'key': 'dictionaryofresources', 'type': '{FlattenedProduct}'}, } def __init__(self, productresource=None, arrayofresources=None, dictionaryofresources=None): self.productresource = productresource self.arrayofresources = arrayofresources self.dictionaryofresources = dictionaryofresources
sharadagarwal/autorest
AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource_collection.py
Python
mit
1,520
import re from ztag.annotation import Annotation from ztag.annotation import OperatingSystem from ztag.annotation import Type from ztag.annotation import Manufacturer from ztag import protocols import ztag.test class FtpFullrate(Annotation): protocol = protocols.FTP subprotocol = protocols.FTP.BANNER port = None manufact_re = re.compile( "^220 Fullrate FTP version \d+\.\d+ ready at", re.IGNORECASE ) ftp_version_re = re.compile( "^220 Fullrate FTP version (\d+\.\d+) ready at", re.IGNORECASE ) tests = { "FtpFullrate_1": { "global_metadata": { "device_type": Type.DSL_MODEM, "manufacturer": Manufacturer.FULLRATE }, "local_metadata": { "version": "1.0" } } } def process(self, obj, meta): banner = obj["banner"] if self.manufact_re.search(banner): meta.global_metadata.device_type = Type.DSL_MODEM meta.global_metadata.manufacturer = Manufacturer.FULLRATE version = self.ftp_version_re.search(banner) if version: meta.local_metadata.version = version.group(1) return meta """ Tests "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:33:10 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:32:12 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:34:15 2015\r\n" "220 fullrate FTP version 1.0 ready at Mon Jun 22 02:35:11 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:34:39 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:35:56 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:35:36 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:36:03 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:36:01 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:36:23 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:34:34 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:36:12 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:36:57 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:37:06 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:36:33 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:36:18 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:37:33 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:37:36 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:36:17 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:38:22 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:35:48 2015\r\n" "220 Fullrate FTP version 1.0 ready at Mon Jun 22 02:38:21 2015\r\n" """
zmap/ztag
ztag/annotations/FtpFullrate.py
Python
apache-2.0
2,892
# # rtlsdr_scan # # http://eartoearoak.com/software/rtlsdr-scanner # # Copyright 2012 - 2014 Al Brown # # A frequency scanning GUI for the OsmoSDR rtl-sdr library at # http://sdr.osmocom.org/trac/wiki/rtl-sdr # # # 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, 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 threading import time from matplotlib import cm, patheffects import matplotlib from matplotlib.colorbar import ColorbarBase from matplotlib.colors import Normalize from matplotlib.dates import DateFormatter from matplotlib.gridspec import GridSpec from matplotlib.lines import Line2D from matplotlib.text import Text from matplotlib.ticker import ScalarFormatter, AutoMinorLocator import numpy from constants import Markers from events import EventThread, Event, post_event from misc import format_time, format_precision from spectrum import split_spectrum, Measure from utils_mpl import utc_to_mpl class Spectrogram(object): def __init__(self, notify, figure, settings): self.notify = notify self.figure = figure self.settings = settings self.data = [[], [], []] self.axes = None self.plot = None self.extent = None self.bar = None self.barBase = None self.lines = {} self.labels = {} self.overflowLabels = {} self.overflow = {'left': [], 'right': []} self.threadPlot = None self.__setup_plot() self.set_grid(self.settings.grid) def __setup_plot(self): gs = GridSpec(1, 2, width_ratios=[9.5, 0.5]) self.axes = self.figure.add_subplot(gs[0], axisbg=self.settings.background) self.axes.set_xlabel("Frequency (MHz)") self.axes.set_ylabel('Time') numFormatter = ScalarFormatter(useOffset=False) timeFormatter = DateFormatter("%H:%M:%S") self.axes.xaxis.set_major_formatter(numFormatter) self.axes.yaxis.set_major_formatter(timeFormatter) self.axes.xaxis.set_minor_locator(AutoMinorLocator(10)) self.axes.yaxis.set_minor_locator(AutoMinorLocator(10)) self.axes.set_xlim(self.settings.start, self.settings.stop) now = time.time() self.axes.set_ylim(utc_to_mpl(now), utc_to_mpl(now - 10)) self.bar = self.figure.add_subplot(gs[1]) norm = Normalize(vmin=-50, vmax=0) self.barBase = ColorbarBase(self.bar, norm=norm, cmap=cm.get_cmap(self.settings.colourMap)) self.__setup_measure() self.__setup_overflow() self.hide_measure() def __setup_measure(self): dashesHalf = [1, 5, 5, 5, 5, 5] self.lines[Markers.HFS] = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='purple') self.lines[Markers.HFE] = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='purple') self.lines[Markers.OFS] = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='#996600') self.lines[Markers.OFE] = Line2D([0, 0], [0, 0], dashes=dashesHalf, color='#996600') if matplotlib.__version__ >= '1.3': effect = patheffects.withStroke(linewidth=3, foreground="w", alpha=0.75) self.lines[Markers.HFS].set_path_effects([effect]) self.lines[Markers.HFE].set_path_effects([effect]) self.lines[Markers.OFS].set_path_effects([effect]) self.lines[Markers.OFE].set_path_effects([effect]) for line in self.lines.itervalues(): self.axes.add_line(line) bbox = self.axes.bbox box = dict(boxstyle='round', fc='white', ec='purple', clip_box=bbox) self.labels[Markers.HFS] = Text(0, 0, '-3dB', fontsize='xx-small', ha="center", va="top", bbox=box, color='purple') self.labels[Markers.HFE] = Text(0, 0, '-3dB', fontsize='xx-small', ha="center", va="top", bbox=box, color='purple') box['ec'] = '#996600' self.labels[Markers.OFS] = Text(0, 0, 'OBW', fontsize='xx-small', ha="center", va="top", bbox=box, color='#996600') self.labels[Markers.OFE] = Text(0, 0, 'OBW', fontsize='xx-small', ha="center", va="top", bbox=box, color='#996600') for label in self.labels.itervalues(): self.axes.add_artist(label) def __setup_overflow(self): bbox = self.axes.bbox box = dict(boxstyle='round', fc='white', ec='black', alpha=0.5, clip_box=bbox) self.overflowLabels['left'] = Text(0, 0.9, '', fontsize='xx-small', ha="left", va="top", bbox=box, transform=self.axes.transAxes, alpha=0.5) self.overflowLabels['right'] = Text(1, 0.9, '', fontsize='xx-small', ha="right", va="top", bbox=box, transform=self.axes.transAxes, alpha=0.5) for label in self.overflowLabels.itervalues(): self.axes.add_artist(label) def __clear_overflow(self): for label in self.overflowLabels: self.overflow[label] = [] def __draw_vline(self, marker, x): line = self.lines[marker] label = self.labels[marker] yLim = self.axes.get_ylim() xLim = self.axes.get_xlim() if xLim[0] < x < xLim[1]: line.set_visible(True) line.set_xdata([x, x]) line.set_ydata([yLim[0], yLim[1]]) self.axes.draw_artist(line) label.set_visible(True) label.set_position((x, yLim[1])) self.axes.draw_artist(label) elif x is not None and x < xLim[0]: self.overflow['left'].append(marker) elif x is not None and x > xLim[1]: self.overflow['right'].append(marker) def __draw_overflow(self): for pos, overflow in self.overflow.iteritems(): if len(overflow) > 0: text = '' for measure in overflow: if len(text) > 0: text += '\n' text += self.labels[measure].get_text() label = self.overflowLabels[pos] if pos == 'left': textMath = '$\\blacktriangleleft$\n' + text elif pos == 'right': textMath = '$\\blacktriangleright$\n' + text label.set_text(textMath) label.set_visible(True) self.axes.draw_artist(label) def draw_measure(self, measure, show): if self.axes.get_renderer_cache() is None: return self.hide_measure() self.__clear_overflow() if show[Measure.HBW]: xStart, xEnd, _y = measure.get_hpw() self.__draw_vline(Markers.HFS, xStart) self.__draw_vline(Markers.HFE, xEnd) if show[Measure.OBW]: xStart, xEnd, _y = measure.get_obw() self.__draw_vline(Markers.OFS, xStart) self.__draw_vline(Markers.OFE, xEnd) self.__draw_overflow() def hide_measure(self): for line in self.lines.itervalues(): line.set_visible(False) for label in self.labels.itervalues(): label.set_visible(False) for label in self.overflowLabels.itervalues(): label.set_visible(False) def scale_plot(self, force=False): if self.figure is not None and self.plot is not None: extent = self.plot.get_extent() if self.settings.autoF or force: if extent[0] == extent[1]: extent[1] += 1 self.axes.set_xlim(extent[0], extent[1]) if self.settings.autoL or force: vmin, vmax = self.plot.get_clim() self.barBase.set_clim(vmin, vmax) try: self.barBase.draw_all() except: pass if self.settings.autoT or force: self.axes.set_ylim(extent[2], extent[3]) def redraw_plot(self): if self.figure is not None: post_event(self.notify, EventThread(Event.DRAW)) def get_axes(self): return self.axes def get_axes_bar(self): return self.barBase.ax def get_plot_thread(self): return self.threadPlot def set_title(self, title): self.axes.set_title(title, fontsize='medium') def set_plot(self, spectrum, extent, annotate=False): self.extent = extent self.threadPlot = ThreadPlot(self, self.settings, self.axes, spectrum, self.extent, self.barBase, annotate) self.threadPlot.start() def clear_plots(self): children = self.axes.get_children() for child in children: if child.get_gid() is not None: if child.get_gid() == "plot_line" or child.get_gid() == "peak": child.remove() def set_grid(self, on): if on: self.axes.grid(True, color='w') else: self.axes.grid(False) self.redraw_plot() def set_colourmap(self, colourMap): if self.plot is not None: self.plot.set_cmap(colourMap) self.barBase.set_cmap(colourMap) try: self.barBase.draw_all() except: pass def close(self): self.figure.clear() self.figure = None class ThreadPlot(threading.Thread): def __init__(self, parent, settings, axes, data, extent, barBase, annotate): threading.Thread.__init__(self) self.name = "Plot" self.parent = parent self.settings = settings self.axes = axes self.data = data self.extent = extent self.retainMax = settings.retainMax self.colourMap = settings.colourMap self.autoL = settings.autoL self.barBase = barBase self.annotate = annotate def run(self): if self.data is None: self.parent.threadPlot = None return total = len(self.data) if total > 0: width = len(self.data[min(self.data)]) c = numpy.ma.masked_all((self.retainMax, width)) self.parent.clear_plots() j = self.retainMax for ys in self.data: j -= 1 _xs, zs = split_spectrum(self.data[ys]) for i in range(len(zs)): try: c[j, i] = zs[i] except IndexError: continue norm = None if not self.autoL: minY, maxY = self.barBase.get_clim() norm = Normalize(vmin=minY, vmax=maxY) extent = self.extent.get_ft() self.parent.plot = self.axes.imshow(c, aspect='auto', extent=extent, norm=norm, cmap=cm.get_cmap(self.colourMap), interpolation='spline16', gid="plot_line") if self.annotate: self.__annotate_plot() if total > 0: self.parent.scale_plot() self.parent.redraw_plot() self.parent.threadPlot = None def __annotate_plot(self): self.__clear_markers() fMax, lMax, tMax = self.extent.get_peak_flt() y = utc_to_mpl(tMax) start, stop = self.axes.get_xlim() textX = ((stop - start) / 50.0) + fMax when = format_time(tMax) text = '{}\n{}\n{when}'.format(*format_precision(self.settings, fMax, lMax, fancyUnits=True), when=when) if matplotlib.__version__ < '1.3': self.axes.annotate(text, xy=(fMax, y), xytext=(textX, y), ha='left', va='bottom', size='x-small', color='w', gid='peak') self.axes.plot(fMax, y, marker='x', markersize=10, color='w', mew=3, gid='peak') self.axes.plot(fMax, y, marker='x', markersize=10, color='r', gid='peak') else: effect = patheffects.withStroke(linewidth=2, foreground="w", alpha=0.75) self.axes.annotate(text, xy=(fMax, y), xytext=(textX, y), ha='left', va='bottom', size='x-small', path_effects=[effect], gid='peak') self.axes.plot(fMax, y, marker='x', markersize=10, color='r', path_effects=[effect], gid='peak') def __clear_markers(self): children = self.axes.get_children() for child in children: if child.get_gid() is not None: if child.get_gid() == 'peak': child.remove() if __name__ == '__main__': print 'Please run rtlsdr_scan.py' exit(1)
thatchristoph/RTLSDR-Scanner
src/plot_spect.py
Python
gpl-3.0
14,513
#process all record import pickle import signal_processing as sig_proc dir_name = '../data/r415/' img_ext = '.png' save_img = False show = False save_obj = False #signal filtering parameter low_cut = 3e2 high_cut = 3e3 #spike finding parameters b_spike = 6 a_spike = 20 spike_thresh = -4 threshold_template = 4 #distance from which it's acceptable to put spike in class base_name = 'r415_' record_name = ['130926', '131008', '131009', '131011', '131016', '131017', '131018', '131021', '131023', '131025', '131030', '131101', '131118', '131129'] record_data = {} with open(dir_name + 'templates', 'rb') as my_file: all_chan_templates = pickle.load(my_file) sp = sig_proc.Signal_processing(save_img, show, img_ext) #for record in record_name: record = record_name[0] print('----- processing record: ' + record + ' -----') signal = sp.load_m(dir_name + base_name + record + '.mat', 'd')#load multichannel signal fs = float(sp.load_m(dir_name + 'fech.mat', 'sampFreq')) #load sample frequency fsignal = sp.signal_mc_filtering(signal, low_cut, high_cut, fs) all_chan_spikes_values = [] all_chan_spikes_times = [] all_chan_spikes_classes = [] all_chan_clusters = [] #create cluster for storing classed spikes inside print('### create cluster storing spikes_values and spikes_time ###') for chan in range(len(all_chan_templates)): all_chan_clusters.append([]) for gpe in all_chan_templates[chan]: all_chan_clusters[chan].append(sig_proc.Spikes_cluster(gpe.template, gpe.number + 1)) for chan in range(fsignal.shape[0]): print('\n\n--- processing chan: ' + str(chan + 1) + ' ---') s = fsignal[chan] spikes_values, spikes_time = sp.find_spikes(s, a_spike, b_spike, spike_thresh) spikes_values = sp.smooth_spikes(spikes_values, 3) print('spikes found: ' + str(spikes_values.shape[0])) spikes_classes = sp.classify_spikes(spikes_values, spikes_time, all_chan_clusters[chan], 2 * threshold_template) all_chan_spikes_classes.append(spikes_classes) all_chan_spikes_times.append(spikes_time) all_chan_spikes_values.append(spikes_values) sp.plot_signal_spikes_classified(spikes_time, spikes_classes, base_name + '_' + record + '_' + str(chan) + '_') # unclass_spikes=[] # for i in range(len(spikes_classes)): # if spikes_classes[i]==-1: # unclass_spikes.append(spikes_values[i]) # sp.plot_spikes(np.array(unclass_spikes),20,'chan_'+str(chan)) #plt.show() record_data[record] = {'spikes_values': all_chan_spikes_values, 'spikes_time': all_chan_spikes_times, 'spikes_classes': all_chan_spikes_classes, 'clusters': all_chan_clusters} if save_obj: with open(dir_name + 'data_processed', 'wb') as my_file: my_pickler = pickle.Pickler(my_file) my_pickler.dump(record_data) print('\n\n#################') print('#### END ####')
scauglog/brain_record_toolbox
script_r415_process_record.py
Python
mit
2,841
#!/usr/bin/env python # sorry, this is very ugly, but I'm in python 2.5 import sys sys.path.insert(0,"../..") from dot11 import ProtocolPacket from ImpactPacket import ProtocolLayer, PacketBuffer from binascii import hexlify import unittest class TestPacket(ProtocolPacket): def __init__(self, aBuffer = None): header_size = 7 tail_size = 5 ProtocolPacket.__init__(self, header_size,tail_size) if(aBuffer): self.load_packet(aBuffer) class TestDot11HierarchicalUpdate(unittest.TestCase): def setUp(self): self.rawpacket1 = "" \ "Header1"\ "Body1"\ "Tail1" self.rawpacket2 = "" \ "Header2"+\ self.rawpacket1+ \ "Tail2" self.rawpacket3 = "" \ "Header3"+\ self.rawpacket2+ \ "Tail3" self.packet1=TestPacket(self.rawpacket1) self.packet2=TestPacket(self.rawpacket2) self.packet2.contains(self.packet1) self.packet3=TestPacket(self.rawpacket3) self.packet3.contains(self.packet2) def test_01_StartupPacketsStringTest(self): "ProtocolPacket - get_packet initial string test" self.assertEqual(self.packet1.get_packet(), "Header1Body1Tail1") self.assertEqual(self.packet2.get_packet(), "Header2Header1Body1Tail1Tail2") self.assertEqual(self.packet3.get_packet(), "Header3Header2Header1Body1Tail1Tail2Tail3") def test_02_StartupPacketsSizeTest(self): "ProtocolPacket - Initial size getters test" self.assertEqual(self.packet1.get_size(), 7+5+5) self.assertEqual(self.packet1.get_header_size(), 7) self.assertEqual(self.packet1.get_body_size(), 5) self.assertEqual(self.packet1.get_tail_size(), 5) self.assertEqual(self.packet2.get_size(), 7+ (7+5+5) + 5) self.assertEqual(self.packet2.get_header_size(), 7) self.assertEqual(self.packet2.get_body_size(), 7+5+5) self.assertEqual(self.packet2.get_tail_size(), 5) self.assertEqual(self.packet3.get_size(), 7+ (7+ (7+5+5) +5) +5 ) self.assertEqual(self.packet3.get_header_size(), 7) self.assertEqual(self.packet3.get_body_size(), 7+ 7+5+5 +5) self.assertEqual(self.packet3.get_tail_size(), 5) def test_03_ChildModificationTest(self): "ProtocolPacket - get_packet hierarchical update test" self.packet1.load_body("**NewBody**") self.assertEqual(self.packet1.get_packet(), "Header1**NewBody**Tail1") self.assertEqual(self.packet2.get_packet(), "Header2Header1**NewBody**Tail1Tail2") self.assertEqual(self.packet3.get_packet(), "Header3Header2Header1**NewBody**Tail1Tail2Tail3") def test_04_ChildModificationTest(self): "ProtocolPacket - size getters hierarchical update test" self.packet1.load_body("**NewBody**") #self.packet1 => "Header1**NewBody**Tail1" #self.packet2 => "Header2Header1**NewBody**Tail1Tail2" #self.packet3 => "Header3Header2Header1**NewBody**Tail1Tail2Tail3" self.assertEqual(self.packet1.get_size(), 7+11+5 ) self.assertEqual(self.packet1.get_header_size(), 7) self.assertEqual(self.packet1.get_body_size(), 11) self.assertEqual(self.packet1.get_tail_size(), 5) self.assertEqual(self.packet2.get_size(), 7+ (7+11+5) +5 ) self.assertEqual(self.packet2.get_header_size(), 7) self.assertEqual(self.packet2.get_body_size(), 7+11+5) self.assertEqual(self.packet2.get_tail_size(), 5) self.assertEqual(self.packet3.get_size(), 7+ (7+ (7+11+5) +5) +5 ) self.assertEqual(self.packet3.get_header_size(), 7) self.assertEqual(self.packet3.get_body_size(), 7+ (7+11+5) +5) self.assertEqual(self.packet3.get_tail_size(), 5) def test_05_ChildModificationTest(self): "ProtocolPacket - body packet hierarchical update test" self.packet1.load_body("**NewBody**") self.assertEqual(self.packet1.body.get_buffer_as_string(), "**NewBody**") self.assertEqual(self.packet2.body.get_buffer_as_string(), "Header1**NewBody**Tail1") self.assertEqual(self.packet3.body.get_buffer_as_string(), "Header2Header1**NewBody**Tail1Tail2") def test_06_ChildModificationTest(self): "ProtocolPacket - get_body_as_string packet hierarchical update test" self.packet1.load_body("**NewBody**") self.assertEqual(self.packet1.get_body_as_string(), "**NewBody**") self.assertEqual(self.packet2.get_body_as_string(), "Header1**NewBody**Tail1") self.assertEqual(self.packet3.get_body_as_string(), "Header2Header1**NewBody**Tail1Tail2") def test_07_ChildModificationTest(self): "ProtocolPacket - load_body child hierarchy update test" self.assertEqual(self.packet1.parent(), self.packet2) self.assertEqual(self.packet2.parent(), self.packet3) self.assertEqual(self.packet3.child(), self.packet2) self.assertEqual(self.packet2.child(), self.packet1) self.packet2.load_body("Header1**NewBody**Tail1") self.assertEqual(self.packet1.parent(), None) self.assertEqual(self.packet2.parent(), self.packet3) self.assertEqual(self.packet3.child(), self.packet2) self.assertEqual(self.packet2.child(), None) self.assertEqual(self.packet1.body.get_buffer_as_string(), "Body1") self.assertEqual(self.packet2.body.get_buffer_as_string(), "Header1**NewBody**Tail1") self.assertEqual(self.packet3.body.get_buffer_as_string(), "Header2Header1**NewBody**Tail1Tail2") suite = unittest.TestLoader().loadTestsFromTestCase(TestDot11HierarchicalUpdate) unittest.TextTestRunner(verbosity=2).run(suite)
tholum/PiBunny
system.d/library/tools_installer/tools_to_install/impacket/impacket/testcases/dot11/test_Dot11HierarchicalUpdate.py
Python
mit
5,961
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) return True pybindgen.settings.error_handler = ErrorHandler() import sys def module_init(): root_module = Module('ns.visualizer', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress', import_from_module='ns.network') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] module.add_class('InetSocketAddress', import_from_module='ns.network') ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## int-to-type.h (module 'core'): ns3::IntToType<0> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['0']) ## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<1> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['1']) ## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<2> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['2']) ## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<3> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['3']) ## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<4> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['4']) ## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<5> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5']) ## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<6> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['6']) ## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'], import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress [class] module.add_class('Ipv6InterfaceAddress', import_from_module='ns.internet') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e [enumeration] module.add_enum('State_e', ['TENTATIVE', 'DEPRECATED', 'PREFERRED', 'PERMANENT', 'HOMEADDRESS', 'TENTATIVE_OPTIMISTIC', 'INVALID'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e [enumeration] module.add_enum('Scope_e', ['HOST', 'LINKLOCAL', 'GLOBAL'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration] module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network') ## pyviz.h (module 'visualizer'): ns3::PyViz [class] module.add_class('PyViz') ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureMode [enumeration] module.add_enum('PacketCaptureMode', ['PACKET_CAPTURE_DISABLED', 'PACKET_CAPTURE_FILTER_HEADERS_OR', 'PACKET_CAPTURE_FILTER_HEADERS_AND'], outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample [struct] module.add_class('LastPacketsSample', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics [struct] module.add_class('NetDeviceStatistics', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics [struct] module.add_class('NodeStatistics', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions [struct] module.add_class('PacketCaptureOptions', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample [struct] module.add_class('PacketDropSample', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample [struct] module.add_class('PacketSample', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::RxPacketSample [struct] module.add_class('RxPacketSample', parent=root_module['ns3::PyViz::PacketSample'], outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample [struct] module.add_class('TransmissionSample', outer_class=root_module['ns3::PyViz']) ## pyviz.h (module 'visualizer'): ns3::PyViz::TxPacketSample [struct] module.add_class('TxPacketSample', parent=root_module['ns3::PyViz::PacketSample'], outer_class=root_module['ns3::PyViz']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## timer.h (module 'core'): ns3::Timer [class] module.add_class('Timer', import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration] module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::State [enumeration] module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer-impl.h (module 'core'): ns3::TimerImpl [class] module.add_class('TimerImpl', allow_subclassing=True, import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class] module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration] module.add_enum('DscpType', ['DscpDefault', 'DSCP_CS1', 'DSCP_AF11', 'DSCP_AF12', 'DSCP_AF13', 'DSCP_CS2', 'DSCP_AF21', 'DSCP_AF22', 'DSCP_AF23', 'DSCP_CS3', 'DSCP_AF31', 'DSCP_AF32', 'DSCP_AF33', 'DSCP_CS4', 'DSCP_AF41', 'DSCP_AF42', 'DSCP_AF43', 'DSCP_CS5', 'DSCP_EF', 'DSCP_CS6', 'DSCP_CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration] module.add_enum('EcnType', ['ECN_NotECT', 'ECN_ECT1', 'ECN_ECT0', 'ECN_CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv6-header.h (module 'internet'): ns3::Ipv6Header [class] module.add_class('Ipv6Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv6-header.h (module 'internet'): 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'], import_from_module='ns.internet') ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4MulticastRoute>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4Route>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## socket.h (module 'network'): ns3::Socket [class] module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::SocketAddressTag [class] module.add_class('SocketAddressTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTosTag [class] module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## channel.h (module 'network'): ns3::Channel [class] module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol [class] module.add_class('IpL4Protocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus [enumeration] module.add_enum('RxStatus', ['RX_OK', 'RX_CSUM_FAILED', 'RX_ENDPOINT_CLOSED', 'RX_ENDPOINT_UNREACH'], outer_class=root_module['ns3::IpL4Protocol'], import_from_module='ns.internet') ## ipv4.h (module 'internet'): ns3::Ipv4 [class] module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol [class] module.add_class('Ipv4L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv4']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::DropReason [enumeration] module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_BAD_CHECKSUM', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv4L3Protocol'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class] module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class] module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class] module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface [class] module.add_class('Ipv6Interface', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) module.add_container('std::vector< ns3::PyViz::RxPacketSample >', 'ns3::PyViz::RxPacketSample', container_type='vector') module.add_container('std::vector< ns3::PyViz::TxPacketSample >', 'ns3::PyViz::TxPacketSample', container_type='vector') module.add_container('std::vector< ns3::PyViz::PacketSample >', 'ns3::PyViz::PacketSample', container_type='vector') module.add_container('std::set< ns3::TypeId >', 'ns3::TypeId', container_type='set') module.add_container('std::vector< ns3::PyViz::TransmissionSample >', 'ns3::PyViz::TransmissionSample', container_type='vector') module.add_container('std::vector< ns3::PyViz::PacketDropSample >', 'ns3::PyViz::PacketDropSample', container_type='vector') module.add_container('std::vector< ns3::PyViz::NetDeviceStatistics >', 'ns3::PyViz::NetDeviceStatistics', container_type='vector') module.add_container('std::vector< std::string >', 'std::string', container_type='vector') module.add_container('std::set< unsigned int >', 'unsigned int', container_type='set') module.add_container('std::vector< ns3::PyViz::NodeStatistics >', 'ns3::PyViz::NodeStatistics', container_type='vector') module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type='map') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) *&', 'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *&', 'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) register_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >']) register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >']) register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >']) register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >']) register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >']) register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >']) register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_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_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3PyViz_methods(root_module, root_module['ns3::PyViz']) register_Ns3PyVizLastPacketsSample_methods(root_module, root_module['ns3::PyViz::LastPacketsSample']) register_Ns3PyVizNetDeviceStatistics_methods(root_module, root_module['ns3::PyViz::NetDeviceStatistics']) register_Ns3PyVizNodeStatistics_methods(root_module, root_module['ns3::PyViz::NodeStatistics']) register_Ns3PyVizPacketCaptureOptions_methods(root_module, root_module['ns3::PyViz::PacketCaptureOptions']) register_Ns3PyVizPacketDropSample_methods(root_module, root_module['ns3::PyViz::PacketDropSample']) register_Ns3PyVizPacketSample_methods(root_module, root_module['ns3::PyViz::PacketSample']) register_Ns3PyVizRxPacketSample_methods(root_module, root_module['ns3::PyViz::RxPacketSample']) register_Ns3PyVizTransmissionSample_methods(root_module, root_module['ns3::PyViz::TransmissionSample']) register_Ns3PyVizTxPacketSample_methods(root_module, root_module['ns3::PyViz::TxPacketSample']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3Timer_methods(root_module, root_module['ns3::Timer']) register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Ipv6Header_methods(root_module, root_module['ns3::Ipv6Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketAddressTag_methods(root_module, root_module['ns3::SocketAddressTag']) register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3Channel_methods(root_module, root_module['ns3::Channel']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3IpL4Protocol_methods(root_module, root_module['ns3::IpL4Protocol']) 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_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute']) register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route']) register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6Interface_methods(root_module, root_module['ns3::Ipv6Interface']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Inet6SocketAddress_methods(root_module, cls): ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor] cls.add_constructor([param('char const *', 'ipv6')]) ## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function] cls.add_method('ConvertFrom', 'ns3::Inet6SocketAddress', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function] cls.add_method('GetIpv6', 'ns3::Ipv6Address', [], is_const=True) ## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function] cls.add_method('SetIpv6', 'void', [param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) return def register_Ns3InetSocketAddress_methods(root_module, cls): ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor] cls.add_constructor([param('char const *', 'ipv4')]) ## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::InetSocketAddress', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function] cls.add_method('GetIpv4', 'ns3::Ipv4Address', [], is_const=True) ## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ipv4Address', 'address')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) return def register_Ns3IntToType__0_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType(ns3::IntToType<0> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 0 > const &', 'arg0')]) return def register_Ns3IntToType__1_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType(ns3::IntToType<1> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 1 > const &', 'arg0')]) return def register_Ns3IntToType__2_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType(ns3::IntToType<2> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 2 > const &', 'arg0')]) return def register_Ns3IntToType__3_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType(ns3::IntToType<3> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 3 > const &', 'arg0')]) return def register_Ns3IntToType__4_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType(ns3::IntToType<4> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 4 > const &', 'arg0')]) return def register_Ns3IntToType__5_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType(ns3::IntToType<5> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')]) return def register_Ns3IntToType__6_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType(ns3::IntToType<6> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 6 > const &', 'arg0')]) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function] cls.add_method('GetLocal', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function] cls.add_method('GetMask', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function] cls.add_method('IsSecondary', 'bool', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function] cls.add_method('SetBroadcast', 'void', [param('ns3::Ipv4Address', 'broadcast')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv4Address', 'local')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function] cls.add_method('SetMask', 'void', [param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function] cls.add_method('SetPrimary', 'void', []) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function] cls.add_method('SetSecondary', 'void', []) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() [member function] cls.add_method('IsIpv4MappedAddress', 'bool', []) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'address')]) ## ipv6-interface-address.h (module 'internet'): 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 (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv6InterfaceAddress const &', 'o')]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6InterfaceAddress::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): uint32_t ns3::Ipv6InterfaceAddress::GetNsDadUid() const [member function] cls.add_method('GetNsDadUid', 'uint32_t', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Prefix ns3::Ipv6InterfaceAddress::GetPrefix() const [member function] cls.add_method('GetPrefix', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): 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 (module 'internet'): 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 (module 'internet'): void ns3::Ipv6InterfaceAddress::SetAddress(ns3::Ipv6Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Ipv6Address', 'address')]) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetNsDadUid(uint32_t uid) [member function] cls.add_method('SetNsDadUid', 'void', [param('uint32_t', 'uid')]) ## ipv6-interface-address.h (module 'internet'): 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 (module 'internet'): 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 (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PyViz_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::PyViz(ns3::PyViz const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PyViz() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample ns3::PyViz::GetLastPackets(uint32_t nodeId) const [member function] cls.add_method('GetLastPackets', 'ns3::PyViz::LastPacketsSample', [param('uint32_t', 'nodeId')], is_const=True) ## pyviz.h (module 'visualizer'): std::vector<ns3::PyViz::NodeStatistics,std::allocator<ns3::PyViz::NodeStatistics> > ns3::PyViz::GetNodesStatistics() const [member function] cls.add_method('GetNodesStatistics', 'std::vector< ns3::PyViz::NodeStatistics >', [], is_const=True) ## pyviz.h (module 'visualizer'): std::vector<ns3::PyViz::PacketDropSample,std::allocator<ns3::PyViz::PacketDropSample> > ns3::PyViz::GetPacketDropSamples() const [member function] cls.add_method('GetPacketDropSamples', 'std::vector< ns3::PyViz::PacketDropSample >', [], is_const=True) ## pyviz.h (module 'visualizer'): std::vector<std::string, std::allocator<std::string> > ns3::PyViz::GetPauseMessages() const [member function] cls.add_method('GetPauseMessages', 'std::vector< std::string >', [], is_const=True) ## pyviz.h (module 'visualizer'): std::vector<ns3::PyViz::TransmissionSample,std::allocator<ns3::PyViz::TransmissionSample> > ns3::PyViz::GetTransmissionSamples() const [member function] cls.add_method('GetTransmissionSamples', 'std::vector< ns3::PyViz::TransmissionSample >', [], is_const=True) ## pyviz.h (module 'visualizer'): static void ns3::PyViz::LineClipping(double boundsX1, double boundsY1, double boundsX2, double boundsY2, double & lineX1, double & lineY1, double & lineX2, double & lineY2) [member function] cls.add_method('LineClipping', 'void', [param('double', 'boundsX1'), param('double', 'boundsY1'), param('double', 'boundsX2'), param('double', 'boundsY2'), param('double &', 'lineX1', direction=3), param('double &', 'lineY1', direction=3), param('double &', 'lineX2', direction=3), param('double &', 'lineY2', direction=3)], is_static=True) ## pyviz.h (module 'visualizer'): static void ns3::PyViz::Pause(std::string const & message) [member function] cls.add_method('Pause', 'void', [param('std::string const &', 'message')], is_static=True) ## pyviz.h (module 'visualizer'): void ns3::PyViz::RegisterCsmaLikeDevice(std::string const & deviceTypeName) [member function] cls.add_method('RegisterCsmaLikeDevice', 'void', [param('std::string const &', 'deviceTypeName')]) ## pyviz.h (module 'visualizer'): void ns3::PyViz::RegisterDropTracePath(std::string const & tracePath) [member function] cls.add_method('RegisterDropTracePath', 'void', [param('std::string const &', 'tracePath')]) ## pyviz.h (module 'visualizer'): void ns3::PyViz::RegisterPointToPointLikeDevice(std::string const & deviceTypeName) [member function] cls.add_method('RegisterPointToPointLikeDevice', 'void', [param('std::string const &', 'deviceTypeName')]) ## pyviz.h (module 'visualizer'): void ns3::PyViz::RegisterWifiLikeDevice(std::string const & deviceTypeName) [member function] cls.add_method('RegisterWifiLikeDevice', 'void', [param('std::string const &', 'deviceTypeName')]) ## pyviz.h (module 'visualizer'): void ns3::PyViz::SetNodesOfInterest(std::set<unsigned int, std::less<unsigned int>, std::allocator<unsigned int> > nodes) [member function] cls.add_method('SetNodesOfInterest', 'void', [param('std::set< unsigned int >', 'nodes')]) ## pyviz.h (module 'visualizer'): void ns3::PyViz::SetPacketCaptureOptions(uint32_t nodeId, ns3::PyViz::PacketCaptureOptions options) [member function] cls.add_method('SetPacketCaptureOptions', 'void', [param('uint32_t', 'nodeId'), param('ns3::PyViz::PacketCaptureOptions', 'options')]) ## pyviz.h (module 'visualizer'): void ns3::PyViz::SimulatorRunUntil(ns3::Time time) [member function] cls.add_method('SimulatorRunUntil', 'void', [param('ns3::Time', 'time')]) return def register_Ns3PyVizLastPacketsSample_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::LastPacketsSample() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::LastPacketsSample(ns3::PyViz::LastPacketsSample const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::LastPacketsSample const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::lastDroppedPackets [variable] cls.add_instance_attribute('lastDroppedPackets', 'std::vector< ns3::PyViz::PacketSample >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::lastReceivedPackets [variable] cls.add_instance_attribute('lastReceivedPackets', 'std::vector< ns3::PyViz::RxPacketSample >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::LastPacketsSample::lastTransmittedPackets [variable] cls.add_instance_attribute('lastTransmittedPackets', 'std::vector< ns3::PyViz::TxPacketSample >', is_const=False) return def register_Ns3PyVizNetDeviceStatistics_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::NetDeviceStatistics(ns3::PyViz::NetDeviceStatistics const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::NetDeviceStatistics const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::NetDeviceStatistics() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::receivedBytes [variable] cls.add_instance_attribute('receivedBytes', 'uint64_t', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::receivedPackets [variable] cls.add_instance_attribute('receivedPackets', 'uint32_t', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::transmittedBytes [variable] cls.add_instance_attribute('transmittedBytes', 'uint64_t', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::NetDeviceStatistics::transmittedPackets [variable] cls.add_instance_attribute('transmittedPackets', 'uint32_t', is_const=False) return def register_Ns3PyVizNodeStatistics_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics::NodeStatistics() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics::NodeStatistics(ns3::PyViz::NodeStatistics const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::NodeStatistics const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics::nodeId [variable] cls.add_instance_attribute('nodeId', 'uint32_t', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::NodeStatistics::statistics [variable] cls.add_instance_attribute('statistics', 'std::vector< ns3::PyViz::NetDeviceStatistics >', is_const=False) return def register_Ns3PyVizPacketCaptureOptions_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::PacketCaptureOptions() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::PacketCaptureOptions(ns3::PyViz::PacketCaptureOptions const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::PacketCaptureOptions const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::headers [variable] cls.add_instance_attribute('headers', 'std::set< ns3::TypeId >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::mode [variable] cls.add_instance_attribute('mode', 'ns3::PyViz::PacketCaptureMode', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketCaptureOptions::numLastPackets [variable] cls.add_instance_attribute('numLastPackets', 'uint32_t', is_const=False) return def register_Ns3PyVizPacketDropSample_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample::PacketDropSample() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample::PacketDropSample(ns3::PyViz::PacketDropSample const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::PacketDropSample const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample::bytes [variable] cls.add_instance_attribute('bytes', 'uint32_t', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketDropSample::transmitter [variable] cls.add_instance_attribute('transmitter', 'ns3::Ptr< ns3::Node >', is_const=False) return def register_Ns3PyVizPacketSample_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::PacketSample() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::PacketSample(ns3::PyViz::PacketSample const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::PacketSample const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::device [variable] cls.add_instance_attribute('device', 'ns3::Ptr< ns3::NetDevice >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::packet [variable] cls.add_instance_attribute('packet', 'ns3::Ptr< ns3::Packet >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::PacketSample::time [variable] cls.add_instance_attribute('time', 'ns3::Time', is_const=False) return def register_Ns3PyVizRxPacketSample_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::RxPacketSample::RxPacketSample() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::RxPacketSample::RxPacketSample(ns3::PyViz::RxPacketSample const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::RxPacketSample const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::RxPacketSample::from [variable] cls.add_instance_attribute('from', 'ns3::Mac48Address', is_const=False) return def register_Ns3PyVizTransmissionSample_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::TransmissionSample() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::TransmissionSample(ns3::PyViz::TransmissionSample const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::TransmissionSample const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::bytes [variable] cls.add_instance_attribute('bytes', 'uint32_t', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::channel [variable] cls.add_instance_attribute('channel', 'ns3::Ptr< ns3::Channel >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::receiver [variable] cls.add_instance_attribute('receiver', 'ns3::Ptr< ns3::Node >', is_const=False) ## pyviz.h (module 'visualizer'): ns3::PyViz::TransmissionSample::transmitter [variable] cls.add_instance_attribute('transmitter', 'ns3::Ptr< ns3::Node >', is_const=False) return def register_Ns3PyVizTxPacketSample_methods(root_module, cls): ## pyviz.h (module 'visualizer'): ns3::PyViz::TxPacketSample::TxPacketSample() [constructor] cls.add_constructor([]) ## pyviz.h (module 'visualizer'): ns3::PyViz::TxPacketSample::TxPacketSample(ns3::PyViz::TxPacketSample const & arg0) [copy constructor] cls.add_constructor([param('ns3::PyViz::TxPacketSample const &', 'arg0')]) ## pyviz.h (module 'visualizer'): ns3::PyViz::TxPacketSample::to [variable] cls.add_instance_attribute('to', 'ns3::Mac48Address', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & time) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'time')], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3Timer_methods(root_module, cls): ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Timer const &', 'arg0')]) ## timer.h (module 'core'): ns3::Timer::Timer() [constructor] cls.add_constructor([]) ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor] cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')]) ## timer.h (module 'core'): void ns3::Timer::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function] cls.add_method('GetDelay', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function] cls.add_method('GetState', 'ns3::Timer::State', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function] cls.add_method('IsSuspended', 'bool', [], is_const=True) ## timer.h (module 'core'): void ns3::Timer::Remove() [member function] cls.add_method('Remove', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Resume() [member function] cls.add_method('Resume', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule() [member function] cls.add_method('Schedule', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function] cls.add_method('Schedule', 'void', [param('ns3::Time', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function] cls.add_method('SetDelay', 'void', [param('ns3::Time const &', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::Suspend() [member function] cls.add_method('Suspend', 'void', []) return def register_Ns3TimerImpl_methods(root_module, cls): ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor] cls.add_constructor([]) ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')]) ## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function] cls.add_method('Invoke', 'void', [], is_pure_virtual=True, is_virtual=True) ## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function] cls.add_method('Schedule', 'ns3::EventId', [param('ns3::Time const &', 'delay')], is_pure_virtual=True, is_virtual=True) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Ipv4Header_methods(root_module, cls): ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')]) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor] cls.add_constructor([]) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function] cls.add_method('DscpTypeToString', 'std::string', [param('ns3::Ipv4Header::DscpType', 'dscp')], is_const=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function] cls.add_method('EcnTypeToString', 'std::string', [param('ns3::Ipv4Header::EcnType', 'ecn')], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function] cls.add_method('EnableChecksum', 'void', []) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function] cls.add_method('GetDscp', 'ns3::Ipv4Header::DscpType', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function] cls.add_method('GetEcn', 'ns3::Ipv4Header::EcnType', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function] cls.add_method('GetFragmentOffset', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function] cls.add_method('GetIdentification', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function] cls.add_method('GetPayloadSize', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function] cls.add_method('IsChecksumOk', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function] cls.add_method('IsDontFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function] cls.add_method('IsLastFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'destination')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function] cls.add_method('SetDontFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function] cls.add_method('SetDscp', 'void', [param('ns3::Ipv4Header::DscpType', 'dscp')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function] cls.add_method('SetEcn', 'void', [param('ns3::Ipv4Header::EcnType', 'ecn')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function] cls.add_method('SetFragmentOffset', 'void', [param('uint16_t', 'offsetBytes')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function] cls.add_method('SetIdentification', 'void', [param('uint16_t', 'identification')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function] cls.add_method('SetLastFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function] cls.add_method('SetMayFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function] cls.add_method('SetMoreFragments', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function] cls.add_method('SetPayloadSize', 'void', [param('uint16_t', 'size')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function] cls.add_method('SetProtocol', 'void', [param('uint8_t', 'num')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'source')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3Ipv6Header_methods(root_module, cls): ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header(ns3::Ipv6Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6Header const &', 'arg0')]) ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header() [constructor] cls.add_constructor([]) ## ipv6-header.h (module 'internet'): 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 (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetDestinationAddress() const [member function] cls.add_method('GetDestinationAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetFlowLabel() const [member function] cls.add_method('GetFlowLabel', 'uint32_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): ns3::TypeId ns3::Ipv6Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetNextHeader() const [member function] cls.add_method('GetNextHeader', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint16_t ns3::Ipv6Header::GetPayloadLength() const [member function] cls.add_method('GetPayloadLength', 'uint16_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetSourceAddress() const [member function] cls.add_method('GetSourceAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetTrafficClass() const [member function] cls.add_method('GetTrafficClass', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): static ns3::TypeId ns3::Ipv6Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-header.h (module 'internet'): 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 (module 'internet'): 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 (module 'internet'): void ns3::Ipv6Header::SetDestinationAddress(ns3::Ipv6Address dst) [member function] cls.add_method('SetDestinationAddress', 'void', [param('ns3::Ipv6Address', 'dst')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetFlowLabel(uint32_t flow) [member function] cls.add_method('SetFlowLabel', 'void', [param('uint32_t', 'flow')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetHopLimit(uint8_t limit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'limit')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetNextHeader(uint8_t next) [member function] cls.add_method('SetNextHeader', 'void', [param('uint8_t', 'next')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetPayloadLength(uint16_t len) [member function] cls.add_method('SetPayloadLength', 'void', [param('uint16_t', 'len')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetSourceAddress(ns3::Ipv6Address src) [member function] cls.add_method('SetSourceAddress', 'void', [param('ns3::Ipv6Address', 'src')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetTrafficClass(uint8_t traffic) [member function] cls.add_method('SetTrafficClass', 'void', [param('uint8_t', 'traffic')]) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4MulticastRoute > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4Route > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Socket_methods(root_module, cls): ## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [copy constructor] cls.add_constructor([param('ns3::Socket const &', 'arg0')]) ## socket.h (module 'network'): ns3::Socket::Socket() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function] cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind() [member function] cls.add_method('Bind', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind6() [member function] cls.add_method('Bind6', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function] cls.add_method('BindToNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'netdevice')], is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Close() [member function] cls.add_method('Close', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function] cls.add_method('Connect', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function] cls.add_method('GetAllowBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function] cls.add_method('GetBoundNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function] cls.add_method('GetErrno', 'ns3::Socket::SocketErrno', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTos() const [member function] cls.add_method('GetIpTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function] cls.add_method('GetIpTtl', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function] cls.add_method('GetIpv6HopLimit', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function] cls.add_method('GetIpv6Tclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function] cls.add_method('IsIpRecvTos', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function] cls.add_method('IsIpRecvTtl', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function] cls.add_method('IsIpv6RecvHopLimit', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function] cls.add_method('IsIpv6RecvTclass', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function] cls.add_method('IsRecvPktInfo', 'bool', [], is_const=True) ## socket.h (module 'network'): int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Recv', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function] cls.add_method('SendTo', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')]) ## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, 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 (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function] cls.add_method('SetCloseCallbacks', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')]) ## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function] cls.add_method('SetConnectCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')]) ## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function] cls.add_method('SetDataSentCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function] cls.add_method('SetIpRecvTos', 'void', [param('bool', 'ipv4RecvTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function] cls.add_method('SetIpRecvTtl', 'void', [param('bool', 'ipv4RecvTtl')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function] cls.add_method('SetIpTos', 'void', [param('uint8_t', 'ipTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function] cls.add_method('SetIpTtl', 'void', [param('uint8_t', 'ipTtl')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function] cls.add_method('SetIpv6HopLimit', 'void', [param('uint8_t', 'ipHopLimit')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function] cls.add_method('SetIpv6RecvHopLimit', 'void', [param('bool', 'ipv6RecvHopLimit')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function] cls.add_method('SetIpv6RecvTclass', 'void', [param('bool', 'ipv6RecvTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function] cls.add_method('SetIpv6Tclass', 'void', [param('int', 'ipTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function] cls.add_method('SetRecvCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function] cls.add_method('SetRecvPktInfo', 'void', [param('bool', 'flag')]) ## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function] cls.add_method('SetSendCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')]) ## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTos() const [member function] cls.add_method('IsManualIpTos', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function] cls.add_method('IsManualIpTtl', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function] cls.add_method('IsManualIpv6HopLimit', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function] cls.add_method('IsManualIpv6Tclass', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function] cls.add_method('NotifyConnectionFailed', 'void', [], visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function] cls.add_method('NotifyConnectionRequest', 'bool', [param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function] cls.add_method('NotifyConnectionSucceeded', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function] cls.add_method('NotifyDataRecv', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function] cls.add_method('NotifyDataSent', 'void', [param('uint32_t', 'size')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function] cls.add_method('NotifyErrorClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function] cls.add_method('NotifyNewConnectionCreated', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function] cls.add_method('NotifyNormalClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function] cls.add_method('NotifySend', 'void', [param('uint32_t', 'spaceAvailable')], visibility='protected') return def register_Ns3SocketAddressTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag(ns3::SocketAddressTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketAddressTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketAddressTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::Address ns3::SocketAddressTag::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketAddressTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketAddressTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketAddressTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): 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 (module 'network'): 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 (module 'network'): void ns3::SocketAddressTag::SetAddress(ns3::Address addr) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'addr')]) return def register_Ns3SocketIpTosTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3SocketIpTtlTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'hopLimit')]) return def register_Ns3SocketIpv6TclassTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function] cls.add_method('GetTclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function] cls.add_method('SetTclass', 'void', [param('uint8_t', 'tclass')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function] cls.add_method('Disable', 'void', []) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function] cls.add_method('Enable', 'void', []) ## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'value')]) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & from, ns3::Time::Unit timeUnit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit timeUnit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3Channel_methods(root_module, cls): ## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor] cls.add_constructor([param('ns3::Channel const &', 'arg0')]) ## channel.h (module 'network'): ns3::Channel::Channel() [constructor] cls.add_constructor([]) ## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3IpL4Protocol_methods(root_module, cls): ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol() [constructor] cls.add_constructor([]) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol(ns3::IpL4Protocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::IpL4Protocol const &', 'arg0')]) ## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget() const [member function] cls.add_method('GetDownTarget', 'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget6() const [member function] cls.add_method('GetDownTarget6', 'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): int ns3::IpL4Protocol::GetProtocolNumber() const [member function] cls.add_method('GetProtocolNumber', 'int', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): static ns3::TypeId ns3::IpL4Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::Ipv4Interface> incomingInterface) [member function] cls.add_method('Receive', 'ns3::IpL4Protocol::RxStatus', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::Ipv4Interface >', 'incomingInterface')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Header const & header, ns3::Ptr<ns3::Ipv6Interface> incomingInterface) [member function] cls.add_method('Receive', 'ns3::IpL4Protocol::RxStatus', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Header const &', 'header'), param('ns3::Ptr< ns3::Ipv6Interface >', 'incomingInterface')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv4Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv4Address payloadSource, ns3::Ipv4Address payloadDestination, uint8_t const * payload) [member function] cls.add_method('ReceiveIcmp', 'void', [param('ns3::Ipv4Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv4Address', 'payloadSource'), param('ns3::Ipv4Address', 'payloadDestination'), param('uint8_t const *', 'payload')], is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv6Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv6Address payloadSource, ns3::Ipv6Address payloadDestination, uint8_t const * payload) [member function] cls.add_method('ReceiveIcmp', 'void', [param('ns3::Ipv6Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv6Address', 'payloadSource'), param('ns3::Ipv6Address', 'payloadDestination'), param('uint8_t const *', 'payload')], is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetDownTarget', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget6(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetDownTarget6', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) return def register_Ns3Ipv4_methods(root_module, cls): ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')]) ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor] cls.add_constructor([]) ## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): static ns3::TypeId ns3::Ipv4::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsForwarding(uint32_t interface) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsUp(uint32_t interface) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetDown(uint32_t interface) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetForwarding(uint32_t interface, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'interface'), param('bool', 'val')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetMetric(uint32_t interface, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'interface'), param('uint16_t', 'metric')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetUp(uint32_t interface) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], is_pure_virtual=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4L3Protocol_methods(root_module, cls): ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::Ipv4L3Protocol() [constructor] cls.add_constructor([]) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::AddAddress(uint32_t i, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'i'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4L3Protocol::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4L3Protocol::GetAddress(uint32_t interfaceIndex, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Interface> ns3::Ipv4L3Protocol::GetInterface(uint32_t i) const [member function] cls.add_method('GetInterface', 'ns3::Ptr< ns3::Ipv4Interface >', [param('uint32_t', 'i')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForAddress(ns3::Ipv4Address addr) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'addr')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForPrefix(ns3::Ipv4Address addr, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'addr'), param('ns3::Ipv4Mask', 'mask')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMetric(uint32_t i) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMtu(uint32_t i) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4L3Protocol::GetNetDevice(uint32_t i) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4L3Protocol::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4L3Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsForwarding(uint32_t i) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUp(uint32_t i) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Receive(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> p, uint16_t protocol, ns3::Address const & from, ns3::Address const & to, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'p'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'from'), param('ns3::Address const &', 'to'), param('ns3::NetDevice::PacketType', 'packetType')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')]) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interfaceIndex, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDefaultTtl(uint8_t ttl) [member function] cls.add_method('SetDefaultTtl', 'void', [param('uint8_t', 'ttl')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDown(uint32_t i) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetForwarding(uint32_t i, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'i'), param('bool', 'val')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetMetric(uint32_t i, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'i'), param('uint16_t', 'metric')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetUp(uint32_t i) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::PROT_NUMBER [variable] cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], visibility='private', is_virtual=True) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv4MulticastRoute_methods(root_module, cls): ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function] cls.add_method('GetGroup', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function] cls.add_method('GetOrigin', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetOutputTtl(uint32_t oif) [member function] cls.add_method('GetOutputTtl', 'uint32_t', [param('uint32_t', 'oif')], deprecated=True) ## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function] cls.add_method('GetOutputTtlMap', 'std::map< unsigned int, unsigned int >', [], is_const=True) ## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function] cls.add_method('GetParent', 'uint32_t', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function] cls.add_method('SetGroup', 'void', [param('ns3::Ipv4Address const', 'group')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function] cls.add_method('SetOrigin', 'void', [param('ns3::Ipv4Address const', 'origin')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function] cls.add_method('SetOutputTtl', 'void', [param('uint32_t', 'oif'), param('uint32_t', 'ttl')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function] cls.add_method('SetParent', 'void', [param('uint32_t', 'iif')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable] cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable] cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True) return def register_Ns3Ipv4Route_methods(root_module, cls): cls.add_output_stream_operator() ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function] cls.add_method('GetGateway', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'dest')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function] cls.add_method('SetGateway', 'void', [param('ns3::Ipv4Address', 'gw')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function] cls.add_method('SetOutputDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'src')]) return def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls): ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor] cls.add_constructor([]) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')]) ## ipv4-routing-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void,ns3::Ptr<ns3::Ipv4Route>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> 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<const ns3::Packet>,const ns3::Ipv4Header&,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 (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_pure_virtual=True, is_virtual=True) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6Interface_methods(root_module, cls): ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface(ns3::Ipv6Interface const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6Interface const &', 'arg0')]) ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface() [constructor] cls.add_constructor([]) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::AddAddress(ns3::Ipv6InterfaceAddress iface) [member function] cls.add_method('AddAddress', 'bool', [param('ns3::Ipv6InterfaceAddress', 'iface')]) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddress(uint32_t index) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'index')], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddressMatchingDestination(ns3::Ipv6Address dst) [member function] cls.add_method('GetAddressMatchingDestination', 'ns3::Ipv6InterfaceAddress', [param('ns3::Ipv6Address', 'dst')]) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetBaseReachableTime() const [member function] cls.add_method('GetBaseReachableTime', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint8_t ns3::Ipv6Interface::GetCurHopLimit() const [member function] cls.add_method('GetCurHopLimit', 'uint8_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6Interface::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True, is_virtual=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetLinkLocalAddress() const [member function] cls.add_method('GetLinkLocalAddress', 'ns3::Ipv6InterfaceAddress', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetMetric() const [member function] cls.add_method('GetMetric', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint32_t ns3::Ipv6Interface::GetNAddresses() const [member function] cls.add_method('GetNAddresses', 'uint32_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetReachableTime() const [member function] cls.add_method('GetReachableTime', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetRetransTimer() const [member function] cls.add_method('GetRetransTimer', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): static ns3::TypeId ns3::Ipv6Interface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsDown() const [member function] cls.add_method('IsDown', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsForwarding() const [member function] cls.add_method('IsForwarding', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsUp() const [member function] cls.add_method('IsUp', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::RemoveAddress(uint32_t index) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'index')]) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::RemoveAddress(ns3::Ipv6Address address) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv6InterfaceAddress', [param('ns3::Ipv6Address', 'address')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::Send(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Address dest) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Address', 'dest')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetBaseReachableTime(uint16_t baseReachableTime) [member function] cls.add_method('SetBaseReachableTime', 'void', [param('uint16_t', 'baseReachableTime')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetCurHopLimit(uint8_t curHopLimit) [member function] cls.add_method('SetCurHopLimit', 'void', [param('uint8_t', 'curHopLimit')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDown() [member function] cls.add_method('SetDown', 'void', []) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetForwarding(bool forward) [member function] cls.add_method('SetForwarding', 'void', [param('bool', 'forward')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetMetric(uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint16_t', 'metric')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNsDadUid(ns3::Ipv6Address address, uint32_t uid) [member function] cls.add_method('SetNsDadUid', 'void', [param('ns3::Ipv6Address', 'address'), param('uint32_t', 'uid')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetReachableTime(uint16_t reachableTime) [member function] cls.add_method('SetReachableTime', 'void', [param('uint16_t', 'reachableTime')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetRetransTimer(uint16_t retransTimer) [member function] cls.add_method('SetRetransTimer', 'void', [param('uint16_t', 'retransTimer')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetState(ns3::Ipv6Address address, ns3::Ipv6InterfaceAddress::State_e state) [member function] cls.add_method('SetState', 'void', [param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6InterfaceAddress::State_e', 'state')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetUp() [member function] cls.add_method('SetUp', 'void', []) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac48Address const &', 'value')]) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3OutputStreamWrapper_methods(root_module, cls): ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> arg0) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'arg0')]) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def main(): out = FileCodeSink(sys.stdout) root_module = module_init() register_types(root_module) register_methods(root_module) register_functions(root_module) root_module.generate(out) if __name__ == '__main__': main()
binhqnguyen/lena
src/visualizer/bindings/modulegen__gcc_LP64.py
Python
gpl-2.0
396,141
import pytz import lxml import dateutil.parser import datetime from openstates.utils import LXMLMixin from pupa.scrape import Scraper, Event class MAEventScraper(Scraper, LXMLMixin): _TZ = pytz.timezone("US/Eastern") date_format = "%m/%d/%Y" def scrape(self, chamber=None, start=None, end=None): if start is None: start_date = datetime.datetime.now().strftime(self.date_format) else: start_date = datetime.datetime.strptime(start, "%Y-%m-%d") start_date = start_date.strftime(self.date_format) # default to 30 days if no end if end is None: dtdelta = datetime.timedelta(days=30) end_date = datetime.datetime.now() + dtdelta end_date = end_date.strftime(self.date_format) else: end_date = datetime.datetime.strptime(end, "%Y-%m-%d") end_date = end_date.strftime(self.date_format) url = "https://malegislature.gov/Events/FilterEventResults" params = { "EventType": "", "Branch": "", "EventRangeType": "", "StartDate": start_date, "EndDate": end_date, "X-Requested-With": "XMLHttpRequest", } page = self.post(url, params) page = lxml.html.fromstring(page.content) page.make_links_absolute("https://malegislature.gov/") rows = page.xpath("//table[contains(@class,'eventTable')]/tbody/tr") for row in rows: # Some rows have an additional TD at the start, # so index em all as offsets td_ct = len(row.xpath("td")) # Skip meetings of the chamber event_type = row.xpath("string(td[{}])".format(td_ct - 3)) if event_type == "Session": continue url = row.xpath("td[{}]/a/@href".format(td_ct - 2))[0] yield from self.scrape_event_page(url, event_type) def scrape_event_page(self, url, event_type): page = self.lxmlize(url) page.make_links_absolute("https://malegislature.gov/") title = page.xpath('string(//div[contains(@class,"followable")]/h1)') title = title.replace("Hearing Details", "").strip() title = title.replace("Special Event Details", "") start_day = page.xpath( 'string(//dl[contains(@class,"eventInformation")]/dd[2])' ).strip() start_time = page.xpath( 'string(//dl[contains(@class,"eventInformation")]/dd[3])' ).strip() location = page.xpath( 'string(//dl[contains(@class,"eventInformation")]/dd[4]//a)' ).strip() description = page.xpath( 'string(//dl[contains(@class,"eventInformation")]/dd[5])' ).strip() start_date = self._TZ.localize( dateutil.parser.parse("{} {}".format(start_day, start_time)) ) event = Event( start_date=start_date, name=title, location_name=location, description=description, ) event.add_source(url) agenda_rows = page.xpath( '//div[contains(@class,"col-sm-8") and .//h2[contains(@class,"agendaHeader")]]' '/div/div/div[contains(@class,"panel-default")]' ) for row in agenda_rows: # only select the text node, not the spans agenda_title = row.xpath( "string(.//h4/a/text()[normalize-space()])" ).strip() if agenda_title == "": agenda_title = row.xpath( "string(.//h4/text()[normalize-space()])" ).strip() agenda = event.add_agenda_item(description=agenda_title) bills = row.xpath(".//tbody/tr/td[1]/a/text()") for bill in bills: bill = bill.strip().replace(".", " ") agenda.add_bill(bill) if event_type == "Hearing": event.add_participant(title, type="committee", note="host") yield event
openstates/openstates
openstates/ma/events.py
Python
gpl-3.0
4,059
from mindfeed.mindfeed import main if __name__ == "__main__": main()
zeckalpha/mindfeed
mindfeed/__init__.py
Python
mit
75
#!/usr/bin/env python from struct import *; from collections import namedtuple; import getopt; import sys; class MdbShmReader: def __init__(self,filename): self.filename = filename; self.readFile(); def readFile(self): try: self.fd = open(self.filename,"r"); except: print "open file failed" exit(-1); def getPoolInfo(self): try: self.fd.seek(0); buf = self.fd.read(20); poolinfo = namedtuple('poolinfo','inited page_size total_pgaes free_pages current_page'); self.mpool = poolinfo._make(unpack('iiiii',buf)); #print "\033[0;32mMdb Info:\033[0;m" print " " print " inited :",self.mpool.inited print " page_size :",self.mpool.page_size print " total_pgaes :",self.mpool.total_pgaes print " free_pages :",self.mpool.free_pages print " current_page :",self.mpool.current_page print " " except: print "getPoolInfo failed" pass; def getCacheInfo(self): try: self.fd.seek(524288); buf = self.fd.read(16); cacheinfo = namedtuple('cacheinfo','inited max_slab_id base_size factor'); self.cinfo = cacheinfo._make(unpack('iiif',buf)); #print self.cinfo; print " cache info:" print " inited :",self.cinfo.inited; print " max_slab_id :",self.cinfo.max_slab_id; print " base_size :",self.cinfo.base_size; print " " except: pass; def getSlabInfo(self): #try: self.fd.seek(524288+16); print "id -- size -- perslab -- item_count--evict_count--full_pages--partial_pages--free_pages" for i in range(0,self.cinfo.max_slab_id+1): self.fd.read(16); #Pool & Cache pointer buf = self.fd.read(16); slabinfo = namedtuple('slabinfo','slabid slabsize perslab page_size'); sinfo = slabinfo._make(unpack('iiii',buf)); #print sinfo; ilist = namedtuple('ilist','head tail'); buf = self.fd.read(16); ilist_e = ilist._make(unpack('LL',buf)); self.fd.read(32752); #self.fd.read(32768); #list & info buf = self.fd.read(28); slabinfo_2 = namedtuple('slabinfo_2','item_count evict_count full_pages partial_pages free_pages'); sinfo_2 = slabinfo_2._make(unpack('lliii',buf)); #print sinfo_2; self.fd.read(20); #list etc. print "%2d"%sinfo.slabid,"%8d"%sinfo.slabsize,"%8d"%sinfo.perslab,"%12d"%sinfo_2.item_count,"%12d"%sinfo_2.evict_count,"%8d"%sinfo_2.full_pages,"%10d"%sinfo_2.partial_pages,"%10d"%sinfo_2.free_pages,"%10d"%ilist_e.head,"%10d"%ilist_e.tail partial_len = ((sinfo.perslab + 9) / 10 ) * 4; self.fd.read(partial_len); #except: # pass def getHashInfo(self): try: self.fd.seek(16384); buf = self.fd.read(16); hashinfo = namedtuple('hashinfo','inited bucket_size item_count start_page'); self.hinfo = hashinfo._make(unpack('iiii',buf)); #print self.hinfo; print " Hash Info:" print " inited :",self.hinfo.inited; print " bucket_size :",self.hinfo.bucket_size; print " item_count :",self.hinfo.item_count; print " start_page :",self.hinfo.start_page; print " " except: pass; def getBitMapInfo(self): try: self.fd.seek(20); buf = self.fd.read(8192); start=0; end=0; prev=(); for b in buf: t = unpack('c',b); if prev==(): pass; elif prev == t: end += 1; else: print start,"-",end,":",prev.__str__()[4:6] end += 1; start = end; prev = t; print start,"-",end,":",prev.__str__()[4:6]; except: pass; def getHashTable(self): #try: self.getHashInfo(); self.fd.seek(self.mpool.page_size * self.hinfo.start_page); bucket = None; for i in range (0,self.hinfo.bucket_size): buf = self.fd.read(8); bucket = unpack('L',buf); if bucket[0] == 0: continue; print "bucket","%8d"%i, old_pos = self.fd.tell(); while bucket[0] != 0: print "->","%20d"%bucket[0], page_id,slab_size,page_offset = MdbShmReader.idToDetail(bucket[0]); self.fd.seek(page_id * self.mpool.page_size + slab_size * page_offset + 24); buf = self.fd.read(8); #h_next bucket = unpack('L',buf); print "" self.fd.seek(old_pos); #except: # pass; def getStatInfo(self): try: self.fd.seek(32768); print "area quota datasize itemcount hit get put rem evict" for i in range(0,1024): buf = self.fd.read(72); statinfo = namedtuple('statinfo','quota data_size space_size item_count hit_count get_count put_count remove_count evict_count'); sinfo = statinfo._make(unpack('LLLLLLLLL',buf)); if sinfo.quota != 0 or sinfo.item_count != 0: print "%4d"%i,"%12d"%sinfo.quota,"%12d"%sinfo.data_size,"%12d"%sinfo.item_count,"%12d"%sinfo.hit_count,"%12d"%sinfo.get_count,"%12d"%sinfo.put_count,"%12d"%sinfo.remove_count,"%12d"%sinfo.evict_count except: print "except" pass; @staticmethod def idToDetail(id): #try: # self.cinfo #except NameError: # self.cinfo = None; #if self.cinfo is None: # self.getCacheInfo(); page_id=((id>>36) & ((1<<16)-1)); slab_size=((id)&((1<<20)-1)); page_offset=((id>>20)&((1<<16)-1)); return (page_id,slab_size,page_offset); def whichSlab(size): start=62 factor=1.1 pagesize=1048576 slab_array=[] i=0 while (i<100 and start < pagesize/2): slab_array.append(start); start = int(start * factor); start = ((start + 7) & (~0x7)); slab_array.append(1048552); #print slab_array; i=0 while size+46+2 > slab_array[i]: i+=1; print i,":",slab_array[i] def main(): try: opts,args = getopt.getopt(sys.argv[1:],"f:i:s:"); except getopt.GetOptError,err: exit(-1); viewid=False; id=None; filename = None; slabsize = None; for o,a in opts: if o == "-i": viewid=True; try: id=int(a,10); except ValueError: id=int(a,16); elif o == "-f": filename = a; elif o == "-s": slabsize = int(a); if filename is None and id is None and slabsize is None: usage(); exit(-1); if viewid: page_id,slab_size,page_offset = MdbShmReader.idToDetail(id); print "page_id:",page_id,"slab_size:",slab_size,"page_offset:",page_offset elif slabsize: whichSlab(slabsize); else: reader = MdbShmReader(filename); reader.getPoolInfo(); reader.getCacheInfo(); reader.getHashInfo(); reader.getStatInfo(); #reader.getBitMapInfo(); reader.getSlabInfo(); #reader.getHashTable(); def usage(): print "mdbshm_reader.py -f shm file" print " -i id" print " -s size" if __name__ == "__main__": main();
zbcwilliam/tair-rdb-modified
scripts/mdbshm_reader.py
Python
gpl-2.0
6,414
# Copyright (c) 2015. # Philipp Wagner <bytefish[at]gmx[dot]de> and # Florian Lier <flier[at]techfak.uni-bielefeld.de> and # Norman Koester <nkoester[at]techfak.uni-bielefeld.de> # # # Released to public domain under terms of the BSD Simplified license. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the organization nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # See <http://www.opensource.org/licenses/bsd-license> # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import os as os from ocvfacerec.facerec.normalization import minmax import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm # try to import the PIL Image module try: from PIL import Image except ImportError: import Image import math as math def create_font(fontname='Tahoma', fontsize=10): return {'fontname': fontname, 'fontsize': fontsize} def plot_gray(X, sz=None, filename=None): if not sz is None: X = X.reshape(sz) X = minmax(I, 0, 255) fig = plt.figure() implot = plt.imshow(np.asarray(Ig), cmap=cm.gray) if filename is None: plt.show() else: fig.savefig(filename, format="png", transparent=False) def plot_eigenvectors(eigenvectors, num_components, sz, filename=None, start_component=0, rows=None, cols=None, title="Subplot", color=True): if (rows is None) or (cols is None): rows = cols = int(math.ceil(np.sqrt(num_components))) num_components = np.min(num_components, eigenvectors.shape[1]) fig = plt.figure() for i in range(start_component, num_components): vi = eigenvectors[0:, i].copy() vi = minmax(np.asarray(vi), 0, 255, dtype=np.uint8) vi = vi.reshape(sz) ax0 = fig.add_subplot(rows, cols, (i - start_component) + 1) plt.setp(ax0.get_xticklabels(), visible=False) plt.setp(ax0.get_yticklabels(), visible=False) plt.title("%s #%d" % (title, i), create_font('Tahoma', 10)) if color: implot = plt.imshow(np.asarray(vi)) else: implot = plt.imshow(np.asarray(vi), cmap=cm.grey) if filename is None: fig.show() else: fig.savefig(filename, format="png", transparent=False) def subplot(title, images, rows, cols, sptitle="subplot", sptitles=[], colormap=cm.gray, ticks_visible=True, filename=None): fig = plt.figure() # main title fig.text(.5, .95, title, horizontalalignment='center') for i in xrange(len(images)): ax0 = fig.add_subplot(rows, cols, (i + 1)) plt.setp(ax0.get_xticklabels(), visible=False) plt.setp(ax0.get_yticklabels(), visible=False) if len(sptitles) == len(images): plt.title("%s #%s" % (sptitle, str(sptitles[i])), create_font('Tahoma', 10)) else: plt.title("%s #%d" % (sptitle, (i + 1)), create_font('Tahoma', 10)) plt.imshow(np.asarray(images[i]), cmap=colormap) if filename is None: plt.show() else: fig.savefig(filename)
warp1337/opencv_facerecognizer
src/ocvfacerec/facerec/visual.py
Python
bsd-3-clause
4,343
import numpy as np import lmfit class SinglePoleStep: def __init__(self, amp, tau): self.amp_s = amp self.tau_s = tau self.amp_k = self.amp_s/(self.amp_s-1.) self.tau_k = (1.-self.amp_s)*self.tau_s self.step_func = lambda t: 1.-self.amp_s*np.exp(-t/self.tau_s) self.kernel_step_func = lambda t: 1.+self.amp_k*np.exp(-t/self.tau_k) self.step_model = lmfit.Model(self.step_func) self.kernel_step_model = lmfit.Model(self.kernel_step_func)
DiCarloLab-Delft/PycQED_py3
pycqed/measurement/distortions_models.py
Python
mit
507
""" find 2 nodes in a binary search tree which make a + b = k. """ class Solution : def twosum(self, root, k): # naive solution # inorder traversal -> array -> 2sum problem. O(n) time O(n) space. # optimization: # Cannot improve time, only space to O(logn) by using stack. stack_left = [] stack_right = [] node1 = root node2 = root # left most -> smallest while node1: stack_left.append(node1) node1 = node1.left # right most -> largest while node2: stack_right.append(node2) node2 = node2.right # 2 sum problem while len(stack_left) > 0 and len(stack_right) > 0: if stack_left[-1].val + stack_right[-1].val < k: node = stack_left.pop() if node.right: stack_left.append(node.right) node = node.right.left while node: stack_left.append(node) node = node.left elif stack_left[-1].val + stack.right[-1].val > k: node = stack_right.pop() if node.left: stack_right.append(node.left) node = node.left.right while node: stack_right.append(node) node = node.right else: return node_right[-1], node_left[-1] return None
linyaoli/acm
tree/hard/2sum_in_binary_search_tree.py
Python
gpl-2.0
1,516
# --------------------------------------------------------------------------- # # BALLOONTIP wxPython IMPLEMENTATION # Python Code By: # # Andrea Gavana, @ 29 May 2005 # Latest Revision: 23 Nov 2009, 09.00 GMT # # # TODO List/Caveats # # 1. With wx.ListBox (And Probably Other Controls), The BalloonTip Sometimes # Flashes (It Is Created And Suddenly Destroyed). I Don't Know What Is # Happening. Probably I Don't Handle Correctly The wx.EVT_ENTER_WINDOW # wx.EVT_LEAVE_WINDOW? # # 2. wx.RadioBox Seems Not To Receive The wx.EVT_ENTER_WINDOW Event # # 3. wx.SpinCtrl (And Probably Other Controls), When Put In A Sizer, Does Not # Return The Correct Size/Position. Probably Is Something I Am Missing. # # 4. Other Issues? # # # FIXED Problems # # 1. Now BalloonTip Control Works Also For TaskBarIcon (Thanks To Everyone # For The Suggetions I Read In The wxPython Mailing List) # # # For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please # Write To Me At: # # [email protected] # [email protected] # # Or, Obviously, To The wxPython Mailing List!!! # # # End Of Comments # --------------------------------------------------------------------------- # """ BalloonTip is a class that allows you to display tooltips in a balloon style window. Description =========== BalloonTip is a class that allows you to display tooltips in a balloon style window (actually a frame), similarly to the windows XP balloon help. There is also an arrow that points to the center of the control designed as a "target" for the BalloonTip. What it can do: - Set the balloon shape as a rectangle or a rounded rectangle; - Set an icon to the top-left of the BalloonTip frame; - Set a title at the top of the BalloonTip frame; - Automatic "best" placement of BalloonTip frame depending on the target control/window position; - Runtime customization of title/tip fonts and foreground colours; - Runtime change of BalloonTip frame shape; - Set the balloon background colour; - Possibility to set the delay after which the BalloonTip is displayed; - Possibility to set the delay after which the BalloonTip is destroyed; - Three different behaviors for the BalloonTip window (regardless the delay destruction time set): a) Destroy by leave: the BalloonTip is destroyed when the mouse leaves the target control/window; b) Destroy by click: the BalloonTip is destroyed when you click on any area of the target control/window; c) Destroy by button: the BalloonTip is destroyed when you click on the top-right close button; - Possibility to enable/disable globally the BalloonTip on you application; - Set the BalloonTip also for the taskbar icon. Usage ===== Usage example:: # let's suppose that in your application you have a wx.TextCtrl defined as: mytextctrl = wx.TextCtrl(panel, -1, "i am a textctrl") # you can define your BalloonTip as follows: tipballoon = BalloonTip(topicon=None, toptitle="textctrl", message="this is a textctrl", shape=BT_ROUNDED, tipstyle=BT_LEAVE) # set the BalloonTip target tipballoon.SetTarget(mytextctrl) # set the BalloonTip background colour tipballoon.SetBalloonColour(wx.white) # set the font for the balloon title tipballoon.SetTitleFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False)) # set the colour for the balloon title tipballoon.SetTitleColour(wx.BLACK) # leave the message font as default tipballoon.SetMessageFont() # set the message (tip) foreground colour tipballoon.SetMessageColour(wx.LIGHT_GREY) # set the start delay for the BalloonTip tipballoon.SetStartDelay(1000) # set the time after which the BalloonTip is destroyed tipballoon.SetEndDelay(3000) Window Styles ============= This class supports the following window styles: ================ =========== ================================================== Window Styles Hex Value Description ================ =========== ================================================== ``BT_ROUNDED`` 0x1 `BalloonTip` will have a rounded rectangular shape. ``BT_RECTANGLE`` 0x2 `BalloonTip` will have a rectangular shape. ``BT_LEAVE`` 0x3 `BalloonTip` will be destroyed when the user moves the mouse outside the target window. ``BT_CLICK`` 0x4 `BalloonTip` will be destroyed when the user click on `BalloonTip`. ``BT_BUTTON`` 0x5 `BalloonTip` will be destroyed when the user click on the close button. ================ =========== ================================================== Events Processing ================= `No custom events are available for this class.` License And Version =================== BalloonTip is distributed under the wxPython license. Latest revision: Andrea Gavana @ 23 Nov 2009, 09.00 GMT Version 0.2 """ import wx import time from wx.lib.buttons import GenButton # Define The Values For The BalloonTip Frame Shape BT_ROUNDED = 1 """ `BalloonTip` will have a rounded rectangular shape. """ BT_RECTANGLE = 2 """ `BalloonTip` will have a rectangular shape. """ # Define The Value For The BalloonTip Destruction Behavior BT_LEAVE = 3 """ `BalloonTip` will be destroyed when the user moves the mouse outside the target window. """ BT_CLICK = 4 """ `BalloonTip` will be destroyed when the user click on `BalloonTip`. """ BT_BUTTON = 5 """ `BalloonTip` will be destroyed when the user click on the close button. """ # --------------------------------------------------------------- # Class BalloonFrame # --------------------------------------------------------------- # This Class Is Called By The Main BalloonTip Class, And It Is # Responsible For The Frame Creation/Positioning On Screen # Depending On Target Control/Window, The Frame Can Position # Itself To NW (Default), NE, SW, SE. The Switch On Positioning # Is Done By Calculating The Absolute Position Of The Target # Control/Window Plus/Minus The BalloonTip Size. The Pointing # Arrow Is Positioned Accordingly. # --------------------------------------------------------------- class BalloonFrame(wx.Frame): """ This class is called by the main L{BalloonTip} class, and it is responsible for the frame creation/positioning on screen depending on target control/window, the frame can position itself to NW (default), NE, SW, SE. The switch on positioning is done by calculating the absolute position of the target control/window plus/minus the balloontip size. The pointing arrow is positioned accordingly. """ def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, classparent=None): """ Default class constructor. Used internally. Do not call directly this class in your application! """ wx.Frame.__init__(self, None, -1, "BalloonTip", pos, size, style=wx.FRAME_SHAPED | wx.SIMPLE_BORDER | wx.FRAME_NO_TASKBAR | wx.STAY_ON_TOP) self._parent = classparent self._toptitle = self._parent._toptitle self._topicon = self._parent._topicon self._message = self._parent._message self._shape = self._parent._shape self._tipstyle = self._parent._tipstyle self._ballooncolour = self._parent._ballooncolour self._balloonmsgcolour = self._parent._balloonmsgcolour self._balloonmsgfont = self._parent._balloonmsgfont if self._toptitle != "": self._balloontitlecolour = self._parent._balloontitlecolour self._balloontitlefont = self._parent._balloontitlefont panel = wx.Panel(self, -1) sizer = wx.BoxSizer(wx.VERTICAL) self.panel = panel subsizer = wx.BoxSizer(wx.VERTICAL) hsizer = wx.BoxSizer(wx.HORIZONTAL) subsizer.Add((0,20), 0, wx.EXPAND) if self._topicon is not None: stb = wx.StaticBitmap(panel, -1, self._topicon) hsizer.Add(stb, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 10) self._balloonbmp = stb if self._toptitle != "": stt = wx.StaticText(panel, -1, self._toptitle) stt.SetFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False)) if self._topicon is None: hsizer.Add((10,0), 0, wx.EXPAND) hsizer.Add(stt, 1, wx.EXPAND | wx.TOP, 10) self._balloontitle = stt self._balloontitle.SetForegroundColour(self._balloontitlecolour) self._balloontitle.SetFont(self._balloontitlefont) if self._tipstyle == BT_BUTTON: self._closebutton = GenButton(panel, -1, "X", style=wx.NO_BORDER) self._closebutton.SetMinSize((16,16)) self._closebutton.SetFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False)) self._closebutton.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterButton) self._closebutton.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveButton) self._closebutton.SetUseFocusIndicator(False) if self._toptitle != "": hsizer.Add(self._closebutton, 0, wx.TOP | wx.RIGHT, 5) else: hsizer.Add((10,0), 1, wx.EXPAND) hsizer.Add(self._closebutton, 0, wx.ALIGN_RIGHT | wx.TOP | wx.RIGHT, 5) if self._topicon is not None or self._toptitle != "" \ or self._tipstyle == BT_BUTTON: subsizer.Add(hsizer, 0, wx.EXPAND | wx.BOTTOM, 5) self._firstline = line = wx.StaticLine(panel, -1, style=wx.LI_HORIZONTAL) if self._topicon is not None or self._toptitle != "" \ or self._tipstyle == BT_BUTTON: subsizer.Add(self._firstline, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) else: subsizer.Add(self._firstline, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.TOP, 10) mainstt = wx.StaticText(panel, -1, self._message) self._balloonmsg = mainstt self._balloonmsg.SetForegroundColour(self._balloonmsgcolour) self._balloonmsg.SetFont(self._balloonmsgfont) subsizer.Add(self._balloonmsg, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) self._secondline = wx.StaticLine(panel, -1, style=wx.LI_HORIZONTAL) subsizer.Add(self._secondline, 0, wx.EXPAND | wx.LEFT | wx.RIGHT, 10) subsizer.Add((0,0),1) panel.SetSizer(subsizer) sizer.Add(panel, 1, wx.EXPAND) self.SetSizerAndFit(sizer) sizer.Layout() if self._tipstyle == BT_CLICK: if self._toptitle != "": self._balloontitle.Bind(wx.EVT_LEFT_DOWN, self.OnClose) if self._topicon is not None: self._balloonbmp.Bind(wx.EVT_LEFT_DOWN, self.OnClose) self._balloonmsg.Bind(wx.EVT_LEFT_DOWN, self.OnClose) self.panel.Bind(wx.EVT_LEFT_DOWN, self.OnClose) elif self._tipstyle == BT_BUTTON: self._closebutton.Bind(wx.EVT_BUTTON, self.OnClose) self.panel.SetBackgroundColour(self._ballooncolour) if wx.Platform == "__WXGTK__": self.Bind(wx.EVT_WINDOW_CREATE, self.SetBalloonShape) else: self.SetBalloonShape() self.Show(True) def SetBalloonShape(self, event=None): """ Sets the balloon shape. :param `event`: on wxGTK, a `wx.WindowCreateEvent` event to process. """ size = self.GetSize() pos = self.GetPosition() dc = wx.MemoryDC(wx.EmptyBitmap(1,1)) textlabel = self._balloonmsg.GetLabel() textfont = self._balloonmsg.GetFont() textextent = dc.GetFullTextExtent(textlabel, textfont) boxheight = size.y - textextent[1]*len(textlabel.split("\n")) boxwidth = size.x position = wx.GetMousePosition() xpos = position[0] ypos = position[1] if xpos > 20 and ypos > 20: # This Is NW Positioning positioning = "NW" xpos = position[0] - boxwidth + 20 ypos = position[1] - boxheight - 20 elif xpos <= 20 and ypos <= 20: # This Is SE Positioning positioning = "SE" xpos = position[0] - 20 ypos = position[1] elif xpos > 20 and ypos <= 20: # This Is SW Positioning positioning = "SW" xpos = position[0] - boxwidth + 20 ypos = position[1] else: # This Is NE Positioning positioning = "NE" xpos = position[0] ypos = position[1] - boxheight + 20 bmp = wx.EmptyBitmap(size.x,size.y) dc = wx.BufferedDC(None, bmp) dc.BeginDrawing() dc.SetBackground(wx.Brush(wx.Colour(0,0,0), wx.SOLID)) dc.Clear() dc.SetPen(wx.Pen(wx.Colour(0,0,0), 1, wx.TRANSPARENT)) if self._shape == BT_ROUNDED: dc.DrawRoundedRectangle(0, 20, boxwidth, boxheight-20, 12) elif self._shape == BT_RECTANGLE: dc.DrawRectangle(0, 20, boxwidth, boxheight-20) if positioning == "NW": dc.DrawPolygon(((boxwidth-40, boxheight), (boxwidth-20, boxheight+20), (boxwidth-20, boxheight))) elif positioning == "SE": dc.DrawPolygon(((20, 20), (20, 0), (40, 20))) elif positioning == "SW": dc.DrawPolygon(((boxwidth-40, 20), (boxwidth-20, 0), (boxwidth-20, 20))) else: dc.DrawPolygon(((20, boxheight), (20, boxheight+20), (40, boxheight))) dc.EndDrawing() r = wx.RegionFromBitmapColour(bmp, wx.Colour(0,0,0)) self.hasShape = self.SetShape(r) if self._tipstyle == BT_BUTTON: colour = self.panel.GetBackgroundColour() self._closebutton.SetBackgroundColour(colour) self.SetPosition((xpos, ypos)) def OnEnterButton(self, event): """ Handles the ``wx.EVT_ENTER_WINDOW`` for the L{BalloonTip} button. When the L{BalloonTip} is created with the `tipstyle` = ``BT_BUTTON``, this event provide some kind of 3D effect when the mouse enters the button area. :param `event`: a `wx.MouseEvent` event to be processed. """ button = event.GetEventObject() colour = button.GetBackgroundColour() red = colour.Red() green = colour.Green() blue = colour.Blue() if red < 30: red = red + 30 if green < 30: green = green + 30 if blue < 30: blue = blue + 30 colour = wx.Colour(red-30, green-30, blue-30) button.SetBackgroundColour(colour) button.SetForegroundColour(wx.WHITE) button.Refresh() event.Skip() def OnLeaveButton(self, event): """ Handles the ``wx.EVT_LEAVE_WINDOW`` for the L{BalloonTip} button. When the L{BalloonTip} is created with the `tipstyle` = ``BT_BUTTON``, this event provide some kind of 3D effect when the mouse enters the button area. :param `event`: a `wx.MouseEvent` event to be processed. """ button = event.GetEventObject() colour = self.panel.GetBackgroundColour() button.SetBackgroundColour(colour) button.SetForegroundColour(wx.BLACK) button.Refresh() event.Skip() def OnClose(self, event): """ Handles the ``wx.EVT_CLOSE`` event for L{BalloonTip}. :param `event`: a `wx.CloseEvent` event to be processed. """ if isinstance(self._parent._widget, wx.TaskBarIcon): self._parent.taskbarcreation = 0 self._parent.taskbartime.Stop() del self._parent.taskbartime del self._parent.BalloonFrame self.Destroy() # --------------------------------------------------------------- # Class BalloonTip # --------------------------------------------------------------- # This Is The Main BalloonTip Implementation # --------------------------------------------------------------- class BalloonTip(object): """ BalloonTip is a class that allows you to display tooltips in a balloon style window. This is the main class implementation. """ def __init__(self, topicon=None, toptitle="", message="", shape=BT_ROUNDED, tipstyle=BT_LEAVE): """ Default class constructor. :param `topicon`: an icon that will be displayed on the top-left part of the L{BalloonTip} frame. If set to ``None``, no icon will be displayed; :param `toptitle`: a title that will be displayed on the top part of the L{BalloonTip} frame. If set to an empty string, no title will be displayed; :param `message`: the tip message that will be displayed. It can not be set to an empty string; :param `shape`: the L{BalloonTip} shape. It can be one of the following: ======================= ========= ==================================== Shape Flag Hex Value Description ======================= ========= ==================================== ``BT_ROUNDED`` 0x1 `BalloonTip` will have a rounded rectangular shape. ``BT_RECTANGLE`` 0x2 `BalloonTip` will have a rectangular shape. ======================= ========= ==================================== :param `tipstyle`: the L{BalloonTip} destruction behavior. It can be one of: ======================= ========= ==================================== Tip Flag Hex Value Description ======================= ========= ==================================== ``BT_LEAVE`` 0x3 `BalloonTip` will be destroyed when the user moves the mouse outside the target window. ``BT_CLICK`` 0x4 `BalloonTip` will be destroyed when the user click on `BalloonTip`. ``BT_BUTTON`` 0x5 `BalloonTip` will be destroyed when the user click on the close button. ======================= ========= ==================================== """ self._shape = shape self._topicon = topicon self._toptitle = toptitle self._message = message self._tipstyle = tipstyle app = wx.GetApp() self._runningapp = app self._runningapp.__tooltipenabled__ = True if self._message == "": raise Exception("\nERROR: You Should At Least Set The Message For The BalloonTip") if self._shape not in [BT_ROUNDED, BT_RECTANGLE]: raise Exception('\nERROR: BalloonTip Shape Should Be One Of "BT_ROUNDED", "BT_RECTANGLE"') if self._tipstyle not in [BT_LEAVE, BT_CLICK, BT_BUTTON]: raise Exception('\nERROR: BalloonTip TipStyle Should Be One Of "BT_LEAVE", '\ '"BT_CLICK", "BT_BUTTON"') self.SetStartDelay() self.SetEndDelay() self.SetBalloonColour() if toptitle != "": self.SetTitleFont() self.SetTitleColour() if topicon is not None: self.SetBalloonIcon(topicon) self.SetMessageFont() self.SetMessageColour() def SetTarget(self, widget): """ Sets the target control/window for the L{BalloonTip}. :param `widget`: an instance of `wx.Window`. """ self._widget = widget if isinstance(widget, wx.TaskBarIcon): self._widget.Bind(wx.EVT_TASKBAR_MOVE, self.OnTaskBarMove) self._widget.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy) self.taskbarcreation = 0 else: self._widget.Bind(wx.EVT_ENTER_WINDOW, self.OnWidgetEnter) self._widget.Bind(wx.EVT_LEAVE_WINDOW, self.OnWidgetLeave) self._widget.Bind(wx.EVT_MOTION, self.OnWidgetMotion) self._widget.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy) def GetTarget(self): """ Returns the target window for the L{BalloonTip}.""" if not hasattr(self, "_widget"): raise Exception("\nERROR: BalloonTip Target Has Not Been Set") return self._widget def SetStartDelay(self, delay=1): """ Sets the delay time after which the L{BalloonTip} is created. :param `delay`: the number of milliseconds after which L{BalloonTip} is created. """ if delay < 1: raise Exception("\nERROR: Delay Time For BalloonTip Creation Should Be Greater Than 1 ms") self._startdelaytime = float(delay) def GetStartDelay(self): """ Returns the delay time after which the L{BalloonTip} is created.""" return self._startdelaytime def SetEndDelay(self, delay=1e6): """ Sets the delay time after which the BalloonTip is destroyed. :param `delay`: the number of milliseconds after which L{BalloonTip} is destroyed. """ if delay < 1: raise Exception("\nERROR: Delay Time For BalloonTip Destruction Should Be Greater Than 1 ms") self._enddelaytime = float(delay) def GetEndDelay(self): """ Returns the delay time after which the L{BalloonTip} is destroyed.""" return self._enddelaytime def OnWidgetEnter(self, event): """ Handles the ``wx.EVT_ENTER_WINDOW`` for the target control/window and starts the L{BalloonTip} timer for creation. :param `event`: a `wx.MouseEvent` event to be processed. """ if hasattr(self, "BalloonFrame"): if self.BalloonFrame: return if not self._runningapp.__tooltipenabled__: return self.showtime = wx.PyTimer(self.NotifyTimer) self.showtime.Start(self._startdelaytime) event.Skip() def OnWidgetLeave(self, event): """ Handles the ``wx.EVT_LEAVE_WINDOW`` for the target control/window. :param `event`: a `wx.MouseEvent` event to be processed. :note: If the BalloonTip `tipstyle` is set to ``BT_LEAVE``, the L{BalloonTip} is destroyed. """ if hasattr(self, "showtime"): if self.showtime: self.showtime.Stop() del self.showtime if hasattr(self, "BalloonFrame"): if self.BalloonFrame: if self._tipstyle == BT_LEAVE: endtime = time.time() if endtime - self.starttime > 0.1: try: self.BalloonFrame.Destroy() except: pass else: event.Skip() else: event.Skip() else: event.Skip() def OnTaskBarMove(self, event): """ Handles the mouse motion inside the taskbar icon area. :param `event`: a `wx.MouseEvent` event to be processed. """ if not hasattr(self, "BalloonFrame"): if self.taskbarcreation == 0: self.mousepos = wx.GetMousePosition() self.currentmousepos = self.mousepos self.taskbartime = wx.PyTimer(self.TaskBarTimer) self.taskbartime.Start(100) self.showtime = wx.PyTimer(self.NotifyTimer) self.showtime.Start(self._startdelaytime) if self.taskbarcreation == 0: self.taskbarcreation = 1 return event.Skip() def OnWidgetMotion(self, event): """ Handle the mouse motion inside the target. This prevents the annoying behavior of L{BalloonTip} to display when the user does something else inside the window. The L{BalloonTip} window is displayed only when the mouse does *not* move for the start delay time. """ if hasattr(self, "BalloonFrame"): if self.BalloonFrame: return if hasattr(self, "showtime"): if self.showtime: self.showtime.Start(self._startdelaytime) event.Skip() def NotifyTimer(self): """ The creation timer has expired. Creates the L{BalloonTip} frame.""" self.BalloonFrame = BalloonFrame(self._widget, classparent=self) self.BalloonFrame.Show(True) self.starttime = time.time() self.showtime.Stop() del self.showtime self.destroytime = wx.PyTimer(self.DestroyTimer) self.destroytime.Start(self._enddelaytime) def TaskBarTimer(self): """ This timer check periodically the mouse position. If the current mouse position is sufficiently far from the coordinates it had when entered the taskbar icon and the L{BalloonTip} style is ``BT_LEAVE``, the L{BalloonTip} frame is destroyed. """ self.currentmousepos = wx.GetMousePosition() mousepos = self.mousepos if abs(self.currentmousepos[0] - mousepos[0]) > 30 or \ abs(self.currentmousepos[1] - mousepos[1]) > 30: if hasattr(self, "BalloonFrame"): if self._tipstyle == BT_LEAVE: try: self.BalloonFrame.Destroy() self.taskbartime.Stop() del self.taskbartime del self.BalloonFrame self.taskbarcreation = 0 except: pass def DestroyTimer(self): """ The destruction timer has expired. Destroys the L{BalloonTip} frame.""" self.destroytime.Stop() del self.destroytime try: self.BalloonFrame.Destroy() except: pass def SetBalloonShape(self, shape=BT_ROUNDED): """ Sets the L{BalloonTip} frame shape. :param `shape`: should be one of ``BT_ROUNDED`` or ``BT_RECTANGLE``. """ if shape not in [BT_ROUNDED, BT_RECTANGLE]: raise Exception('\nERROR: BalloonTip Shape Should Be One Of "BT_ROUNDED", "BT_RECTANGLE"') self._shape = shape def GetBalloonShape(self): """ Returns the L{BalloonTip} frame shape.""" return self._shape def SetBalloonIcon(self, icon): """ Sets the L{BalloonTip} top-left icon. :param `icon`: an instance of `wx.Bitmap`. """ if icon.Ok(): self._topicon = icon else: raise Exception("\nERROR: Invalid Image Passed To BalloonTip") def GetBalloonIcon(self): """ Returns the L{BalloonTip} top-left icon.""" return self._topicon def SetBalloonTitle(self, title=""): """ Sets the L{BalloonTip} top title. :param `title`: a string to use as a L{BalloonTip} title. """ self._toptitle = title def GetBalloonTitle(self): """ Returns the L{BalloonTip} top title.""" return self._toptitle def SetBalloonMessage(self, message): """ Sets the L{BalloonTip} tip message. :param `message`: a string identifying the main message body of L{BalloonTip}. :note: The L{BalloonTip} message should never be empty. """ if len(message.strip()) < 1: raise Exception("\nERROR: BalloonTip Message Can Not Be Empty") self._message = message def GetBalloonMessage(self): """ Returns the L{BalloonTip} tip message.""" return self._message def SetBalloonTipStyle(self, tipstyle=BT_LEAVE): """ Sets the L{BalloonTip} `tipstyle` parameter. :param `tipstyle`: one of the following bit set: ============== ========== ===================================== Tip Style Hex Value Description ============== ========== ===================================== ``BT_LEAVE`` 0x3 `BalloonTip` will be destroyed when the user moves the mouse outside the target window. ``BT_CLICK`` 0x4 `BalloonTip` will be destroyed when the user click on `BalloonTip`. ``BT_BUTTON`` 0x5 `BalloonTip` will be destroyed when the user click on the close button. ============== ========== ===================================== """ if tipstyle not in [BT_LEAVE, BT_CLICK, BT_BUTTON]: raise Exception('\nERROR: BalloonTip TipStyle Should Be One Of "BT_LEAVE", '\ '"BT_CLICK", "BT_BUTTON"') self._tipstyle = tipstyle def GetBalloonTipStyle(self): """ Returns the L{BalloonTip} `tipstyle` parameter. :see: L{SetBalloonTipStyle} """ return self._tipstyle def SetBalloonColour(self, colour=None): """ Sets the L{BalloonTip} background colour. :param `colour`: a valid `wx.Colour` instance. """ if colour is None: colour = wx.Colour(255, 250, 205) self._ballooncolour = colour def GetBalloonColour(self): """ Returns the L{BalloonTip} background colour.""" return self._ballooncolour def SetTitleFont(self, font=None): """ Sets the font for the top title. :param `font`: a valid `wx.Font` instance. """ if font is None: font = wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False) self._balloontitlefont = font def GetTitleFont(self): """ Returns the font for the top title.""" return self._balloontitlefont def SetMessageFont(self, font=None): """ Sets the font for the tip message. :param `font`: a valid `wx.Font` instance. """ if font is None: font = wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False) self._balloonmsgfont = font def GetMessageFont(self): """ Returns the font for the tip message.""" return self._balloonmsgfont def SetTitleColour(self, colour=None): """ Sets the colour for the top title. :param `colour`: a valid `wx.Colour` instance. """ if colour is None: colour = wx.BLACK self._balloontitlecolour = colour def GetTitleColour(self): """ Returns the colour for the top title.""" return self._balloontitlecolour def SetMessageColour(self, colour=None): """ Sets the colour for the tip message. :param `colour`: a valid `wx.Colour` instance. """ if colour is None: colour = wx.BLACK self._balloonmsgcolour = colour def GetMessageColour(self): """ Returns the colour for the tip message.""" return self._balloonmsgcolour def OnDestroy(self, event): """ Handles the target destruction, specifically handling the ``wx.EVT_WINDOW_DESTROY`` event. :param `event`: a `wx.WindowDestroyEvent` event to be processed. """ if hasattr(self, "BalloonFrame"): if self.BalloonFrame: try: if isinstance(self._widget, wx.TaskBarIcon): self._widget.Unbind(wx.EVT_TASKBAR_MOVE) self.taskbartime.Stop() del self.taskbartime else: self._widget.Unbind(wx.EVT_MOTION) self._widget.Unbind(wx.EVT_LEAVE_WINDOW) self._widget.Unbind(wx.EVT_ENTER_WINDOW) self.BalloonFrame.Destroy() except: pass del self.BalloonFrame def EnableTip(self, enable=True): """ Enable/disable globally the L{BalloonTip}. :param `enable`: ``True`` to enable L{BalloonTip}, ``False`` otherwise. """ self._runningapp.__tooltipenabled__ = enable
163gal/Time-Line
libs64/wx/lib/agw/balloontip.py
Python
gpl-3.0
32,252
from StateMachine.State import State from StateMachine.StateMachine import StateMachine from StateMachine.InputAction import InputAction from GameData.GameData import GameData class StateT(State): state_stack = list() game_data = GameData() def __init__(self): self.transitions = None def next(self, input): if self.transitions.has_key(input): return self.transitions[input] else: raise Exception("Input not supported for current state") class NightBegins(StateT): def run(self): print("NightTime Falls") def next(self, input): StateT.state_stack.append(self) if not self.transitions: self.transitions = { InputAction.getGameData : GameStates.nightBegins, InputAction.playHeroCard : GameStates.nightBegins, InputAction.playQuestCard : GameStates.nightBegins, InputAction.drawDSCard : GameStates.drawDSCard, } return StateT.next(self, input) class DrawDSCard(StateT): def run(self): print("Darkness Spreads drawing card") StateT.current_ds_card = StateT.game_data.ds_cards.pop() StateT.current_ds_card.display() print "STACK: " + str(StateT.state_stack) def next(self, input): StateT.state_stack.append(self) if not self.transitions: self.transitions = { InputAction.getGameData : GameStates.nightBegins, InputAction.playHeroCard : GameStates.nightBegins, InputAction.playQuestCard : GameStates.nightBegins, InputAction.drawDSCard : GameStates.drawDSCard, InputAction.executeDSCard : GameStates.executeDSCard, } return StateT.next(self, input) class ExecuteDSCard(StateT): def run(self): print("Darkness Spreads - executing card") StateT.current_ds_card.execute(StateT.game_data) print "STACK: " + str(StateT.state_stack) def next(self, input): StateT.state_stack.append(self) if not self.transitions: self.transitions = { InputAction.getGameData : GameStates.nightBegins, InputAction.playHeroCard : GameStates.nightBegins, InputAction.playQuestCard : GameStates.nightBegins, InputAction.drawDSCard : GameStates.drawDSCard, InputAction.advanceToDay : GameStates.dayBegins, } return StateT.next(self, input) class DayBegins(StateT): def run(self): print("Day Time") print "STACK: " + str(StateT.state_stack) def next(self, input): if not self.transitions: self.transitions = { InputAction.getGameData : GameStates.nightBegins, InputAction.playHeroCard : GameStates.nightBegins, InputAction.PlayQuestCard : GameStates.nightBegins, InputAction.advanceToEvening : GameStates.eveningBegins, } return StateT.next(self, input) class EveningBegins(StateT): def run(self): print("Day Time") print "STACK: " + str(StateT.state_stack) def next(self, input): if not self.transitions: self.transitions = { InputAction.getGameData : GameStates.nightBegins, InputAction.playHeroCard : GameStates.nightBegins, InputAction.PlayQuestCard : GameStates.nightBegins, InputAction.advanceToNight : GameStates.nightBegins, } return StateT.next(self, input) class GameStates(StateMachine): def __init__(self): # Initial state StateMachine.__init__(self, GameStates.nightBegins) # Static variable initialization: GameStates.nightBegins = NightBegins() GameStates.drawDSCard = DrawDSCard() GameStates.executeDSCard = ExecuteDSCard() GameStates.eveningBegins = EveningBegins() GameStates.dayBegins = DayBegins()
jmacleod/dotr
GameStates.py
Python
gpl-2.0
3,904
# Copyright (c) 2015 Mirantis, 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 urllib from muranoclient.common import base class Category(base.Resource): def __repr__(self): return "<Category %s>" % self._info def data(self, **kwargs): return self.manager.data(self, **kwargs) class CategoryManager(base.Manager): resource_class = Category def list(self, **kwargs): """Get category list with pagination support. :param sort_keys: an array of fields used to sort the list (string) :param sort_dir: 'asc' or 'desc' for ascending or descending sort :param limit: maximum number of categories to return :param marker: begin returning categories that appear later in the category list than that represented by this marker id """ params = {} for key, value in kwargs.items(): if value: params[key] = value url = '/v1/catalog/categories?{0}'.format( urllib.parse.urlencode(params, True)) return self._list(url, response_key='categories') def get(self, id): return self._get('/v1/catalog/categories/{0}'.format(id)) def add(self, data): return self._create('/v1/catalog/categories', data) def delete(self, id): return self._delete('/v1/catalog/categories/{0}'.format(id))
openstack/python-muranoclient
muranoclient/v1/categories.py
Python
apache-2.0
1,930
# -*- coding: utf-8 # RUR-PLE: Roberge's Used Robot - a Python Learning Environment # images.py - Contains all images for RUR-PLE # Version 0.8.7 # Author: Andre Roberge Copyright 2005 # [email protected] import os import wx import conf # robots GREY_ROBOT_S = 'robot_s.png' GREY_ROBOT_N = 'robot_n.png' GREY_ROBOT_E = 'robot_e.png' GREY_ROBOT_W = 'robot_w.png' YELLOW_ROBOT_S = 'yellow_robot_s.png' YELLOW_ROBOT_N = 'yellow_robot_n.png' YELLOW_ROBOT_E = 'yellow_robot_e.png' YELLOW_ROBOT_W = 'yellow_robot_w.png' GREEN_ROBOT_S = 'green_robot_s.png' GREEN_ROBOT_N = 'green_robot_n.png' GREEN_ROBOT_E = 'green_robot_e.png' GREEN_ROBOT_W = 'green_robot_w.png' BLUE_ROBOT_S = 'blue_robot_s.png' BLUE_ROBOT_N = 'blue_robot_n.png' BLUE_ROBOT_E = 'blue_robot_e.png' BLUE_ROBOT_W = 'blue_robot_w.png' LIGHT_BLUE_ROBOT_S = 'light_blue_robot_s.png' LIGHT_BLUE_ROBOT_N = 'light_blue_robot_n.png' LIGHT_BLUE_ROBOT_E = 'light_blue_robot_e.png' LIGHT_BLUE_ROBOT_W = 'light_blue_robot_w.png' PURPLE_ROBOT_S = 'purple_robot_s.png' PURPLE_ROBOT_N = 'purple_robot_n.png' PURPLE_ROBOT_E = 'purple_robot_e.png' PURPLE_ROBOT_W = 'purple_robot_w.png' #== browser OPEN_HTML = 'folder_html.png' HOME = 'folder_home.png' BACK = 'back.png' FORWARD = 'forward.png' LANGUAGES = 'languages.png' #== Robot world RUN_PROGRAM = 'run1.png' SPEED = 'speed.png' STEP = 'step.png' STOP = 'stop.png' PAUSE = 'pause.png' WALL = 'wall.png' HIGHLIGHT = 'highlight.png' SHOW_WORLD_FILE = 'show_world_file.png' OPEN_PROGRAM = 'open_program.png' SAVE_PROGRAM = 'save_program.png' OPEN_WORLD = 'open_world.png' SAVE_WORLD = 'save_world.png' EDIT_WORLD = 'edit_world.png' RESET_WORLD = 'reset_world.png' ADD_REMOVE_ROBOT = 'add_robot.png' BEEPERS_ROBOT = 'beepers.png' RESIZE = 'resize.png' NEW_ROBOT_IMAGES = 'new_images.png' #== Python editor OPEN_PYTHON = 'open_py.png' SAVE_PYTHON = 'save_py.png' CLEAR_TEXT = 'clear_text.png' RUN_WITH = 'run_with.png' HELP = 'help.png' GOTO = 'goto.png' LAYOUT = 'layout.png' SHOW_HIDE = 'show_hide.png' # others SPLASH_SCREEN = 'splash_screen.png' ICON = 'rur16x16.png' HIT_WALL_IMAGE = 'ouch.png' MINI_SPLASH = 'splash_screen_small.png' settings = conf.getSettings() _imageBitmap = {} def getImage(imagePath): ''' ''' global _imageBitmap, settings if not imagePath in _imageBitmap: _imageBitmap[imagePath] = wx.Image( os.path.join(settings.IMAGE_DIR, imagePath), wx.BITMAP_TYPE_PNG).ConvertToBitmap() return _imageBitmap[imagePath] def setImage(imagePath, image): ''' ''' _imageBitmap[imagePath] = image
badbear1727/rur-ple
rur_py/images.py
Python
gpl-2.0
2,608
from flask import render_template, redirect, url_for, request from flask.views import MethodView from nastradini import mongo, utils from positionform import PositionForm class Position(MethodView): methods = ['GET', 'POST'] def get(self): form = PositionForm() return render_template('position.html', form=form) def post(self): # First, let's get the doc id. doc_id = utils.get_doc_id() # Create position info object. form = PositionForm(request.form) json = form.data # Store the document. mongo.db.positions.update({'_id': doc_id}, json, True) return redirect(url_for('browse_internal_positions'))
assemblio/project-nastradin
nastradini/views/forms/position.py
Python
gpl-2.0
700
#!/usr/bin/env python # -*- coding: utf-8 -*- # Scour # # Copyright 2010 Jeff Schiller # Copyright 2010 Louis Simard # # This file is part of Scour, http://www.codedread.com/scour/ # # 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. # Notes: # rubys' path-crunching ideas here: http://intertwingly.net/code/svgtidy/spec.rb # (and implemented here: http://intertwingly.net/code/svgtidy/svgtidy.rb ) # Yet more ideas here: http://wiki.inkscape.org/wiki/index.php/Save_Cleaned_SVG # # * Process Transformations # * Collapse all group based transformations # Even more ideas here: http://esw.w3.org/topic/SvgTidy # * analysis of path elements to see if rect can be used instead? (must also need to look # at rounded corners) # Next Up: # - why are marker-start, -end not removed from the style attribute? # - why are only overflow style properties considered and not attributes? # - only remove unreferenced elements if they are not children of a referenced element # - add an option to remove ids if they match the Inkscape-style of IDs # - investigate point-reducing algorithms # - parse transform attribute # - if a <g> has only one element in it, collapse the <g> (ensure transform, etc are carried down) # necessary to get true division from __future__ import division import os import sys import xml.dom.minidom import re import math from svg_regex import svg_parser from svg_transform import svg_transform_parser import optparse from yocto_css import parseCssString # Python 2.3- did not have Decimal try: from decimal import * except ImportError: print >>sys.stderr, "Scour requires Python 2.4." # Import Psyco if available try: import psyco psyco.full() except ImportError: pass APP = 'scour' VER = '0.26+r220' COPYRIGHT = 'Copyright Jeff Schiller, Louis Simard, 2012' NS = { 'SVG': 'http://www.w3.org/2000/svg', 'XLINK': 'http://www.w3.org/1999/xlink', 'SODIPODI': 'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd', 'INKSCAPE': 'http://www.inkscape.org/namespaces/inkscape', 'ADOBE_ILLUSTRATOR': 'http://ns.adobe.com/AdobeIllustrator/10.0/', 'ADOBE_GRAPHS': 'http://ns.adobe.com/Graphs/1.0/', 'ADOBE_SVG_VIEWER': 'http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/', 'ADOBE_VARIABLES': 'http://ns.adobe.com/Variables/1.0/', 'ADOBE_SFW': 'http://ns.adobe.com/SaveForWeb/1.0/', 'ADOBE_EXTENSIBILITY': 'http://ns.adobe.com/Extensibility/1.0/', 'ADOBE_FLOWS': 'http://ns.adobe.com/Flows/1.0/', 'ADOBE_IMAGE_REPLACEMENT': 'http://ns.adobe.com/ImageReplacement/1.0/', 'ADOBE_CUSTOM': 'http://ns.adobe.com/GenericCustomNamespace/1.0/', 'ADOBE_XPATH': 'http://ns.adobe.com/XPath/1.0/' } unwanted_ns = [ NS['SODIPODI'], NS['INKSCAPE'], NS['ADOBE_ILLUSTRATOR'], NS['ADOBE_GRAPHS'], NS['ADOBE_SVG_VIEWER'], NS['ADOBE_VARIABLES'], NS['ADOBE_SFW'], NS['ADOBE_EXTENSIBILITY'], NS['ADOBE_FLOWS'], NS['ADOBE_IMAGE_REPLACEMENT'], NS['ADOBE_CUSTOM'], NS['ADOBE_XPATH'] ] svgAttributes = [ 'clip-rule', 'display', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'font-family', 'font-size', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'line-height', 'marker', 'marker-end', 'marker-mid', 'marker-start', 'opacity', 'overflow', 'stop-color', 'stop-opacity', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'visibility' ] colors = { 'aliceblue': 'rgb(240, 248, 255)', 'antiquewhite': 'rgb(250, 235, 215)', 'aqua': 'rgb( 0, 255, 255)', 'aquamarine': 'rgb(127, 255, 212)', 'azure': 'rgb(240, 255, 255)', 'beige': 'rgb(245, 245, 220)', 'bisque': 'rgb(255, 228, 196)', 'black': 'rgb( 0, 0, 0)', 'blanchedalmond': 'rgb(255, 235, 205)', 'blue': 'rgb( 0, 0, 255)', 'blueviolet': 'rgb(138, 43, 226)', 'brown': 'rgb(165, 42, 42)', 'burlywood': 'rgb(222, 184, 135)', 'cadetblue': 'rgb( 95, 158, 160)', 'chartreuse': 'rgb(127, 255, 0)', 'chocolate': 'rgb(210, 105, 30)', 'coral': 'rgb(255, 127, 80)', 'cornflowerblue': 'rgb(100, 149, 237)', 'cornsilk': 'rgb(255, 248, 220)', 'crimson': 'rgb(220, 20, 60)', 'cyan': 'rgb( 0, 255, 255)', 'darkblue': 'rgb( 0, 0, 139)', 'darkcyan': 'rgb( 0, 139, 139)', 'darkgoldenrod': 'rgb(184, 134, 11)', 'darkgray': 'rgb(169, 169, 169)', 'darkgreen': 'rgb( 0, 100, 0)', 'darkgrey': 'rgb(169, 169, 169)', 'darkkhaki': 'rgb(189, 183, 107)', 'darkmagenta': 'rgb(139, 0, 139)', 'darkolivegreen': 'rgb( 85, 107, 47)', 'darkorange': 'rgb(255, 140, 0)', 'darkorchid': 'rgb(153, 50, 204)', 'darkred': 'rgb(139, 0, 0)', 'darksalmon': 'rgb(233, 150, 122)', 'darkseagreen': 'rgb(143, 188, 143)', 'darkslateblue': 'rgb( 72, 61, 139)', 'darkslategray': 'rgb( 47, 79, 79)', 'darkslategrey': 'rgb( 47, 79, 79)', 'darkturquoise': 'rgb( 0, 206, 209)', 'darkviolet': 'rgb(148, 0, 211)', 'deeppink': 'rgb(255, 20, 147)', 'deepskyblue': 'rgb( 0, 191, 255)', 'dimgray': 'rgb(105, 105, 105)', 'dimgrey': 'rgb(105, 105, 105)', 'dodgerblue': 'rgb( 30, 144, 255)', 'firebrick': 'rgb(178, 34, 34)', 'floralwhite': 'rgb(255, 250, 240)', 'forestgreen': 'rgb( 34, 139, 34)', 'fuchsia': 'rgb(255, 0, 255)', 'gainsboro': 'rgb(220, 220, 220)', 'ghostwhite': 'rgb(248, 248, 255)', 'gold': 'rgb(255, 215, 0)', 'goldenrod': 'rgb(218, 165, 32)', 'gray': 'rgb(128, 128, 128)', 'grey': 'rgb(128, 128, 128)', 'green': 'rgb( 0, 128, 0)', 'greenyellow': 'rgb(173, 255, 47)', 'honeydew': 'rgb(240, 255, 240)', 'hotpink': 'rgb(255, 105, 180)', 'indianred': 'rgb(205, 92, 92)', 'indigo': 'rgb( 75, 0, 130)', 'ivory': 'rgb(255, 255, 240)', 'khaki': 'rgb(240, 230, 140)', 'lavender': 'rgb(230, 230, 250)', 'lavenderblush': 'rgb(255, 240, 245)', 'lawngreen': 'rgb(124, 252, 0)', 'lemonchiffon': 'rgb(255, 250, 205)', 'lightblue': 'rgb(173, 216, 230)', 'lightcoral': 'rgb(240, 128, 128)', 'lightcyan': 'rgb(224, 255, 255)', 'lightgoldenrodyellow': 'rgb(250, 250, 210)', 'lightgray': 'rgb(211, 211, 211)', 'lightgreen': 'rgb(144, 238, 144)', 'lightgrey': 'rgb(211, 211, 211)', 'lightpink': 'rgb(255, 182, 193)', 'lightsalmon': 'rgb(255, 160, 122)', 'lightseagreen': 'rgb( 32, 178, 170)', 'lightskyblue': 'rgb(135, 206, 250)', 'lightslategray': 'rgb(119, 136, 153)', 'lightslategrey': 'rgb(119, 136, 153)', 'lightsteelblue': 'rgb(176, 196, 222)', 'lightyellow': 'rgb(255, 255, 224)', 'lime': 'rgb( 0, 255, 0)', 'limegreen': 'rgb( 50, 205, 50)', 'linen': 'rgb(250, 240, 230)', 'magenta': 'rgb(255, 0, 255)', 'maroon': 'rgb(128, 0, 0)', 'mediumaquamarine': 'rgb(102, 205, 170)', 'mediumblue': 'rgb( 0, 0, 205)', 'mediumorchid': 'rgb(186, 85, 211)', 'mediumpurple': 'rgb(147, 112, 219)', 'mediumseagreen': 'rgb( 60, 179, 113)', 'mediumslateblue': 'rgb(123, 104, 238)', 'mediumspringgreen': 'rgb( 0, 250, 154)', 'mediumturquoise': 'rgb( 72, 209, 204)', 'mediumvioletred': 'rgb(199, 21, 133)', 'midnightblue': 'rgb( 25, 25, 112)', 'mintcream': 'rgb(245, 255, 250)', 'mistyrose': 'rgb(255, 228, 225)', 'moccasin': 'rgb(255, 228, 181)', 'navajowhite': 'rgb(255, 222, 173)', 'navy': 'rgb( 0, 0, 128)', 'oldlace': 'rgb(253, 245, 230)', 'olive': 'rgb(128, 128, 0)', 'olivedrab': 'rgb(107, 142, 35)', 'orange': 'rgb(255, 165, 0)', 'orangered': 'rgb(255, 69, 0)', 'orchid': 'rgb(218, 112, 214)', 'palegoldenrod': 'rgb(238, 232, 170)', 'palegreen': 'rgb(152, 251, 152)', 'paleturquoise': 'rgb(175, 238, 238)', 'palevioletred': 'rgb(219, 112, 147)', 'papayawhip': 'rgb(255, 239, 213)', 'peachpuff': 'rgb(255, 218, 185)', 'peru': 'rgb(205, 133, 63)', 'pink': 'rgb(255, 192, 203)', 'plum': 'rgb(221, 160, 221)', 'powderblue': 'rgb(176, 224, 230)', 'purple': 'rgb(128, 0, 128)', 'red': 'rgb(255, 0, 0)', 'rosybrown': 'rgb(188, 143, 143)', 'royalblue': 'rgb( 65, 105, 225)', 'saddlebrown': 'rgb(139, 69, 19)', 'salmon': 'rgb(250, 128, 114)', 'sandybrown': 'rgb(244, 164, 96)', 'seagreen': 'rgb( 46, 139, 87)', 'seashell': 'rgb(255, 245, 238)', 'sienna': 'rgb(160, 82, 45)', 'silver': 'rgb(192, 192, 192)', 'skyblue': 'rgb(135, 206, 235)', 'slateblue': 'rgb(106, 90, 205)', 'slategray': 'rgb(112, 128, 144)', 'slategrey': 'rgb(112, 128, 144)', 'snow': 'rgb(255, 250, 250)', 'springgreen': 'rgb( 0, 255, 127)', 'steelblue': 'rgb( 70, 130, 180)', 'tan': 'rgb(210, 180, 140)', 'teal': 'rgb( 0, 128, 128)', 'thistle': 'rgb(216, 191, 216)', 'tomato': 'rgb(255, 99, 71)', 'turquoise': 'rgb( 64, 224, 208)', 'violet': 'rgb(238, 130, 238)', 'wheat': 'rgb(245, 222, 179)', 'white': 'rgb(255, 255, 255)', 'whitesmoke': 'rgb(245, 245, 245)', 'yellow': 'rgb(255, 255, 0)', 'yellowgreen': 'rgb(154, 205, 50)', } default_attributes = { # excluded all attributes with 'auto' as default # SVG 1.1 presentation attributes 'baseline-shift': 'baseline', 'clip-path': 'none', 'clip-rule': 'nonzero', 'color': '#000', 'color-interpolation-filters': 'linearRGB', 'color-interpolation': 'sRGB', 'direction': 'ltr', 'display': 'inline', 'enable-background': 'accumulate', 'fill': '#000', 'fill-opacity': '1', 'fill-rule': 'nonzero', 'filter': 'none', 'flood-color': '#000', 'flood-opacity': '1', 'font-size-adjust': 'none', 'font-size': 'medium', 'font-stretch': 'normal', 'font-style': 'normal', 'font-variant': 'normal', 'font-weight': 'normal', 'glyph-orientation-horizontal': '0deg', 'letter-spacing': 'normal', 'lighting-color': '#fff', 'marker': 'none', 'marker-start': 'none', 'marker-mid': 'none', 'marker-end': 'none', 'mask': 'none', 'opacity': '1', 'pointer-events': 'visiblePainted', 'stop-color': '#000', 'stop-opacity': '1', 'stroke': 'none', 'stroke-dasharray': 'none', 'stroke-dashoffset': '0', 'stroke-linecap': 'butt', 'stroke-linejoin': 'miter', 'stroke-miterlimit': '4', 'stroke-opacity': '1', 'stroke-width': '1', 'text-anchor': 'start', 'text-decoration': 'none', 'unicode-bidi': 'normal', 'visibility': 'visible', 'word-spacing': 'normal', 'writing-mode': 'lr-tb', # SVG 1.2 tiny properties 'audio-level': '1', 'solid-color': '#000', 'solid-opacity': '1', 'text-align': 'start', 'vector-effect': 'none', 'viewport-fill': 'none', 'viewport-fill-opacity': '1', } def isSameSign(a,b): return (a <= 0 and b <= 0) or (a >= 0 and b >= 0) scinumber = re.compile(r"[-+]?(\d*\.?)?\d+[eE][-+]?\d+") number = re.compile(r"[-+]?(\d*\.?)?\d+") sciExponent = re.compile(r"[eE]([-+]?\d+)") unit = re.compile("(em|ex|px|pt|pc|cm|mm|in|%){1,1}$") class Unit(object): # Integer constants for units. INVALID = -1 NONE = 0 PCT = 1 PX = 2 PT = 3 PC = 4 EM = 5 EX = 6 CM = 7 MM = 8 IN = 9 # String to Unit. Basically, converts unit strings to their integer constants. s2u = { '': NONE, '%': PCT, 'px': PX, 'pt': PT, 'pc': PC, 'em': EM, 'ex': EX, 'cm': CM, 'mm': MM, 'in': IN, } # Unit to String. Basically, converts unit integer constants to their corresponding strings. u2s = { NONE: '', PCT: '%', PX: 'px', PT: 'pt', PC: 'pc', EM: 'em', EX: 'ex', CM: 'cm', MM: 'mm', IN: 'in', } # @staticmethod def get(unitstr): if unitstr is None: return Unit.NONE try: return Unit.s2u[unitstr] except KeyError: return Unit.INVALID # @staticmethod def str(unitint): try: return Unit.u2s[unitint] except KeyError: return 'INVALID' get = staticmethod(get) str = staticmethod(str) class SVGLength(object): def __init__(self, str): try: # simple unitless and no scientific notation self.value = float(str) if int(self.value) == self.value: self.value = int(self.value) self.units = Unit.NONE except ValueError: # we know that the length string has an exponent, a unit, both or is invalid # parse out number, exponent and unit self.value = 0 unitBegin = 0 scinum = scinumber.match(str) if scinum != None: # this will always match, no need to check it numMatch = number.match(str) expMatch = sciExponent.search(str, numMatch.start(0)) self.value = (float(numMatch.group(0)) * 10 ** float(expMatch.group(1))) unitBegin = expMatch.end(1) else: # unit or invalid numMatch = number.match(str) if numMatch != None: self.value = float(numMatch.group(0)) unitBegin = numMatch.end(0) if int(self.value) == self.value: self.value = int(self.value) if unitBegin != 0 : unitMatch = unit.search(str, unitBegin) if unitMatch != None : self.units = Unit.get(unitMatch.group(0)) # invalid else: # TODO: this needs to set the default for the given attribute (how?) self.value = 0 self.units = Unit.INVALID def findElementsWithId(node, elems=None): """ Returns all elements with id attributes """ if elems is None: elems = {} id = node.getAttribute('id') if id != '' : elems[id] = node if node.hasChildNodes() : for child in node.childNodes: # from http://www.w3.org/TR/DOM-Level-2-Core/idl-definitions.html # we are only really interested in nodes of type Element (1) if child.nodeType == 1 : findElementsWithId(child, elems) return elems referencingProps = ['fill', 'stroke', 'filter', 'clip-path', 'mask', 'marker-start', 'marker-end', 'marker-mid'] def findReferencedElements(node, ids=None): """ Returns the number of times an ID is referenced as well as all elements that reference it. node is the node at which to start the search. The return value is a map which has the id as key and each value is an array where the first value is a count and the second value is a list of nodes that referenced it. Currently looks at fill, stroke, clip-path, mask, marker, and xlink:href attributes. """ global referencingProps if ids is None: ids = {} # TODO: input argument ids is clunky here (see below how it is called) # GZ: alternative to passing dict, use **kwargs # if this node is a style element, parse its text into CSS if node.nodeName == 'style' and node.namespaceURI == NS['SVG']: # one stretch of text, please! (we could use node.normalize(), but # this actually modifies the node, and we don't want to keep # whitespace around if there's any) stylesheet = "".join([child.nodeValue for child in node.childNodes]) if stylesheet != '': cssRules = parseCssString(stylesheet) for rule in cssRules: for propname in rule['properties']: propval = rule['properties'][propname] findReferencingProperty(node, propname, propval, ids) return ids # else if xlink:href is set, then grab the id href = node.getAttributeNS(NS['XLINK'],'href') if href != '' and len(href) > 1 and href[0] == '#': # we remove the hash mark from the beginning of the id id = href[1:] if id in ids: ids[id][0] += 1 ids[id][1].append(node) else: ids[id] = [1,[node]] # now get all style properties and the fill, stroke, filter attributes styles = node.getAttribute('style').split(';') for attr in referencingProps: styles.append(':'.join([attr, node.getAttribute(attr)])) for style in styles: propval = style.split(':') if len(propval) == 2 : prop = propval[0].strip() val = propval[1].strip() findReferencingProperty(node, prop, val, ids) if node.hasChildNodes() : for child in node.childNodes: if child.nodeType == 1 : findReferencedElements(child, ids) return ids def findReferencingProperty(node, prop, val, ids): global referencingProps if prop in referencingProps and val != '' : if len(val) >= 7 and val[0:5] == 'url(#' : id = val[5:val.find(')')] if ids.has_key(id) : ids[id][0] += 1 ids[id][1].append(node) else: ids[id] = [1,[node]] # if the url has a quote in it, we need to compensate elif len(val) >= 8 : id = None # double-quote if val[0:6] == 'url("#' : id = val[6:val.find('")')] # single-quote elif val[0:6] == "url('#" : id = val[6:val.find("')")] if id != None: if ids.has_key(id) : ids[id][0] += 1 ids[id][1].append(node) else: ids[id] = [1,[node]] numIDsRemoved = 0 numElemsRemoved = 0 numAttrsRemoved = 0 numRastersEmbedded = 0 numPathSegmentsReduced = 0 numCurvesStraightened = 0 numBytesSavedInPathData = 0 numBytesSavedInColors = 0 numBytesSavedInIDs = 0 numBytesSavedInLengths = 0 numBytesSavedInTransforms = 0 numPointsRemovedFromPolygon = 0 numCommentBytes = 0 def flattenDefs(doc): """ Puts all defined elements into a newly created defs in the document. This function handles recursive defs elements. """ defs = doc.documentElement.getElementsByTagName('defs') if defs.length > 1: topDef = doc.createElementNS(NS['SVG'], 'defs') for defElem in defs: # Remove all children of this defs and put it into the topDef. while defElem.hasChildNodes(): topDef.appendChild(defElem.firstChild) defElem.parentNode.removeChild(defElem) if topDef.hasChildNodes(): doc.documentElement.insertBefore(topDef, doc.documentElement.firstChild) def removeUnusedDefs(doc, defElem, elemsToRemove=None): if elemsToRemove is None: elemsToRemove = [] identifiedElements = findElementsWithId(doc.documentElement) referencedIDs = findReferencedElements(doc.documentElement) keepTags = ['font', 'style', 'metadata', 'script', 'title', 'desc'] for elem in defElem.childNodes: # only look at it if an element and not referenced anywhere else if elem.nodeType == 1 and (elem.getAttribute('id') == '' or \ (not elem.getAttribute('id') in referencedIDs)): # we only inspect the children of a group in a defs if the group # is not referenced anywhere else if elem.nodeName == 'g' and elem.namespaceURI == NS['SVG']: elemsToRemove = removeUnusedDefs(doc, elem, elemsToRemove) # we only remove if it is not one of our tags we always keep (see above) elif not elem.nodeName in keepTags: elemsToRemove.append(elem) return elemsToRemove def removeUnreferencedElements(doc): """ Removes all unreferenced elements except for <svg>, <font>, <metadata>, <title>, and <desc>. Also vacuums the defs of any non-referenced renderable elements. Returns the number of unreferenced elements removed from the document. """ global numElemsRemoved num = 0 # Remove certain unreferenced elements outside of defs removeTags = ['linearGradient', 'radialGradient', 'pattern'] identifiedElements = findElementsWithId(doc.documentElement) referencedIDs = findReferencedElements(doc.documentElement) for id in identifiedElements: if not id in referencedIDs: goner = identifiedElements[id] if goner != None and goner.parentNode != None and goner.nodeName in removeTags: goner.parentNode.removeChild(goner) num += 1 numElemsRemoved += 1 # Remove most unreferenced elements inside defs defs = doc.documentElement.getElementsByTagName('defs') for aDef in defs: elemsToRemove = removeUnusedDefs(doc, aDef) for elem in elemsToRemove: elem.parentNode.removeChild(elem) numElemsRemoved += 1 num += 1 return num def shortenIDs(doc, unprotectedElements=None): """ Shortens ID names used in the document. ID names referenced the most often are assigned the shortest ID names. If the list unprotectedElements is provided, only IDs from this list will be shortened. Returns the number of bytes saved by shortening ID names in the document. """ num = 0 identifiedElements = findElementsWithId(doc.documentElement) if unprotectedElements is None: unprotectedElements = identifiedElements referencedIDs = findReferencedElements(doc.documentElement) # Make idList (list of idnames) sorted by reference count # descending, so the highest reference count is first. # First check that there's actually a defining element for the current ID name. # (Cyn: I've seen documents with #id references but no element with that ID!) idList = [(referencedIDs[rid][0], rid) for rid in referencedIDs if rid in unprotectedElements] idList.sort(reverse=True) idList = [rid for count, rid in idList] curIdNum = 1 for rid in idList: curId = intToID(curIdNum) # First make sure that *this* element isn't already using # the ID name we want to give it. if curId != rid: # Then, skip ahead if the new ID is already in identifiedElement. while curId in identifiedElements: curIdNum += 1 curId = intToID(curIdNum) # Then go rename it. num += renameID(doc, rid, curId, identifiedElements, referencedIDs) curIdNum += 1 return num def intToID(idnum): """ Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z, then from aa to az, ba to bz, etc., until zz. """ rid = '' while idnum > 0: idnum -= 1 rid = chr((idnum % 26) + ord('a')) + rid idnum = int(idnum / 26) return rid def renameID(doc, idFrom, idTo, identifiedElements, referencedIDs): """ Changes the ID name from idFrom to idTo, on the declaring element as well as all references in the document doc. Updates identifiedElements and referencedIDs. Does not handle the case where idTo is already the ID name of another element in doc. Returns the number of bytes saved by this replacement. """ num = 0 definingNode = identifiedElements[idFrom] definingNode.setAttribute("id", idTo) del identifiedElements[idFrom] identifiedElements[idTo] = definingNode referringNodes = referencedIDs[idFrom] # Look for the idFrom ID name in each of the referencing elements, # exactly like findReferencedElements would. # Cyn: Duplicated processing! for node in referringNodes[1]: # if this node is a style element, parse its text into CSS if node.nodeName == 'style' and node.namespaceURI == NS['SVG']: # node.firstChild will be either a CDATA or a Text node now if node.firstChild != None: # concatenate the value of all children, in case # there's a CDATASection node surrounded by whitespace # nodes # (node.normalize() will NOT work here, it only acts on Text nodes) oldValue = "".join([child.nodeValue for child in node.childNodes]) # not going to reparse the whole thing newValue = oldValue.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')') newValue = newValue.replace("url(#'" + idFrom + "')", 'url(#' + idTo + ')') newValue = newValue.replace('url(#"' + idFrom + '")', 'url(#' + idTo + ')') # and now replace all the children with this new stylesheet. # again, this is in case the stylesheet was a CDATASection node.childNodes[:] = [node.ownerDocument.createTextNode(newValue)] num += len(oldValue) - len(newValue) # if xlink:href is set to #idFrom, then change the id href = node.getAttributeNS(NS['XLINK'],'href') if href == '#' + idFrom: node.setAttributeNS(NS['XLINK'],'href', '#' + idTo) num += len(idFrom) - len(idTo) # if the style has url(#idFrom), then change the id styles = node.getAttribute('style') if styles != '': newValue = styles.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')') newValue = newValue.replace("url('#" + idFrom + "')", 'url(#' + idTo + ')') newValue = newValue.replace('url("#' + idFrom + '")', 'url(#' + idTo + ')') node.setAttribute('style', newValue) num += len(styles) - len(newValue) # now try the fill, stroke, filter attributes for attr in referencingProps: oldValue = node.getAttribute(attr) if oldValue != '': newValue = oldValue.replace('url(#' + idFrom + ')', 'url(#' + idTo + ')') newValue = newValue.replace("url('#" + idFrom + "')", 'url(#' + idTo + ')') newValue = newValue.replace('url("#' + idFrom + '")', 'url(#' + idTo + ')') node.setAttribute(attr, newValue) num += len(oldValue) - len(newValue) del referencedIDs[idFrom] referencedIDs[idTo] = referringNodes return num def unprotected_ids(doc, options): u"""Returns a list of unprotected IDs within the document doc.""" identifiedElements = findElementsWithId(doc.documentElement) if not (options.protect_ids_noninkscape or options.protect_ids_list or options.protect_ids_prefix): return identifiedElements if options.protect_ids_list: protect_ids_list = options.protect_ids_list.split(",") if options.protect_ids_prefix: protect_ids_prefixes = options.protect_ids_prefix.split(",") for id in identifiedElements.keys(): protected = False if options.protect_ids_noninkscape and not id[-1].isdigit(): protected = True if options.protect_ids_list and id in protect_ids_list: protected = True if options.protect_ids_prefix: for prefix in protect_ids_prefixes: if id.startswith(prefix): protected = True if protected: del identifiedElements[id] return identifiedElements def removeUnreferencedIDs(referencedIDs, identifiedElements): """ Removes the unreferenced ID attributes. Returns the number of ID attributes removed """ global numIDsRemoved keepTags = ['font'] num = 0; for id in identifiedElements.keys(): node = identifiedElements[id] if referencedIDs.has_key(id) == False and not node.nodeName in keepTags: node.removeAttribute('id') numIDsRemoved += 1 num += 1 return num def removeNamespacedAttributes(node, namespaces): global numAttrsRemoved num = 0 if node.nodeType == 1 : # remove all namespace'd attributes from this element attrList = node.attributes attrsToRemove = [] for attrNum in xrange(attrList.length): attr = attrList.item(attrNum) if attr != None and attr.namespaceURI in namespaces: attrsToRemove.append(attr.nodeName) for attrName in attrsToRemove : num += 1 numAttrsRemoved += 1 node.removeAttribute(attrName) # now recurse for children for child in node.childNodes: num += removeNamespacedAttributes(child, namespaces) return num def removeNamespacedElements(node, namespaces): global numElemsRemoved num = 0 if node.nodeType == 1 : # remove all namespace'd child nodes from this element childList = node.childNodes childrenToRemove = [] for child in childList: if child != None and child.namespaceURI in namespaces: childrenToRemove.append(child) for child in childrenToRemove : num += 1 numElemsRemoved += 1 node.removeChild(child) # now recurse for children for child in node.childNodes: num += removeNamespacedElements(child, namespaces) return num def removeMetadataElements(doc): global numElemsRemoved num = 0 # clone the list, as the tag list is live from the DOM elementsToRemove = [element for element in doc.documentElement.getElementsByTagName('metadata')] for element in elementsToRemove: element.parentNode.removeChild(element) num += 1 numElemsRemoved += 1 return num def removeNestedGroups(node): """ This walks further and further down the tree, removing groups which do not have any attributes or a title/desc child and promoting their children up one level """ global numElemsRemoved num = 0 groupsToRemove = [] # Only consider <g> elements for promotion if this element isn't a <switch>. # (partial fix for bug 594930, required by the SVG spec however) if not (node.nodeType == 1 and node.nodeName == 'switch'): for child in node.childNodes: if child.nodeName == 'g' and child.namespaceURI == NS['SVG'] and len(child.attributes) == 0: # only collapse group if it does not have a title or desc as a direct descendant, for grandchild in child.childNodes: if grandchild.nodeType == 1 and grandchild.namespaceURI == NS['SVG'] and \ grandchild.nodeName in ['title','desc']: break else: groupsToRemove.append(child) for g in groupsToRemove: while g.childNodes.length > 0: g.parentNode.insertBefore(g.firstChild, g) g.parentNode.removeChild(g) numElemsRemoved += 1 num += 1 # now recurse for children for child in node.childNodes: if child.nodeType == 1: num += removeNestedGroups(child) return num def moveCommonAttributesToParentGroup(elem, referencedElements): """ This recursively calls this function on all children of the passed in element and then iterates over all child elements and removes common inheritable attributes from the children and places them in the parent group. But only if the parent contains nothing but element children and whitespace. The attributes are only removed from the children if the children are not referenced by other elements in the document. """ num = 0 childElements = [] # recurse first into the children (depth-first) for child in elem.childNodes: if child.nodeType == 1: # only add and recurse if the child is not referenced elsewhere if not child.getAttribute('id') in referencedElements: childElements.append(child) num += moveCommonAttributesToParentGroup(child, referencedElements) # else if the parent has non-whitespace text children, do not # try to move common attributes elif child.nodeType == 3 and child.nodeValue.strip(): return num # only process the children if there are more than one element if len(childElements) <= 1: return num commonAttrs = {} # add all inheritable properties of the first child element # FIXME: Note there is a chance that the first child is a set/animate in which case # its fill attribute is not what we want to look at, we should look for the first # non-animate/set element attrList = childElements[0].attributes for num in xrange(attrList.length): attr = attrList.item(num) # this is most of the inheritable properties from http://www.w3.org/TR/SVG11/propidx.html # and http://www.w3.org/TR/SVGTiny12/attributeTable.html if attr.nodeName in ['clip-rule', 'display-align', 'fill', 'fill-opacity', 'fill-rule', 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'letter-spacing', 'pointer-events', 'shape-rendering', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'visibility', 'word-spacing', 'writing-mode']: # we just add all the attributes from the first child commonAttrs[attr.nodeName] = attr.nodeValue # for each subsequent child element for childNum in xrange(len(childElements)): # skip first child if childNum == 0: continue child = childElements[childNum] # if we are on an animateXXX/set element, ignore it (due to the 'fill' attribute) if child.localName in ['set', 'animate', 'animateColor', 'animateTransform', 'animateMotion']: continue distinctAttrs = [] # loop through all current 'common' attributes for name in commonAttrs.keys(): # if this child doesn't match that attribute, schedule it for removal if child.getAttribute(name) != commonAttrs[name]: distinctAttrs.append(name) # remove those attributes which are not common for name in distinctAttrs: del commonAttrs[name] # commonAttrs now has all the inheritable attributes which are common among all child elements for name in commonAttrs.keys(): for child in childElements: child.removeAttribute(name) elem.setAttribute(name, commonAttrs[name]) # update our statistic (we remove N*M attributes and add back in M attributes) num += (len(childElements)-1) * len(commonAttrs) return num def createGroupsForCommonAttributes(elem): """ Creates <g> elements to contain runs of 3 or more consecutive child elements having at least one common attribute. Common attributes are not promoted to the <g> by this function. This is handled by moveCommonAttributesToParentGroup. If all children have a common attribute, an extra <g> is not created. This function acts recursively on the given element. """ num = 0 global numElemsRemoved # TODO perhaps all of the Presentation attributes in http://www.w3.org/TR/SVG/struct.html#GElement # could be added here # Cyn: These attributes are the same as in moveAttributesToParentGroup, and must always be for curAttr in ['clip-rule', 'display-align', 'fill', 'fill-opacity', 'fill-rule', 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'letter-spacing', 'pointer-events', 'shape-rendering', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'visibility', 'word-spacing', 'writing-mode']: # Iterate through the children in reverse order, so item(i) for # items we have yet to visit still returns the correct nodes. curChild = elem.childNodes.length - 1 while curChild >= 0: childNode = elem.childNodes.item(curChild) if childNode.nodeType == 1 and childNode.getAttribute(curAttr) != '': # We're in a possible run! Track the value and run length. value = childNode.getAttribute(curAttr) runStart, runEnd = curChild, curChild # Run elements includes only element tags, no whitespace/comments/etc. # Later, we calculate a run length which includes these. runElements = 1 # Backtrack to get all the nodes having the same # attribute value, preserving any nodes in-between. while runStart > 0: nextNode = elem.childNodes.item(runStart - 1) if nextNode.nodeType == 1: if nextNode.getAttribute(curAttr) != value: break else: runElements += 1 runStart -= 1 else: runStart -= 1 if runElements >= 3: # Include whitespace/comment/etc. nodes in the run. while runEnd < elem.childNodes.length - 1: if elem.childNodes.item(runEnd + 1).nodeType == 1: break else: runEnd += 1 runLength = runEnd - runStart + 1 if runLength == elem.childNodes.length: # Every child has this # If the current parent is a <g> already, if elem.nodeName == 'g' and elem.namespaceURI == NS['SVG']: # do not act altogether on this attribute; all the # children have it in common. # Let moveCommonAttributesToParentGroup do it. curChild = -1 continue # otherwise, it might be an <svg> element, and # even if all children have the same attribute value, # it's going to be worth making the <g> since # <svg> doesn't support attributes like 'stroke'. # Fall through. # Create a <g> element from scratch. # We need the Document for this. document = elem.ownerDocument group = document.createElementNS(NS['SVG'], 'g') # Move the run of elements to the group. # a) ADD the nodes to the new group. group.childNodes[:] = elem.childNodes[runStart:runEnd + 1] for child in group.childNodes: child.parentNode = group # b) REMOVE the nodes from the element. elem.childNodes[runStart:runEnd + 1] = [] # Include the group in elem's children. elem.childNodes.insert(runStart, group) group.parentNode = elem num += 1 curChild = runStart - 1 numElemsRemoved -= 1 else: curChild -= 1 else: curChild -= 1 # each child gets the same treatment, recursively for childNode in elem.childNodes: if childNode.nodeType == 1: num += createGroupsForCommonAttributes(childNode) return num def removeUnusedAttributesOnParent(elem): """ This recursively calls this function on all children of the element passed in, then removes any unused attributes on this elem if none of the children inherit it """ num = 0 childElements = [] # recurse first into the children (depth-first) for child in elem.childNodes: if child.nodeType == 1: childElements.append(child) num += removeUnusedAttributesOnParent(child) # only process the children if there are more than one element if len(childElements) <= 1: return num # get all attribute values on this parent attrList = elem.attributes unusedAttrs = {} for num in xrange(attrList.length): attr = attrList.item(num) if attr.nodeName in ['clip-rule', 'display-align', 'fill', 'fill-opacity', 'fill-rule', 'font', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'letter-spacing', 'pointer-events', 'shape-rendering', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'visibility', 'word-spacing', 'writing-mode']: unusedAttrs[attr.nodeName] = attr.nodeValue # for each child, if at least one child inherits the parent's attribute, then remove for childNum in xrange(len(childElements)): child = childElements[childNum] inheritedAttrs = [] for name in unusedAttrs.keys(): val = child.getAttribute(name) if val == '' or val == None or val == 'inherit': inheritedAttrs.append(name) for a in inheritedAttrs: del unusedAttrs[a] # unusedAttrs now has all the parent attributes that are unused for name in unusedAttrs.keys(): elem.removeAttribute(name) num += 1 return num def removeDuplicateGradientStops(doc): global numElemsRemoved num = 0 for gradType in ['linearGradient', 'radialGradient']: for grad in doc.getElementsByTagName(gradType): stops = {} stopsToRemove = [] for stop in grad.getElementsByTagName('stop'): # convert percentages into a floating point number offsetU = SVGLength(stop.getAttribute('offset')) if offsetU.units == Unit.PCT: offset = offsetU.value / 100.0 elif offsetU.units == Unit.NONE: offset = offsetU.value else: offset = 0 # set the stop offset value to the integer or floating point equivalent if int(offset) == offset: stop.setAttribute('offset', str(int(offset))) else: stop.setAttribute('offset', str(offset)) color = stop.getAttribute('stop-color') opacity = stop.getAttribute('stop-opacity') style = stop.getAttribute('style') if stops.has_key(offset) : oldStop = stops[offset] if oldStop[0] == color and oldStop[1] == opacity and oldStop[2] == style: stopsToRemove.append(stop) stops[offset] = [color, opacity, style] for stop in stopsToRemove: stop.parentNode.removeChild(stop) num += 1 numElemsRemoved += 1 # linear gradients return num def collapseSinglyReferencedGradients(doc): global numElemsRemoved num = 0 identifiedElements = findElementsWithId(doc.documentElement) # make sure to reset the ref'ed ids for when we are running this in testscour for rid,nodeCount in findReferencedElements(doc.documentElement).iteritems(): count = nodeCount[0] nodes = nodeCount[1] # Make sure that there's actually a defining element for the current ID name. # (Cyn: I've seen documents with #id references but no element with that ID!) if count == 1 and rid in identifiedElements: elem = identifiedElements[rid] if elem != None and elem.nodeType == 1 and elem.nodeName in ['linearGradient', 'radialGradient'] \ and elem.namespaceURI == NS['SVG']: # found a gradient that is referenced by only 1 other element refElem = nodes[0] if refElem.nodeType == 1 and refElem.nodeName in ['linearGradient', 'radialGradient'] \ and refElem.namespaceURI == NS['SVG']: # elem is a gradient referenced by only one other gradient (refElem) # add the stops to the referencing gradient (this removes them from elem) if len(refElem.getElementsByTagName('stop')) == 0: stopsToAdd = elem.getElementsByTagName('stop') for stop in stopsToAdd: refElem.appendChild(stop) # adopt the gradientUnits, spreadMethod, gradientTransform attributes if # they are unspecified on refElem for attr in ['gradientUnits','spreadMethod','gradientTransform']: if refElem.getAttribute(attr) == '' and not elem.getAttribute(attr) == '': refElem.setAttributeNS(None, attr, elem.getAttribute(attr)) # if both are radialGradients, adopt elem's fx,fy,cx,cy,r attributes if # they are unspecified on refElem if elem.nodeName == 'radialGradient' and refElem.nodeName == 'radialGradient': for attr in ['fx','fy','cx','cy','r']: if refElem.getAttribute(attr) == '' and not elem.getAttribute(attr) == '': refElem.setAttributeNS(None, attr, elem.getAttribute(attr)) # if both are linearGradients, adopt elem's x1,y1,x2,y2 attributes if # they are unspecified on refElem if elem.nodeName == 'linearGradient' and refElem.nodeName == 'linearGradient': for attr in ['x1','y1','x2','y2']: if refElem.getAttribute(attr) == '' and not elem.getAttribute(attr) == '': refElem.setAttributeNS(None, attr, elem.getAttribute(attr)) # now remove the xlink:href from refElem refElem.removeAttributeNS(NS['XLINK'], 'href') # now delete elem elem.parentNode.removeChild(elem) numElemsRemoved += 1 num += 1 return num def removeDuplicateGradients(doc): global numElemsRemoved num = 0 gradientsToRemove = {} duplicateToMaster = {} for gradType in ['linearGradient', 'radialGradient']: grads = doc.getElementsByTagName(gradType) for grad in grads: # TODO: should slice grads from 'grad' here to optimize for ograd in grads: # do not compare gradient to itself if grad == ograd: continue # compare grad to ograd (all properties, then all stops) # if attributes do not match, go to next gradient someGradAttrsDoNotMatch = False for attr in ['gradientUnits','spreadMethod','gradientTransform','x1','y1','x2','y2','cx','cy','fx','fy','r']: if grad.getAttribute(attr) != ograd.getAttribute(attr): someGradAttrsDoNotMatch = True break; if someGradAttrsDoNotMatch: continue # compare xlink:href values too if grad.getAttributeNS(NS['XLINK'], 'href') != ograd.getAttributeNS(NS['XLINK'], 'href'): continue # all gradient properties match, now time to compare stops stops = grad.getElementsByTagName('stop') ostops = ograd.getElementsByTagName('stop') if stops.length != ostops.length: continue # now compare stops stopsNotEqual = False for i in xrange(stops.length): if stopsNotEqual: break stop = stops.item(i) ostop = ostops.item(i) for attr in ['offset', 'stop-color', 'stop-opacity', 'style']: if stop.getAttribute(attr) != ostop.getAttribute(attr): stopsNotEqual = True break if stopsNotEqual: continue # ograd is a duplicate of grad, we schedule it to be removed UNLESS # ograd is ALREADY considered a 'master' element if not gradientsToRemove.has_key(ograd): if not duplicateToMaster.has_key(ograd): if not gradientsToRemove.has_key(grad): gradientsToRemove[grad] = [] gradientsToRemove[grad].append( ograd ) duplicateToMaster[ograd] = grad # get a collection of all elements that are referenced and their referencing elements referencedIDs = findReferencedElements(doc.documentElement) for masterGrad in gradientsToRemove.keys(): master_id = masterGrad.getAttribute('id') # print 'master='+master_id for dupGrad in gradientsToRemove[masterGrad]: # if the duplicate gradient no longer has a parent that means it was # already re-mapped to another master gradient if not dupGrad.parentNode: continue dup_id = dupGrad.getAttribute('id') # print 'dup='+dup_id # print referencedIDs[dup_id] # for each element that referenced the gradient we are going to remove for elem in referencedIDs[dup_id][1]: # find out which attribute referenced the duplicate gradient for attr in ['fill', 'stroke']: v = elem.getAttribute(attr) if v == 'url(#'+dup_id+')' or v == 'url("#'+dup_id+'")' or v == "url('#"+dup_id+"')": elem.setAttribute(attr, 'url(#'+master_id+')') if elem.getAttributeNS(NS['XLINK'], 'href') == '#'+dup_id: elem.setAttributeNS(NS['XLINK'], 'href', '#'+master_id) styles = _getStyle(elem) for style in styles: v = styles[style] if v == 'url(#'+dup_id+')' or v == 'url("#'+dup_id+'")' or v == "url('#"+dup_id+"')": styles[style] = 'url(#'+master_id+')' _setStyle(elem, styles) # now that all referencing elements have been re-mapped to the master # it is safe to remove this gradient from the document dupGrad.parentNode.removeChild(dupGrad) numElemsRemoved += 1 num += 1 return num def _getStyle(node): u"""Returns the style attribute of a node as a dictionary.""" if node.nodeType == 1 and len(node.getAttribute('style')) > 0 : styleMap = { } rawStyles = node.getAttribute('style').split(';') for style in rawStyles: propval = style.split(':') if len(propval) == 2 : styleMap[propval[0].strip()] = propval[1].strip() return styleMap else: return {} def _setStyle(node, styleMap): u"""Sets the style attribute of a node to the dictionary ``styleMap``.""" fixedStyle = ';'.join([prop + ':' + styleMap[prop] for prop in styleMap.keys()]) if fixedStyle != '' : node.setAttribute('style', fixedStyle) elif node.getAttribute('style'): node.removeAttribute('style') return node def repairStyle(node, options): num = 0 styleMap = _getStyle(node) if styleMap: # I've seen this enough to know that I need to correct it: # fill: url(#linearGradient4918) rgb(0, 0, 0); for prop in ['fill', 'stroke'] : if styleMap.has_key(prop) : chunk = styleMap[prop].split(') ') if len(chunk) == 2 and (chunk[0][:5] == 'url(#' or chunk[0][:6] == 'url("#' or chunk[0][:6] == "url('#") and chunk[1] == 'rgb(0, 0, 0)' : styleMap[prop] = chunk[0] + ')' num += 1 # Here is where we can weed out unnecessary styles like: # opacity:1 if styleMap.has_key('opacity') : opacity = float(styleMap['opacity']) # if opacity='0' then all fill and stroke properties are useless, remove them if opacity == 0.0 : for uselessStyle in ['fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-linejoin', 'stroke-opacity', 'stroke-miterlimit', 'stroke-linecap', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-opacity'] : if styleMap.has_key(uselessStyle): del styleMap[uselessStyle] num += 1 # if stroke:none, then remove all stroke-related properties (stroke-width, etc) # TODO: should also detect if the computed value of this element is stroke="none" if styleMap.has_key('stroke') and styleMap['stroke'] == 'none' : for strokestyle in [ 'stroke-width', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-linecap', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-opacity'] : if styleMap.has_key(strokestyle) : del styleMap[strokestyle] num += 1 # TODO: This is actually a problem if a parent element has a specified stroke # we need to properly calculate computed values del styleMap['stroke'] # if fill:none, then remove all fill-related properties (fill-rule, etc) if styleMap.has_key('fill') and styleMap['fill'] == 'none' : for fillstyle in [ 'fill-rule', 'fill-opacity' ] : if styleMap.has_key(fillstyle) : del styleMap[fillstyle] num += 1 # fill-opacity: 0 if styleMap.has_key('fill-opacity') : fillOpacity = float(styleMap['fill-opacity']) if fillOpacity == 0.0 : for uselessFillStyle in [ 'fill', 'fill-rule' ] : if styleMap.has_key(uselessFillStyle): del styleMap[uselessFillStyle] num += 1 # stroke-opacity: 0 if styleMap.has_key('stroke-opacity') : strokeOpacity = float(styleMap['stroke-opacity']) if strokeOpacity == 0.0 : for uselessStrokeStyle in [ 'stroke', 'stroke-width', 'stroke-linejoin', 'stroke-linecap', 'stroke-dasharray', 'stroke-dashoffset' ] : if styleMap.has_key(uselessStrokeStyle): del styleMap[uselessStrokeStyle] num += 1 # stroke-width: 0 if styleMap.has_key('stroke-width') : strokeWidth = SVGLength(styleMap['stroke-width']) if strokeWidth.value == 0.0 : for uselessStrokeStyle in [ 'stroke', 'stroke-linejoin', 'stroke-linecap', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-opacity' ] : if styleMap.has_key(uselessStrokeStyle): del styleMap[uselessStrokeStyle] num += 1 # remove font properties for non-text elements # I've actually observed this in real SVG content if not mayContainTextNodes(node): for fontstyle in [ 'font-family', 'font-size', 'font-stretch', 'font-size-adjust', 'font-style', 'font-variant', 'font-weight', 'letter-spacing', 'line-height', 'kerning', 'text-align', 'text-anchor', 'text-decoration', 'text-rendering', 'unicode-bidi', 'word-spacing', 'writing-mode'] : if styleMap.has_key(fontstyle) : del styleMap[fontstyle] num += 1 # remove inkscape-specific styles # TODO: need to get a full list of these for inkscapeStyle in ['-inkscape-font-specification']: if styleMap.has_key(inkscapeStyle): del styleMap[inkscapeStyle] num += 1 if styleMap.has_key('overflow') : # overflow specified on element other than svg, marker, pattern if not node.nodeName in ['svg','marker','pattern']: del styleMap['overflow'] num += 1 # it is a marker, pattern or svg # as long as this node is not the document <svg>, then only # remove overflow='hidden'. See # http://www.w3.org/TR/2010/WD-SVG11-20100622/masking.html#OverflowProperty elif node != node.ownerDocument.documentElement: if styleMap['overflow'] == 'hidden': del styleMap['overflow'] num += 1 # else if outer svg has a overflow="visible", we can remove it elif styleMap['overflow'] == 'visible': del styleMap['overflow'] num += 1 # now if any of the properties match known SVG attributes we prefer attributes # over style so emit them and remove them from the style map if options.style_to_xml: for propName in styleMap.keys() : if propName in svgAttributes : node.setAttribute(propName, styleMap[propName]) del styleMap[propName] _setStyle(node, styleMap) # recurse for our child elements for child in node.childNodes : num += repairStyle(child,options) return num def mayContainTextNodes(node): """ Returns True if the passed-in node is probably a text element, or at least one of its descendants is probably a text element. If False is returned, it is guaranteed that the passed-in node has no business having text-based attributes. If True is returned, the passed-in node should not have its text-based attributes removed. """ # Cached result of a prior call? try: return node.mayContainTextNodes except AttributeError: pass result = True # Default value # Comment, text and CDATA nodes don't have attributes and aren't containers if node.nodeType != 1: result = False # Non-SVG elements? Unknown elements! elif node.namespaceURI != NS['SVG']: result = True # Blacklisted elements. Those are guaranteed not to be text elements. elif node.nodeName in ['rect', 'circle', 'ellipse', 'line', 'polygon', 'polyline', 'path', 'image', 'stop']: result = False # Group elements. If we're missing any here, the default of True is used. elif node.nodeName in ['g', 'clipPath', 'marker', 'mask', 'pattern', 'linearGradient', 'radialGradient', 'symbol']: result = False for child in node.childNodes: if mayContainTextNodes(child): result = True # Everything else should be considered a future SVG-version text element # at best, or an unknown element at worst. result will stay True. # Cache this result before returning it. node.mayContainTextNodes = result return result def taint(taintedSet, taintedAttribute): u"""Adds an attribute to a set of attributes. Related attributes are also included.""" taintedSet.add(taintedAttribute) if taintedAttribute == 'marker': taintedSet |= set(['marker-start', 'marker-mid', 'marker-end']) if taintedAttribute in ['marker-start', 'marker-mid', 'marker-end']: taintedSet.add('marker') return taintedSet def removeDefaultAttributeValues(node, options, tainted=set()): u"""'tainted' keeps a set of attributes defined in parent nodes. For such attributes, we don't delete attributes with default values.""" num = 0 if node.nodeType != 1: return 0 # gradientUnits: objectBoundingBox if node.getAttribute('gradientUnits') == 'objectBoundingBox': node.removeAttribute('gradientUnits') num += 1 # spreadMethod: pad if node.getAttribute('spreadMethod') == 'pad': node.removeAttribute('spreadMethod') num += 1 # x1: 0% if node.getAttribute('x1') != '': x1 = SVGLength(node.getAttribute('x1')) if x1.value == 0: node.removeAttribute('x1') num += 1 # y1: 0% if node.getAttribute('y1') != '': y1 = SVGLength(node.getAttribute('y1')) if y1.value == 0: node.removeAttribute('y1') num += 1 # x2: 100% if node.getAttribute('x2') != '': x2 = SVGLength(node.getAttribute('x2')) if (x2.value == 100 and x2.units == Unit.PCT) or (x2.value == 1 and x2.units == Unit.NONE): node.removeAttribute('x2') num += 1 # y2: 0% if node.getAttribute('y2') != '': y2 = SVGLength(node.getAttribute('y2')) if y2.value == 0: node.removeAttribute('y2') num += 1 # fx: equal to rx if node.getAttribute('fx') != '': if node.getAttribute('fx') == node.getAttribute('cx'): node.removeAttribute('fx') num += 1 # fy: equal to ry if node.getAttribute('fy') != '': if node.getAttribute('fy') == node.getAttribute('cy'): node.removeAttribute('fy') num += 1 # cx: 50% if node.getAttribute('cx') != '': cx = SVGLength(node.getAttribute('cx')) if (cx.value == 50 and cx.units == Unit.PCT) or (cx.value == 0.5 and cx.units == Unit.NONE): node.removeAttribute('cx') num += 1 # cy: 50% if node.getAttribute('cy') != '': cy = SVGLength(node.getAttribute('cy')) if (cy.value == 50 and cy.units == Unit.PCT) or (cy.value == 0.5 and cy.units == Unit.NONE): node.removeAttribute('cy') num += 1 # r: 50% if node.getAttribute('r') != '': r = SVGLength(node.getAttribute('r')) if (r.value == 50 and r.units == Unit.PCT) or (r.value == 0.5 and r.units == Unit.NONE): node.removeAttribute('r') num += 1 # Summarily get rid of some more attributes attributes = [node.attributes.item(i).nodeName for i in range(node.attributes.length)] for attribute in attributes: if attribute not in tainted: if attribute in default_attributes.keys(): if node.getAttribute(attribute) == default_attributes[attribute]: node.removeAttribute(attribute) num += 1 else: tainted = taint(tainted, attribute) # These attributes might also occur as styles styles = _getStyle(node) for attribute in styles.keys(): if attribute not in tainted: if attribute in default_attributes.keys(): if styles[attribute] == default_attributes[attribute]: del styles[attribute] num += 1 else: tainted = taint(tainted, attribute) _setStyle(node, styles) # recurse for our child elements for child in node.childNodes : num += removeDefaultAttributeValues(child, options, tainted.copy()) return num rgb = re.compile(r"\s*rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*") rgbp = re.compile(r"\s*rgb\(\s*(\d*\.?\d+)%\s*,\s*(\d*\.?\d+)%\s*,\s*(\d*\.?\d+)%\s*\)\s*") def convertColor(value): """ Converts the input color string and returns a #RRGGBB (or #RGB if possible) string """ s = value if s in colors.keys(): s = colors[s] rgbpMatch = rgbp.match(s) if rgbpMatch != None : r = int(float(rgbpMatch.group(1)) * 255.0 / 100.0) g = int(float(rgbpMatch.group(2)) * 255.0 / 100.0) b = int(float(rgbpMatch.group(3)) * 255.0 / 100.0) s = '#%02x%02x%02x' % (r, g, b) else: rgbMatch = rgb.match(s) if rgbMatch != None : r = int( rgbMatch.group(1) ) g = int( rgbMatch.group(2) ) b = int( rgbMatch.group(3) ) s = '#%02x%02x%02x' % (r, g, b) if s[0] == '#': s = s.lower() if len(s)==7 and s[1]==s[2] and s[3]==s[4] and s[5]==s[6]: s = '#'+s[1]+s[3]+s[5] return s def convertColors(element) : """ Recursively converts all color properties into #RRGGBB format if shorter """ numBytes = 0 if element.nodeType != 1: return 0 # set up list of color attributes for each element type attrsToConvert = [] if element.nodeName in ['rect', 'circle', 'ellipse', 'polygon', \ 'line', 'polyline', 'path', 'g', 'a']: attrsToConvert = ['fill', 'stroke'] elif element.nodeName in ['stop']: attrsToConvert = ['stop-color'] elif element.nodeName in ['solidColor']: attrsToConvert = ['solid-color'] # now convert all the color formats styles = _getStyle(element) for attr in attrsToConvert: oldColorValue = element.getAttribute(attr) if oldColorValue != '': newColorValue = convertColor(oldColorValue) oldBytes = len(oldColorValue) newBytes = len(newColorValue) if oldBytes > newBytes: element.setAttribute(attr, newColorValue) numBytes += (oldBytes - len(element.getAttribute(attr))) # colors might also hide in styles if attr in styles.keys(): oldColorValue = styles[attr] newColorValue = convertColor(oldColorValue) oldBytes = len(oldColorValue) newBytes = len(newColorValue) if oldBytes > newBytes: styles[attr] = newColorValue numBytes += (oldBytes - len(element.getAttribute(attr))) _setStyle(element, styles) # now recurse for our child elements for child in element.childNodes : numBytes += convertColors(child) return numBytes # TODO: go over what this method does and see if there is a way to optimize it # TODO: go over the performance of this method and see if I can save memory/speed by # reusing data structures, etc def cleanPath(element, options) : """ Cleans the path string (d attribute) of the element """ global numBytesSavedInPathData global numPathSegmentsReduced global numCurvesStraightened # this gets the parser object from svg_regex.py oldPathStr = element.getAttribute('d') path = svg_parser.parse(oldPathStr) # This determines whether the stroke has round linecaps. If it does, # we do not want to collapse empty segments, as they are actually rendered. withRoundLineCaps = element.getAttribute('stroke-linecap') == 'round' # The first command must be a moveto, and whether it's relative (m) # or absolute (M), the first set of coordinates *is* absolute. So # the first iteration of the loop below will get x,y and startx,starty. # convert absolute coordinates into relative ones. # Reuse the data structure 'path', since we're not adding or removing subcommands. # Also reuse the coordinate lists since we're not adding or removing any. for pathIndex in xrange(0, len(path)): cmd, data = path[pathIndex] # Changes to cmd don't get through to the data structure i = 0 # adjust abs to rel # only the A command has some values that we don't want to adjust (radii, rotation, flags) if cmd == 'A': for i in xrange(i, len(data), 7): data[i+5] -= x data[i+6] -= y x += data[i+5] y += data[i+6] path[pathIndex] = ('a', data) elif cmd == 'a': x += sum(data[5::7]) y += sum(data[6::7]) elif cmd == 'H': for i in xrange(i, len(data)): data[i] -= x x += data[i] path[pathIndex] = ('h', data) elif cmd == 'h': x += sum(data) elif cmd == 'V': for i in xrange(i, len(data)): data[i] -= y y += data[i] path[pathIndex] = ('v', data) elif cmd == 'v': y += sum(data) elif cmd == 'M': startx, starty = data[0], data[1] # If this is a path starter, don't convert its first # coordinate to relative; that would just make it (0, 0) if pathIndex != 0: data[0] -= x data[1] -= y x, y = startx, starty i = 2 for i in xrange(i, len(data), 2): data[i] -= x data[i+1] -= y x += data[i] y += data[i+1] path[pathIndex] = ('m', data) elif cmd in ['L','T']: for i in xrange(i, len(data), 2): data[i] -= x data[i+1] -= y x += data[i] y += data[i+1] path[pathIndex] = (cmd.lower(), data) elif cmd in ['m']: if pathIndex == 0: # START OF PATH - this is an absolute moveto # followed by relative linetos startx, starty = data[0], data[1] x, y = startx, starty i = 2 else: startx = x + data[0] starty = y + data[1] for i in xrange(i, len(data), 2): x += data[i] y += data[i+1] elif cmd in ['l','t']: x += sum(data[0::2]) y += sum(data[1::2]) elif cmd in ['S','Q']: for i in xrange(i, len(data), 4): data[i] -= x data[i+1] -= y data[i+2] -= x data[i+3] -= y x += data[i+2] y += data[i+3] path[pathIndex] = (cmd.lower(), data) elif cmd in ['s','q']: x += sum(data[2::4]) y += sum(data[3::4]) elif cmd == 'C': for i in xrange(i, len(data), 6): data[i] -= x data[i+1] -= y data[i+2] -= x data[i+3] -= y data[i+4] -= x data[i+5] -= y x += data[i+4] y += data[i+5] path[pathIndex] = ('c', data) elif cmd == 'c': x += sum(data[4::6]) y += sum(data[5::6]) elif cmd in ['z','Z']: x, y = startx, starty path[pathIndex] = ('z', data) # remove empty segments # Reuse the data structure 'path' and the coordinate lists, even if we're # deleting items, because these deletions are relatively cheap. if not withRoundLineCaps: for pathIndex in xrange(0, len(path)): cmd, data = path[pathIndex] i = 0 if cmd in ['m','l','t']: if cmd == 'm': # remove m0,0 segments if pathIndex > 0 and data[0] == data[i+1] == 0: # 'm0,0 x,y' can be replaces with 'lx,y', # except the first m which is a required absolute moveto path[pathIndex] = ('l', data[2:]) numPathSegmentsReduced += 1 else: # else skip move coordinate i = 2 while i < len(data): if data[i] == data[i+1] == 0: del data[i:i+2] numPathSegmentsReduced += 1 else: i += 2 elif cmd == 'c': while i < len(data): if data[i] == data[i+1] == data[i+2] == data[i+3] == data[i+4] == data[i+5] == 0: del data[i:i+6] numPathSegmentsReduced += 1 else: i += 6 elif cmd == 'a': while i < len(data): if data[i+5] == data[i+6] == 0: del data[i:i+7] numPathSegmentsReduced += 1 else: i += 7 elif cmd == 'q': while i < len(data): if data[i] == data[i+1] == data[i+2] == data[i+3] == 0: del data[i:i+4] numPathSegmentsReduced += 1 else: i += 4 elif cmd in ['h','v']: oldLen = len(data) path[pathIndex] = (cmd, [coord for coord in data if coord != 0]) numPathSegmentsReduced += len(path[pathIndex][1]) - oldLen # fixup: Delete subcommands having no coordinates. path = [elem for elem in path if len(elem[1]) > 0 or elem[0] == 'z'] # convert straight curves into lines newPath = [path[0]] for (cmd,data) in path[1:]: i = 0 newData = data if cmd == 'c': newData = [] while i < len(data): # since all commands are now relative, we can think of previous point as (0,0) # and new point (dx,dy) is (data[i+4],data[i+5]) # eqn of line will be y = (dy/dx)*x or if dx=0 then eqn of line is x=0 (p1x,p1y) = (data[i],data[i+1]) (p2x,p2y) = (data[i+2],data[i+3]) dx = data[i+4] dy = data[i+5] foundStraightCurve = False if dx == 0: if p1x == 0 and p2x == 0: foundStraightCurve = True else: m = dy/dx if p1y == m*p1x and p2y == m*p2x: foundStraightCurve = True if foundStraightCurve: # flush any existing curve coords first if newData: newPath.append( (cmd,newData) ) newData = [] # now create a straight line segment newPath.append( ('l', [dx,dy]) ) numCurvesStraightened += 1 else: newData.extend(data[i:i+6]) i += 6 if newData or cmd == 'z' or cmd == 'Z': newPath.append( (cmd,newData) ) path = newPath # collapse all consecutive commands of the same type into one command prevCmd = '' prevData = [] newPath = [] for (cmd,data) in path: # flush the previous command if it is not the same type as the current command if prevCmd != '': if cmd != prevCmd or cmd == 'm': newPath.append( (prevCmd, prevData) ) prevCmd = '' prevData = [] # if the previous and current commands are the same type, # or the previous command is moveto and the current is lineto, collapse, # but only if they are not move commands (since move can contain implicit lineto commands) if (cmd == prevCmd or (cmd == 'l' and prevCmd == 'm')) and cmd != 'm': prevData.extend(data) # save last command and data else: prevCmd = cmd prevData = data # flush last command and data if prevCmd != '': newPath.append( (prevCmd, prevData) ) path = newPath # convert to shorthand path segments where possible newPath = [] for (cmd,data) in path: # convert line segments into h,v where possible if cmd == 'l': i = 0 lineTuples = [] while i < len(data): if data[i] == 0: # vertical if lineTuples: # flush the existing line command newPath.append( ('l', lineTuples) ) lineTuples = [] # append the v and then the remaining line coords newPath.append( ('v', [data[i+1]]) ) numPathSegmentsReduced += 1 elif data[i+1] == 0: if lineTuples: # flush the line command, then append the h and then the remaining line coords newPath.append( ('l', lineTuples) ) lineTuples = [] newPath.append( ('h', [data[i]]) ) numPathSegmentsReduced += 1 else: lineTuples.extend(data[i:i+2]) i += 2 if lineTuples: newPath.append( ('l', lineTuples) ) # also handle implied relative linetos elif cmd == 'm': i = 2 lineTuples = [data[0], data[1]] while i < len(data): if data[i] == 0: # vertical if lineTuples: # flush the existing m/l command newPath.append( (cmd, lineTuples) ) lineTuples = [] cmd = 'l' # dealing with linetos now # append the v and then the remaining line coords newPath.append( ('v', [data[i+1]]) ) numPathSegmentsReduced += 1 elif data[i+1] == 0: if lineTuples: # flush the m/l command, then append the h and then the remaining line coords newPath.append( (cmd, lineTuples) ) lineTuples = [] cmd = 'l' # dealing with linetos now newPath.append( ('h', [data[i]]) ) numPathSegmentsReduced += 1 else: lineTuples.extend(data[i:i+2]) i += 2 if lineTuples: newPath.append( (cmd, lineTuples) ) # convert Bézier curve segments into s where possible elif cmd == 'c': bez_ctl_pt = (0,0) i = 0 curveTuples = [] while i < len(data): # rotate by 180deg means negate both coordinates # if the previous control point is equal then we can substitute a # shorthand bezier command if bez_ctl_pt[0] == data[i] and bez_ctl_pt[1] == data[i+1]: if curveTuples: newPath.append( ('c', curveTuples) ) curveTuples = [] # append the s command newPath.append( ('s', [data[i+2], data[i+3], data[i+4], data[i+5]]) ) numPathSegmentsReduced += 1 else: j = 0 while j <= 5: curveTuples.append(data[i+j]) j += 1 # set up control point for next curve segment bez_ctl_pt = (data[i+4]-data[i+2], data[i+5]-data[i+3]) i += 6 if curveTuples: newPath.append( ('c', curveTuples) ) # convert quadratic curve segments into t where possible elif cmd == 'q': quad_ctl_pt = (0,0) i = 0 curveTuples = [] while i < len(data): if quad_ctl_pt[0] == data[i] and quad_ctl_pt[1] == data[i+1]: if curveTuples: newPath.append( ('q', curveTuples) ) curveTuples = [] # append the t command newPath.append( ('t', [data[i+2], data[i+3]]) ) numPathSegmentsReduced += 1 else: j = 0; while j <= 3: curveTuples.append(data[i+j]) j += 1 quad_ctl_pt = (data[i+2]-data[i], data[i+3]-data[i+1]) i += 4 if curveTuples: newPath.append( ('q', curveTuples) ) else: newPath.append( (cmd, data) ) path = newPath # for each h or v, collapse unnecessary coordinates that run in the same direction # i.e. "h-100-100" becomes "h-200" but "h300-100" does not change # Reuse the data structure 'path', since we're not adding or removing subcommands. # Also reuse the coordinate lists, even if we're deleting items, because these # deletions are relatively cheap. for pathIndex in xrange(1, len(path)): cmd, data = path[pathIndex] if cmd in ['h','v'] and len(data) > 1: coordIndex = 1 while coordIndex < len(data): if isSameSign(data[coordIndex - 1], data[coordIndex]): data[coordIndex - 1] += data[coordIndex] del data[coordIndex] numPathSegmentsReduced += 1 else: coordIndex += 1 # it is possible that we have consecutive h, v, c, t commands now # so again collapse all consecutive commands of the same type into one command prevCmd = '' prevData = [] newPath = [path[0]] for (cmd,data) in path[1:]: # flush the previous command if it is not the same type as the current command if prevCmd != '': if cmd != prevCmd or cmd == 'm': newPath.append( (prevCmd, prevData) ) prevCmd = '' prevData = [] # if the previous and current commands are the same type, collapse if cmd == prevCmd and cmd != 'm': prevData.extend(data) # save last command and data else: prevCmd = cmd prevData = data # flush last command and data if prevCmd != '': newPath.append( (prevCmd, prevData) ) path = newPath newPathStr = serializePath(path, options) numBytesSavedInPathData += ( len(oldPathStr) - len(newPathStr) ) element.setAttribute('d', newPathStr) def parseListOfPoints(s): """ Parse string into a list of points. Returns a list of containing an even number of coordinate strings """ i = 0 # (wsp)? comma-or-wsp-separated coordinate pairs (wsp)? # coordinate-pair = coordinate comma-or-wsp coordinate # coordinate = sign? integer # comma-wsp: (wsp+ comma? wsp*) | (comma wsp*) ws_nums = re.split(r"\s*,?\s*", s.strip()) nums = [] # also, if 100-100 is found, split it into two also # <polygon points="100,-100,100-100,100-100-100,-100-100" /> for i in xrange(len(ws_nums)): negcoords = ws_nums[i].split("-") # this string didn't have any negative coordinates if len(negcoords) == 1: nums.append(negcoords[0]) # we got negative coords else: for j in xrange(len(negcoords)): if j == 0: # first number could be positive if negcoords[0] != '': nums.append(negcoords[0]) # but it could also be negative elif len(nums) == 0: nums.append('-' + negcoords[j]) # otherwise all other strings will be negative else: # unless we accidentally split a number that was in scientific notation # and had a negative exponent (500.00e-1) prev = nums[len(nums)-1] if prev[len(prev)-1] in ['e', 'E']: nums[len(nums)-1] = prev + '-' + negcoords[j] else: nums.append( '-'+negcoords[j] ) # if we have an odd number of points, return empty if len(nums) % 2 != 0: return [] # now resolve into Decimal values i = 0 while i < len(nums): try: nums[i] = getcontext().create_decimal(nums[i]) nums[i + 1] = getcontext().create_decimal(nums[i + 1]) except decimal.InvalidOperation: # one of the lengths had a unit or is an invalid number return [] i += 2 return nums def cleanPolygon(elem, options): """ Remove unnecessary closing point of polygon points attribute """ global numPointsRemovedFromPolygon pts = parseListOfPoints(elem.getAttribute('points')) N = len(pts)/2 if N >= 2: (startx,starty) = pts[:2] (endx,endy) = pts[-2:] if startx == endx and starty == endy: del pts[-2:] numPointsRemovedFromPolygon += 1 elem.setAttribute('points', scourCoordinates(pts, options, True)) def cleanPolyline(elem, options): """ Scour the polyline points attribute """ pts = parseListOfPoints(elem.getAttribute('points')) elem.setAttribute('points', scourCoordinates(pts, options, True)) def serializePath(pathObj, options): """ Reserializes the path data with some cleanups. """ # elliptical arc commands must have comma/wsp separating the coordinates # this fixes an issue outlined in Fix https://bugs.launchpad.net/scour/+bug/412754 return ''.join([cmd + scourCoordinates(data, options, (cmd == 'a')) for cmd, data in pathObj]) def serializeTransform(transformObj): """ Reserializes the transform data with some cleanups. """ return ' '.join( [command + '(' + ' '.join( [scourUnitlessLength(number) for number in numbers] ) + ')' for command, numbers in transformObj] ) def scourCoordinates(data, options, forceCommaWsp = False): """ Serializes coordinate data with some cleanups: - removes all trailing zeros after the decimal - integerize coordinates if possible - removes extraneous whitespace - adds spaces between values in a subcommand if required (or if forceCommaWsp is True) """ if data != None: newData = [] c = 0 previousCoord = '' for coord in data: scouredCoord = scourUnitlessLength(coord, needsRendererWorkaround=options.renderer_workaround) # only need the comma if the current number starts with a digit # (numbers can start with - without needing a comma before) # or if forceCommaWsp is True # or if this number starts with a dot and the previous number # had *no* dot or exponent (so we can go like -5.5.5 for -5.5,0.5 # and 4e4.5 for 40000,0.5) if c > 0 and (forceCommaWsp or scouredCoord[0].isdigit() or (scouredCoord[0] == '.' and not ('.' in previousCoord or 'e' in previousCoord)) ): newData.append( ' ' ) # add the scoured coordinate to the path string newData.append( scouredCoord ) previousCoord = scouredCoord c += 1 # What we need to do to work around GNOME bugs 548494, 563933 and # 620565, which are being fixed and unfixed in Ubuntu, is # to make sure that a dot doesn't immediately follow a command # (so 'h50' and 'h0.5' are allowed, but not 'h.5'). # Then, we need to add a space character after any coordinates # having an 'e' (scientific notation), so as to have the exponent # separate from the next number. if options.renderer_workaround: if len(newData) > 0: for i in xrange(1, len(newData)): if newData[i][0] == '-' and 'e' in newData[i - 1]: newData[i - 1] += ' ' return ''.join(newData) else: return ''.join(newData) return '' def scourLength(length): """ Scours a length. Accepts units. """ length = SVGLength(length) return scourUnitlessLength(length.value) + Unit.str(length.units) def scourUnitlessLength(length, needsRendererWorkaround=False): # length is of a numeric type """ Scours the numeric part of a length only. Does not accept units. This is faster than scourLength on elements guaranteed not to contain units. """ # reduce to the proper number of digits if not isinstance(length, Decimal): length = getcontext().create_decimal(str(length)) # if the value is an integer, it may still have .0[...] attached to it for some reason # remove those if int(length) == length: length = getcontext().create_decimal(int(length)) # gather the non-scientific notation version of the coordinate. # this may actually be in scientific notation if the value is # sufficiently large or small, so this is a misnomer. nonsci = unicode(length).lower().replace("e+", "e") if not needsRendererWorkaround: if len(nonsci) > 2 and nonsci[:2] == '0.': nonsci = nonsci[1:] # remove the 0, leave the dot elif len(nonsci) > 3 and nonsci[:3] == '-0.': nonsci = '-' + nonsci[2:] # remove the 0, leave the minus and dot if len(nonsci) > 3: # avoid calling normalize unless strictly necessary # and then the scientific notation version, with E+NUMBER replaced with # just eNUMBER, since SVG accepts this. sci = unicode(length.normalize()).lower().replace("e+", "e") if len(sci) < len(nonsci): return sci else: return nonsci else: return nonsci def reducePrecision(element) : """ Because opacities, letter spacings, stroke widths and all that don't need to be preserved in SVG files with 9 digits of precision. Takes all of these attributes, in the given element node and its children, and reduces their precision to the current Decimal context's precision. Also checks for the attributes actually being lengths, not 'inherit', 'none' or anything that isn't an SVGLength. Returns the number of bytes saved after performing these reductions. """ num = 0 styles = _getStyle(element) for lengthAttr in ['opacity', 'flood-opacity', 'fill-opacity', 'stroke-opacity', 'stop-opacity', 'stroke-miterlimit', 'stroke-dashoffset', 'letter-spacing', 'word-spacing', 'kerning', 'font-size-adjust', 'font-size', 'stroke-width']: val = element.getAttribute(lengthAttr) if val != '': valLen = SVGLength(val) if valLen.units != Unit.INVALID: # not an absolute/relative size or inherit, can be % though newVal = scourLength(val) if len(newVal) < len(val): num += len(val) - len(newVal) element.setAttribute(lengthAttr, newVal) # repeat for attributes hidden in styles if lengthAttr in styles.keys(): val = styles[lengthAttr] valLen = SVGLength(val) if valLen.units != Unit.INVALID: newVal = scourLength(val) if len(newVal) < len(val): num += len(val) - len(newVal) styles[lengthAttr] = newVal _setStyle(element, styles) for child in element.childNodes: if child.nodeType == 1: num += reducePrecision(child) return num def optimizeAngle(angle): """ Because any rotation can be expressed within 360 degrees of any given number, and since negative angles sometimes are one character longer than corresponding positive angle, we shorten the number to one in the range to [-90, 270[. """ # First, we put the new angle in the range ]-360, 360[. # The modulo operator yields results with the sign of the # divisor, so for negative dividends, we preserve the sign # of the angle. if angle < 0: angle %= -360 else: angle %= 360 # 720 degrees is unneccessary, as 360 covers all angles. # As "-x" is shorter than "35x" and "-xxx" one character # longer than positive angles <= 260, we constrain angle # range to [-90, 270[ (or, equally valid: ]-100, 260]). if angle >= 270: angle -= 360 elif angle < -90: angle += 360 return angle def optimizeTransform(transform): """ Optimises a series of transformations parsed from a single transform="" attribute. The transformation list is modified in-place. """ # FIXME: reordering these would optimize even more cases: # first: Fold consecutive runs of the same transformation # extra: Attempt to cast between types to create sameness: # "matrix(0 1 -1 0 0 0) rotate(180) scale(-1)" all # are rotations (90, 180, 180) -- thus "rotate(90)" # second: Simplify transforms where numbers are optional. # third: Attempt to simplify any single remaining matrix() # # if there's only one transformation and it's a matrix, # try to make it a shorter non-matrix transformation # NOTE: as matrix(a b c d e f) in SVG means the matrix: # |¯ a c e ¯| make constants |¯ A1 A2 A3 ¯| # | b d f | translating them | B1 B2 B3 | # |_ 0 0 1 _| to more readable |_ 0 0 1 _| if len(transform) == 1 and transform[0][0] == 'matrix': matrix = A1, B1, A2, B2, A3, B3 = transform[0][1] # |¯ 1 0 0 ¯| # | 0 1 0 | Identity matrix (no transformation) # |_ 0 0 1 _| if matrix == [1, 0, 0, 1, 0, 0]: del transform[0] # |¯ 1 0 X ¯| # | 0 1 Y | Translation by (X, Y). # |_ 0 0 1 _| elif (A1 == 1 and A2 == 0 and B1 == 0 and B2 == 1): transform[0] = ('translate', [A3, B3]) # |¯ X 0 0 ¯| # | 0 Y 0 | Scaling by (X, Y). # |_ 0 0 1 _| elif ( A2 == 0 and A3 == 0 and B1 == 0 and B3 == 0): transform[0] = ('scale', [A1, B2]) # |¯ cos(A) -sin(A) 0 ¯| Rotation by angle A, # | sin(A) cos(A) 0 | clockwise, about the origin. # |_ 0 0 1 _| A is in degrees, [-180...180]. elif (A1 == B2 and -1 <= A1 <= 1 and A3 == 0 and -B1 == A2 and -1 <= B1 <= 1 and B3 == 0 # as cos² A + sin² A == 1 and as decimal trig is approximate: # FIXME: the "epsilon" term here should really be some function # of the precision of the (sin|cos)_A terms, not 1e-15: and abs((B1 ** 2) + (A1 ** 2) - 1) < Decimal("1e-15")): sin_A, cos_A = B1, A1 # while asin(A) and acos(A) both only have an 180° range # the sign of sin(A) and cos(A) varies across quadrants, # letting us hone in on the angle the matrix represents: # -- => < -90 | -+ => -90..0 | ++ => 0..90 | +- => >= 90 # # http://en.wikipedia.org/wiki/File:Sine_cosine_plot.svg # shows asin has the correct angle the middle quadrants: A = Decimal(str(math.degrees(math.asin(float(sin_A))))) if cos_A < 0: # otherwise needs adjusting from the edges if sin_A < 0: A = -180 - A else: A = 180 - A transform[0] = ('rotate', [A]) # Simplify transformations where numbers are optional. for type, args in transform: if type == 'translate': # Only the X coordinate is required for translations. # If the Y coordinate is unspecified, it's 0. if len(args) == 2 and args[1] == 0: del args[1] elif type == 'rotate': args[0] = optimizeAngle(args[0]) # angle # Only the angle is required for rotations. # If the coordinates are unspecified, it's the origin (0, 0). if len(args) == 3 and args[1] == args[2] == 0: del args[1:] elif type == 'scale': # Only the X scaling factor is required. # If the Y factor is unspecified, it's the same as X. if len(args) == 2 and args[0] == args[1]: del args[1] # Attempt to coalesce runs of the same transformation. # Translations followed immediately by other translations, # rotations followed immediately by other rotations, # scaling followed immediately by other scaling, # are safe to add. # Identity skewX/skewY are safe to remove, but how do they accrete? # |¯ 1 0 0 ¯| # | tan(A) 1 0 | skews X coordinates by angle A # |_ 0 0 1 _| # # |¯ 1 tan(A) 0 ¯| # | 0 1 0 | skews Y coordinates by angle A # |_ 0 0 1 _| # # FIXME: A matrix followed immediately by another matrix # would be safe to multiply together, too. i = 1 while i < len(transform): currType, currArgs = transform[i] prevType, prevArgs = transform[i - 1] if currType == prevType == 'translate': prevArgs[0] += currArgs[0] # x # for y, only add if the second translation has an explicit y if len(currArgs) == 2: if len(prevArgs) == 2: prevArgs[1] += currArgs[1] # y elif len(prevArgs) == 1: prevArgs.append(currArgs[1]) # y del transform[i] if prevArgs[0] == prevArgs[1] == 0: # Identity translation! i -= 1 del transform[i] elif (currType == prevType == 'rotate' and len(prevArgs) == len(currArgs) == 1): # Only coalesce if both rotations are from the origin. prevArgs[0] = optimizeAngle(prevArgs[0] + currArgs[0]) del transform[i] elif currType == prevType == 'scale': prevArgs[0] *= currArgs[0] # x # handle an implicit y if len(prevArgs) == 2 and len(currArgs) == 2: # y1 * y2 prevArgs[1] *= currArgs[1] elif len(prevArgs) == 1 and len(currArgs) == 2: # create y2 = uniformscalefactor1 * y2 prevArgs.append(prevArgs[0] * currArgs[1]) elif len(prevArgs) == 2 and len(currArgs) == 1: # y1 * uniformscalefactor2 prevArgs[1] *= currArgs[0] del transform[i] if prevArgs[0] == prevArgs[1] == 1: # Identity scale! i -= 1 del transform[i] else: i += 1 # Some fixups are needed for single-element transformation lists, since # the loop above was to coalesce elements with their predecessors in the # list, and thus it required 2 elements. i = 0 while i < len(transform): currType, currArgs = transform[i] if ((currType == 'skewX' or currType == 'skewY') and len(currArgs) == 1 and currArgs[0] == 0): # Identity skew! del transform[i] elif ((currType == 'rotate') and len(currArgs) == 1 and currArgs[0] == 0): # Identity rotation! del transform[i] else: i += 1 def optimizeTransforms(element, options) : """ Attempts to optimise transform specifications on the given node and its children. Returns the number of bytes saved after performing these reductions. """ num = 0 for transformAttr in ['transform', 'patternTransform', 'gradientTransform']: val = element.getAttribute(transformAttr) if val != '': transform = svg_transform_parser.parse(val) optimizeTransform(transform) newVal = serializeTransform(transform) if len(newVal) < len(val): if len(newVal): element.setAttribute(transformAttr, newVal) else: element.removeAttribute(transformAttr) num += len(val) - len(newVal) for child in element.childNodes: if child.nodeType == 1: num += optimizeTransforms(child, options) return num def removeComments(element) : """ Removes comments from the element and its children. """ global numCommentBytes if isinstance(element, xml.dom.minidom.Document): # must process the document object separately, because its # documentElement's nodes have None as their parentNode # iterate in reverse order to prevent mess-ups with renumbering for index in xrange(len(element.childNodes) - 1, -1, -1): subelement = element.childNodes[index] if isinstance(subelement, xml.dom.minidom.Comment): numCommentBytes += len(subelement.data) element.removeChild(subelement) else: removeComments(subelement) elif isinstance(element, xml.dom.minidom.Comment): numCommentBytes += len(element.data) element.parentNode.removeChild(element) else: # iterate in reverse order to prevent mess-ups with renumbering for index in xrange(len(element.childNodes) - 1, -1, -1): subelement = element.childNodes[index] removeComments(subelement) def embedRasters(element, options) : import base64 import urllib """ Converts raster references to inline images. NOTE: there are size limits to base64-encoding handling in browsers """ global numRastersEmbedded href = element.getAttributeNS(NS['XLINK'],'href') # if xlink:href is set, then grab the id if href != '' and len(href) > 1: # find if href value has filename ext ext = os.path.splitext(os.path.basename(href))[1].lower()[1:] # look for 'png', 'jpg', and 'gif' extensions if ext == 'png' or ext == 'jpg' or ext == 'gif': # file:// URLs denote files on the local system too if href[:7] == 'file://': href = href[7:] # does the file exist? if os.path.isfile(href): # if this is not an absolute path, set path relative # to script file based on input arg infilename = '.' if options.infilename: infilename = options.infilename href = os.path.join(os.path.dirname(infilename), href) rasterdata = '' # test if file exists locally if os.path.isfile(href): # open raster file as raw binary raster = open( href, "rb") rasterdata = raster.read() elif href[:7] == 'http://': webFile = urllib.urlopen( href ) rasterdata = webFile.read() webFile.close() # ... should we remove all images which don't resolve? if rasterdata != '' : # base64-encode raster b64eRaster = base64.b64encode( rasterdata ) # set href attribute to base64-encoded equivalent if b64eRaster != '': # PNG and GIF both have MIME Type 'image/[ext]', but # JPEG has MIME Type 'image/jpeg' if ext == 'jpg': ext = 'jpeg' element.setAttributeNS(NS['XLINK'], 'href', 'data:image/' + ext + ';base64,' + b64eRaster) numRastersEmbedded += 1 del b64eRaster def properlySizeDoc(docElement, options): # get doc width and height w = SVGLength(docElement.getAttribute('width')) h = SVGLength(docElement.getAttribute('height')) # if width/height are not unitless or px then it is not ok to rewrite them into a viewBox. # well, it may be OK for Web browsers and vector editors, but not for librsvg. if options.renderer_workaround: if ((w.units != Unit.NONE and w.units != Unit.PX) or (h.units != Unit.NONE and h.units != Unit.PX)): return # else we have a statically sized image and we should try to remedy that # parse viewBox attribute vbSep = re.split("\\s*\\,?\\s*", docElement.getAttribute('viewBox'), 3) # if we have a valid viewBox we need to check it vbWidth,vbHeight = 0,0 if len(vbSep) == 4: try: # if x or y are specified and non-zero then it is not ok to overwrite it vbX = float(vbSep[0]) vbY = float(vbSep[1]) if vbX != 0 or vbY != 0: return # if width or height are not equal to doc width/height then it is not ok to overwrite it vbWidth = float(vbSep[2]) vbHeight = float(vbSep[3]) if vbWidth != w.value or vbHeight != h.value: return # if the viewBox did not parse properly it is invalid and ok to overwrite it except ValueError: pass # at this point it's safe to set the viewBox and remove width/height docElement.setAttribute('viewBox', '0 0 %s %s' % (w.value, h.value)) docElement.removeAttribute('width') docElement.removeAttribute('height') def remapNamespacePrefix(node, oldprefix, newprefix): if node == None or node.nodeType != 1: return if node.prefix == oldprefix: localName = node.localName namespace = node.namespaceURI doc = node.ownerDocument parent = node.parentNode # create a replacement node newNode = None if newprefix != '': newNode = doc.createElementNS(namespace, newprefix+":"+localName) else: newNode = doc.createElement(localName); # add all the attributes attrList = node.attributes for i in xrange(attrList.length): attr = attrList.item(i) newNode.setAttributeNS( attr.namespaceURI, attr.localName, attr.nodeValue) # clone and add all the child nodes for child in node.childNodes: newNode.appendChild(child.cloneNode(True)) # replace old node with new node parent.replaceChild( newNode, node ) # set the node to the new node in the remapped namespace prefix node = newNode # now do all child nodes for child in node.childNodes : remapNamespacePrefix(child, oldprefix, newprefix) def makeWellFormed(str): xml_ents = { '<':'&lt;', '>':'&gt;', '&':'&amp;', "'":'&apos;', '"':'&quot;'} # starr = [] # for c in str: # if c in xml_ents: # starr.append(xml_ents[c]) # else: # starr.append(c) # this list comprehension is short-form for the above for-loop: return ''.join([xml_ents[c] if c in xml_ents else c for c in str]) # hand-rolled serialization function that has the following benefits: # - pretty printing # - somewhat judicious use of whitespace # - ensure id attributes are first def serializeXML(element, options, ind = 0, preserveWhitespace = False): outParts = [] indent = ind I='' if options.indent_type == 'tab': I='\t' elif options.indent_type == 'space': I=' ' outParts.extend([(I * ind), '<', element.nodeName]) # always serialize the id or xml:id attributes first if element.getAttribute('id') != '': id = element.getAttribute('id') quot = '"' if id.find('"') != -1: quot = "'" outParts.extend([' id=', quot, id, quot]) if element.getAttribute('xml:id') != '': id = element.getAttribute('xml:id') quot = '"' if id.find('"') != -1: quot = "'" outParts.extend([' xml:id=', quot, id, quot]) # now serialize the other attributes attrList = element.attributes for num in xrange(attrList.length) : attr = attrList.item(num) if attr.nodeName == 'id' or attr.nodeName == 'xml:id': continue # if the attribute value contains a double-quote, use single-quotes quot = '"' if attr.nodeValue.find('"') != -1: quot = "'" attrValue = makeWellFormed( attr.nodeValue ) outParts.append(' ') # preserve xmlns: if it is a namespace prefix declaration if attr.prefix != None: outParts.extend([attr.prefix, ':']) elif attr.namespaceURI != None: if attr.namespaceURI == 'http://www.w3.org/2000/xmlns/' and attr.nodeName.find('xmlns') == -1: outParts.append('xmlns:') elif attr.namespaceURI == 'http://www.w3.org/1999/xlink': outParts.append('xlink:') outParts.extend([attr.localName, '=', quot, attrValue, quot]) if attr.nodeName == 'xml:space': if attrValue == 'preserve': preserveWhitespace = True elif attrValue == 'default': preserveWhitespace = False # if no children, self-close children = element.childNodes if children.length > 0: outParts.append('>') onNewLine = False for child in element.childNodes: # element node if child.nodeType == 1: if preserveWhitespace: outParts.append(serializeXML(child, options, 0, preserveWhitespace)) else: outParts.extend(['\n', serializeXML(child, options, indent + 1, preserveWhitespace)]) onNewLine = True # text node elif child.nodeType == 3: # trim it only in the case of not being a child of an element # where whitespace might be important if preserveWhitespace: outParts.append(makeWellFormed(child.nodeValue)) else: outParts.append(makeWellFormed(child.nodeValue.strip())) # CDATA node elif child.nodeType == 4: outParts.extend(['<![CDATA[', child.nodeValue, ']]>']) # Comment node elif child.nodeType == 8: outParts.extend(['<!--', child.nodeValue, '-->']) # TODO: entities, processing instructions, what else? else: # ignore the rest pass if onNewLine: outParts.append(I * ind) outParts.extend(['</', element.nodeName, '>']) if indent > 0: outParts.append('\n') else: outParts.append('/>') if indent > 0: outParts.append('\n') return "".join(outParts) # this is the main method # input is a string representation of the input XML # returns a string representation of the output XML def scourString(in_string, options=None): if options is None: options = _options_parser.get_default_values() getcontext().prec = options.digits global numAttrsRemoved global numStylePropsFixed global numElemsRemoved global numBytesSavedInColors global numCommentsRemoved global numBytesSavedInIDs global numBytesSavedInLengths global numBytesSavedInTransforms doc = xml.dom.minidom.parseString(in_string) # for whatever reason this does not always remove all inkscape/sodipodi attributes/elements # on the first pass, so we do it multiple times # does it have to do with removal of children affecting the childlist? if options.keep_editor_data == False: while removeNamespacedElements( doc.documentElement, unwanted_ns ) > 0 : pass while removeNamespacedAttributes( doc.documentElement, unwanted_ns ) > 0 : pass # remove the xmlns: declarations now xmlnsDeclsToRemove = [] attrList = doc.documentElement.attributes for num in xrange(attrList.length) : if attrList.item(num).nodeValue in unwanted_ns : xmlnsDeclsToRemove.append(attrList.item(num).nodeName) for attr in xmlnsDeclsToRemove : doc.documentElement.removeAttribute(attr) numAttrsRemoved += 1 # ensure namespace for SVG is declared # TODO: what if the default namespace is something else (i.e. some valid namespace)? if doc.documentElement.getAttribute('xmlns') != 'http://www.w3.org/2000/svg': doc.documentElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg') # TODO: throw error or warning? # check for redundant SVG namespace declaration attrList = doc.documentElement.attributes xmlnsDeclsToRemove = [] redundantPrefixes = [] for i in xrange(attrList.length): attr = attrList.item(i) name = attr.nodeName val = attr.nodeValue if name[0:6] == 'xmlns:' and val == 'http://www.w3.org/2000/svg': redundantPrefixes.append(name[6:]) xmlnsDeclsToRemove.append(name) for attrName in xmlnsDeclsToRemove: doc.documentElement.removeAttribute(attrName) for prefix in redundantPrefixes: remapNamespacePrefix(doc.documentElement, prefix, '') if options.strip_comments: numCommentsRemoved = removeComments(doc) # repair style (remove unnecessary style properties and change them into XML attributes) numStylePropsFixed = repairStyle(doc.documentElement, options) # convert colors to #RRGGBB format if options.simple_colors: numBytesSavedInColors = convertColors(doc.documentElement) # remove <metadata> if the user wants to if options.remove_metadata: removeMetadataElements(doc) # flattend defs elements into just one defs element flattenDefs(doc) # remove unreferenced gradients/patterns outside of defs # and most unreferenced elements inside of defs while removeUnreferencedElements(doc) > 0: pass # remove empty defs, metadata, g # NOTE: these elements will be removed if they just have whitespace-only text nodes for tag in ['defs', 'metadata', 'g'] : for elem in doc.documentElement.getElementsByTagName(tag) : removeElem = not elem.hasChildNodes() if removeElem == False : for child in elem.childNodes : if child.nodeType in [1, 4, 8]: break elif child.nodeType == 3 and not child.nodeValue.isspace(): break else: removeElem = True if removeElem : elem.parentNode.removeChild(elem) numElemsRemoved += 1 if options.strip_ids: bContinueLooping = True while bContinueLooping: identifiedElements = unprotected_ids(doc, options) referencedIDs = findReferencedElements(doc.documentElement) bContinueLooping = (removeUnreferencedIDs(referencedIDs, identifiedElements) > 0) while removeDuplicateGradientStops(doc) > 0: pass # remove gradients that are only referenced by one other gradient while collapseSinglyReferencedGradients(doc) > 0: pass # remove duplicate gradients while removeDuplicateGradients(doc) > 0: pass # create <g> elements if there are runs of elements with the same attributes. # this MUST be before moveCommonAttributesToParentGroup. if options.group_create: createGroupsForCommonAttributes(doc.documentElement) # move common attributes to parent group # NOTE: the if the <svg> element's immediate children # all have the same value for an attribute, it must not # get moved to the <svg> element. The <svg> element # doesn't accept fill=, stroke= etc.! referencedIds = findReferencedElements(doc.documentElement) for child in doc.documentElement.childNodes: numAttrsRemoved += moveCommonAttributesToParentGroup(child, referencedIds) # remove unused attributes from parent numAttrsRemoved += removeUnusedAttributesOnParent(doc.documentElement) # Collapse groups LAST, because we've created groups. If done before # moveAttributesToParentGroup, empty <g>'s may remain. if options.group_collapse: while removeNestedGroups(doc.documentElement) > 0: pass # remove unnecessary closing point of polygons and scour points for polygon in doc.documentElement.getElementsByTagName('polygon') : cleanPolygon(polygon, options) # scour points of polyline for polyline in doc.documentElement.getElementsByTagName('polyline') : cleanPolyline(polyline, options) # clean path data for elem in doc.documentElement.getElementsByTagName('path') : if elem.getAttribute('d') == '': elem.parentNode.removeChild(elem) else: cleanPath(elem, options) # shorten ID names as much as possible if options.shorten_ids: numBytesSavedInIDs += shortenIDs(doc, unprotected_ids(doc, options)) # scour lengths (including coordinates) for type in ['svg', 'image', 'rect', 'circle', 'ellipse', 'line', 'linearGradient', 'radialGradient', 'stop', 'filter']: for elem in doc.getElementsByTagName(type): for attr in ['x', 'y', 'width', 'height', 'cx', 'cy', 'r', 'rx', 'ry', 'x1', 'y1', 'x2', 'y2', 'fx', 'fy', 'offset']: if elem.getAttribute(attr) != '': elem.setAttribute(attr, scourLength(elem.getAttribute(attr))) # more length scouring in this function numBytesSavedInLengths = reducePrecision(doc.documentElement) # remove default values of attributes numAttrsRemoved += removeDefaultAttributeValues(doc.documentElement, options) # reduce the length of transformation attributes numBytesSavedInTransforms = optimizeTransforms(doc.documentElement, options) # convert rasters references to base64-encoded strings if options.embed_rasters: for elem in doc.documentElement.getElementsByTagName('image') : embedRasters(elem, options) # properly size the SVG document (ideally width/height should be 100% with a viewBox) if options.enable_viewboxing: properlySizeDoc(doc.documentElement, options) # output the document as a pretty string with a single space for indent # NOTE: removed pretty printing because of this problem: # http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace/ # rolled our own serialize function here to save on space, put id first, customize indentation, etc # out_string = doc.documentElement.toprettyxml(' ') out_string = serializeXML(doc.documentElement, options) + '\n' # now strip out empty lines lines = [] # Get rid of empty lines for line in out_string.splitlines(True): if line.strip(): lines.append(line) # return the string with its XML prolog and surrounding comments if options.strip_xml_prolog == False: total_output = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n' else: total_output = "" for child in doc.childNodes: if child.nodeType == 1: total_output += "".join(lines) else: # doctypes, entities, comments total_output += child.toxml() + '\n' return total_output # used mostly by unit tests # input is a filename # returns the minidom doc representation of the SVG def scourXmlFile(filename, options=None): in_string = open(filename).read() out_string = scourString(in_string, options) return xml.dom.minidom.parseString(out_string.encode('utf-8')) # GZ: Seems most other commandline tools don't do this, is it really wanted? class HeaderedFormatter(optparse.IndentedHelpFormatter): """ Show application name, version number, and copyright statement above usage information. """ def format_usage(self, usage): return "%s %s\n%s\n%s" % (APP, VER, COPYRIGHT, optparse.IndentedHelpFormatter.format_usage(self, usage)) # GZ: would prefer this to be in a function or class scope, but tests etc need # access to the defaults anyway _options_parser = optparse.OptionParser( usage="%prog [-i input.svg] [-o output.svg] [OPTIONS]", description=("If the input/output files are specified with a svgz" " extension, then compressed SVG is assumed. If the input file is not" " specified, stdin is used. If the output file is not specified, " " stdout is used."), formatter=HeaderedFormatter(max_help_position=30), version=VER) _options_parser.add_option("--disable-simplify-colors", action="store_false", dest="simple_colors", default=True, help="won't convert all colors to #RRGGBB format") _options_parser.add_option("--disable-style-to-xml", action="store_false", dest="style_to_xml", default=True, help="won't convert styles into XML attributes") _options_parser.add_option("--disable-group-collapsing", action="store_false", dest="group_collapse", default=True, help="won't collapse <g> elements") _options_parser.add_option("--create-groups", action="store_true", dest="group_create", default=False, help="create <g> elements for runs of elements with identical attributes") _options_parser.add_option("--enable-id-stripping", action="store_true", dest="strip_ids", default=False, help="remove all un-referenced ID attributes") _options_parser.add_option("--enable-comment-stripping", action="store_true", dest="strip_comments", default=False, help="remove all <!-- --> comments") _options_parser.add_option("--shorten-ids", action="store_true", dest="shorten_ids", default=False, help="shorten all ID attributes to the least number of letters possible") _options_parser.add_option("--disable-embed-rasters", action="store_false", dest="embed_rasters", default=True, help="won't embed rasters as base64-encoded data") _options_parser.add_option("--keep-editor-data", action="store_true", dest="keep_editor_data", default=False, help="won't remove Inkscape, Sodipodi or Adobe Illustrator elements and attributes") _options_parser.add_option("--remove-metadata", action="store_true", dest="remove_metadata", default=False, help="remove <metadata> elements (which may contain license metadata etc.)") _options_parser.add_option("--renderer-workaround", action="store_true", dest="renderer_workaround", default=True, help="work around various renderer bugs (currently only librsvg) (default)") _options_parser.add_option("--no-renderer-workaround", action="store_false", dest="renderer_workaround", default=True, help="do not work around various renderer bugs (currently only librsvg)") _options_parser.add_option("--strip-xml-prolog", action="store_true", dest="strip_xml_prolog", default=False, help="won't output the <?xml ?> prolog") _options_parser.add_option("--enable-viewboxing", action="store_true", dest="enable_viewboxing", default=False, help="changes document width/height to 100%/100% and creates viewbox coordinates") # GZ: this is confusing, most people will be thinking in terms of # decimal places, which is not what decimal precision is doing _options_parser.add_option("-p", "--set-precision", action="store", type=int, dest="digits", default=5, help="set number of significant digits (default: %default)") _options_parser.add_option("-i", action="store", dest="infilename", help=optparse.SUPPRESS_HELP) _options_parser.add_option("-o", action="store", dest="outfilename", help=optparse.SUPPRESS_HELP) _options_parser.add_option("-q", "--quiet", action="store_true", dest="quiet", default=False, help="suppress non-error output") _options_parser.add_option("--indent", action="store", type="string", dest="indent_type", default="space", help="indentation of the output: none, space, tab (default: %default)") _options_parser.add_option("--protect-ids-noninkscape", action="store_true", dest="protect_ids_noninkscape", default=False, help="Don't change IDs not ending with a digit") _options_parser.add_option("--protect-ids-list", action="store", type="string", dest="protect_ids_list", default=None, help="Don't change IDs given in a comma-separated list") _options_parser.add_option("--protect-ids-prefix", action="store", type="string", dest="protect_ids_prefix", default=None, help="Don't change IDs starting with the given prefix") def maybe_gziped_file(filename, mode="r"): if os.path.splitext(filename)[1].lower() in (".svgz", ".gz"): import gzip return gzip.GzipFile(filename, mode) return file(filename, mode) def parse_args(args=None): options, rargs = _options_parser.parse_args(args) if rargs: _options_parser.error("Additional arguments not handled: %r, see --help" % rargs) if options.digits < 0: _options_parser.error("Can't have negative significant digits, see --help") if not options.indent_type in ["tab", "space", "none"]: _options_parser.error("Invalid value for --indent, see --help") if options.infilename and options.outfilename and options.infilename == options.outfilename: _options_parser.error("Input filename is the same as output filename") if options.infilename: infile = maybe_gziped_file(options.infilename) # GZ: could catch a raised IOError here and report else: # GZ: could sniff for gzip compression here infile = sys.stdin if options.outfilename: outfile = maybe_gziped_file(options.outfilename, "wb") else: outfile = sys.stdout return options, [infile, outfile] def getReport(): return ' Number of elements removed: ' + str(numElemsRemoved) + os.linesep + \ ' Number of attributes removed: ' + str(numAttrsRemoved) + os.linesep + \ ' Number of unreferenced id attributes removed: ' + str(numIDsRemoved) + os.linesep + \ ' Number of style properties fixed: ' + str(numStylePropsFixed) + os.linesep + \ ' Number of raster images embedded inline: ' + str(numRastersEmbedded) + os.linesep + \ ' Number of path segments reduced/removed: ' + str(numPathSegmentsReduced) + os.linesep + \ ' Number of bytes saved in path data: ' + str(numBytesSavedInPathData) + os.linesep + \ ' Number of bytes saved in colors: ' + str(numBytesSavedInColors) + os.linesep + \ ' Number of points removed from polygons: ' + str(numPointsRemovedFromPolygon) + os.linesep + \ ' Number of bytes saved in comments: ' + str(numCommentBytes) + os.linesep + \ ' Number of bytes saved in id attributes: ' + str(numBytesSavedInIDs) + os.linesep + \ ' Number of bytes saved in lengths: ' + str(numBytesSavedInLengths) + os.linesep + \ ' Number of bytes saved in transformations: ' + str(numBytesSavedInTransforms) if __name__ == '__main__': if sys.platform == "win32": from time import clock as get_tick else: # GZ: is this different from time.time() in any way? def get_tick(): return os.times()[0] start = get_tick() options, (input, output) = parse_args() if not options.quiet: print >>sys.stderr, "%s %s\n%s" % (APP, VER, COPYRIGHT) # do the work in_string = input.read() out_string = scourString(in_string, options).encode("UTF-8") output.write(out_string) # Close input and output files input.close() output.close() end = get_tick() # GZ: not using globals would be good too if not options.quiet: print >>sys.stderr, ' File:', input.name, \ os.linesep + ' Time taken:', str(end-start) + 's' + os.linesep, \ getReport() oldsize = len(in_string) newsize = len(out_string) sizediff = (newsize / oldsize) * 100 print >>sys.stderr, ' Original file size:', oldsize, 'bytes;', \ 'new file size:', newsize, 'bytes (' + str(sizediff)[:5] + '%)'
piksels-and-lines-orchestra/inkscape
share/extensions/scour.py
Python
gpl-2.0
110,535
""" Testing Image spaces """ from __future__ import absolute_import import numpy as np import nibabel as nib from nibabel.affines import from_matvec from ..image import Image, rollimg from ..image_spaces import (is_xyz_affable, as_xyz_image, xyz_affine, make_xyz_image) from ...reference.coordinate_system import CoordinateSystem as CS from ...reference.coordinate_map import AffineTransform from ...reference.spaces import (vox2mni, vox2talairach, voxel_csm, mni_space, talairach_space, AffineError, AxesError, XYZSpace, SpaceError) from numpy.testing import (assert_array_almost_equal, assert_array_equal) from nose.tools import assert_true, assert_false, assert_equal, assert_raises def test_image_xyz_affine(): # Test getting the image xyz affines arr = np.arange(24).reshape((2,3,4)) aff = np.diag([2,3,4,1]) img = Image(arr, vox2mni(aff)) assert_true(is_xyz_affable(img)) assert_array_equal(xyz_affine(img), aff) arr4 = np.arange(24).reshape((1,2,3,4)) img4 = Image(arr4, vox2mni(np.diag([2,3,4,5,1]))) assert_true(is_xyz_affable(img4)) img4_r = img4.reordered_axes([3,2,0,1]) assert_false(is_xyz_affable(img4_r)) assert_raises(AxesError, xyz_affine, img4_r) nimg = nib.Nifti1Image(arr, aff) assert_true(is_xyz_affable(nimg)) assert_array_equal(xyz_affine(nimg), aff) # Any dimensions not spatial, AxesError d_cs = CS('ijk', 'voxels') r_cs = CS(('mni-x=L->R', 'mni-y=P->A', 'mni-q'), 'mni') cmap = AffineTransform(d_cs,r_cs, aff) img = Image(arr, cmap) assert_raises(AxesError, xyz_affine, img) # Can pass in own validator my_valtor = dict(blind='x', leading='y', ditch='z') r_cs = CS(('blind', 'leading', 'ditch'), 'fall') cmap = AffineTransform(d_cs, r_cs, aff) img = Image(arr, cmap) assert_raises(AxesError, xyz_affine, img) assert_array_equal(xyz_affine(img, my_valtor), aff) def test_image_as_xyz_image(): # Test getting xyz affable version of the image arr = np.arange(24).reshape((1,2,3,4)) aff = np.diag([2,3,4,5,1]) img = Image(arr, vox2mni(aff)) img_r = as_xyz_image(img) assert_true(img is img_r) # Reorder, reverse reordering, test != and == for order in ((3, 0, 1, 2), (0, 3, 1, 2)): img_ro_out = img.reordered_reference(order) img_ro_in = img.reordered_axes(order) img_ro_both = img_ro_out.reordered_axes(order) for tmap in (img_ro_out, img_ro_in, img_ro_both): assert_false(is_xyz_affable(tmap)) img_r = as_xyz_image(tmap) assert_false(tmap is img_r) assert_equal(img, img_r) assert_array_equal(img.get_data(), img_r.get_data()) img_t0 = rollimg(img, 't') assert_false(is_xyz_affable(img_t0)) img_t0_r = as_xyz_image(img_t0) assert_false(img_t0 is img_t0_r) assert_array_equal(img.get_data(), img_t0_r.get_data()) assert_equal(img.coordmap, img_t0_r.coordmap) # Test against nibabel image nimg = nib.Nifti1Image(arr, np.diag([2,3,4,1])) nimg_r = as_xyz_image(nimg) assert_true(nimg is nimg_r) # It's sometimes impossible to make an xyz affable image # If the xyz coordinates depend on the time coordinate aff = np.array([[2, 0, 0, 2, 20], [0, 3, 0, 0, 21], [0, 0, 4, 0, 22], [0, 0, 0, 5, 23], [0, 0, 0, 0, 1]]) img = Image(arr, vox2mni(aff)) assert_raises(AffineError, as_xyz_image, img) # If any dimensions not spatial, AxesError arr = np.arange(24).reshape((2,3,4)) aff = np.diag([2,3,4,1]) d_cs = CS('ijk', 'voxels') r_cs = CS(('mni-x=L->R', 'mni-y=P->A', 'mni-q'), 'mni') cmap = AffineTransform(d_cs, r_cs, aff) img = Image(arr, cmap) assert_raises(AxesError, as_xyz_image, img) # Can pass in own validator my_valtor = dict(blind='x', leading='y', ditch='z') r_cs = CS(('blind', 'leading', 'ditch'), 'fall') cmap = AffineTransform(d_cs, r_cs, aff) img = Image(arr, cmap) assert_raises(AxesError, as_xyz_image, img) assert_true(as_xyz_image(img, my_valtor) is img) def test_image_xyza_slices(): # Jonathan found some nastiness where xyz present in output but there was # not corresponding axis for x in the input arr = np.arange(24).reshape((1,2,3,4)) aff = np.diag([2,3,4,5,1]) img = Image(arr, vox2mni(aff)) img0 = img[0] # slice in X # The result does not have an input axis corresponding to x, and should # raise an error assert_raises(AxesError, as_xyz_image, img0) img0r = img0.reordered_reference([1,0,2,3]).reordered_axes([2,0,1]) assert_raises(AxesError, as_xyz_image, img0r) def test_make_xyz_image(): # Standard neuro image creator arr = np.arange(24).reshape((1,2,3,4)) aff = np.diag([2,3,4,1]) img = make_xyz_image(arr, aff, 'mni') assert_equal(img.coordmap, vox2mni(aff, 1.0)) assert_array_equal(img.get_data(), arr) img = make_xyz_image(arr, aff, 'talairach') assert_equal(img.coordmap, vox2talairach(aff, 1.0)) assert_array_equal(img.get_data(), arr) img = make_xyz_image(arr, aff, talairach_space) assert_equal(img.coordmap, vox2talairach(aff, 1.0)) # Unknown space as string raises SpaceError assert_raises(SpaceError, make_xyz_image, arr, aff, 'unlikely space name') funky_space = XYZSpace('hija') img = make_xyz_image(arr, aff, funky_space) csm = funky_space.to_coordsys_maker('t') in_cs = CS('ijkl', 'voxels') exp_cmap = AffineTransform(in_cs, csm(4), np.diag([2, 3, 4, 1, 1])) assert_equal(img.coordmap, exp_cmap) # Affine must be 4, 4 bad_aff = np.diag([2,3,4,2,1]) assert_raises(ValueError, make_xyz_image, arr, bad_aff, 'mni') # Can pass added zooms img = make_xyz_image(arr, (aff, (2.,)), 'mni') assert_equal(img.coordmap, vox2mni(aff, 2.0)) # Also as scalar img = make_xyz_image(arr, (aff, 2.), 'mni') assert_equal(img.coordmap, vox2mni(aff, 2.0)) # Must match length of needed zooms arr5 = arr[...,None] assert_raises(ValueError, make_xyz_image, arr5, (aff, 2.), 'mni') img = make_xyz_image(arr5, (aff, (2., 3.)), 'mni') assert_equal(img.coordmap, vox2mni(aff, (2.0, 3.0))) # Always xyz affable after creation assert_array_equal(xyz_affine(img), aff) assert_true(is_xyz_affable(img)) # Need at least 3 dimensions in data assert_raises(ValueError, make_xyz_image, np.zeros((2,3)), aff, 'mni') # Check affines don't round / floor floating point aff = np.diag([2.1, 3, 4, 1]) img = make_xyz_image(np.zeros((2, 3, 4)), aff, 'scanner') assert_array_equal(img.coordmap.affine, aff) img = make_xyz_image(np.zeros((2, 3, 4, 5)), aff, 'scanner') assert_array_equal(img.coordmap.affine, np.diag([2.1, 3, 4, 1, 1]))
alexis-roche/nipy
nipy/core/image/tests/test_image_spaces.py
Python
bsd-3-clause
6,953
#* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgpl-2.1.html import sys, os, json, shutil from collections import namedtuple from Scheduler import Scheduler from TestHarness.StatusSystem import StatusSystem class QueueManager(Scheduler): """ QueueManager is a Scheduler plugin responsible for allowing the testers to be scheduled via a third-party queue system (like PBS). The QueueManager works by intercepting and altering the statuses of all but one job contained in the group to a finished state. This affords us the behavior of only using the runner thread pool once per group (see augmentJobs). Using this one unmodified job, the spec file involved is noted, and instructs the derived scheduler how to launch this one single spec file (using --spec-file), along with any supplied/allowable command line arguments (--re, --cli-args, --ignore, etc). The third-party queueing manager then executes `run_tests --spec-file /path/to/spec_file`. It is the results of this additional ./run_tests run, that is captured and presented to the user as the finished result of the test. """ @staticmethod def validParams(): params = Scheduler.validParams() return params def __init__(self, harness, params): Scheduler.__init__(self, harness, params) self.harness = harness self.options = self.harness.getOptions() self.__job_storage_file = self.harness.original_storage self.__clean_args = None def augmentJobs(self, Jobs): """ Filter through incomming jobs and figure out if we are launching them or attempting to process finished results. """ # Flatten the DAG. We want to easily iterate over all jobs produced by the spec file Jobs.removeAllDependencies() # Perform cleanup operations and return if thats what the user wants if self.options.queue_cleanup: self._cleanupFiles(Jobs) return # Create a namedtuple of frequently used information contained within Jobs, so we can # more easily pass this information among our methods job_list = Jobs.getJobs() if job_list: queue_data = namedtuple('JobData', ['jobs', 'job_dir', 'json_data', 'plugin']) job_data = queue_data(jobs=Jobs, job_dir=job_list[0].getTestDir(), json_data=self.options.results_storage, plugin=self.harness.scheduler.__class__.__name__) if self._isProcessReady(job_data): self._setJobStatus(job_data) elif self._isLaunchable(job_data): self._prepareJobs(job_data) def createQueueScript(self, job, template): """ Write the launch script to disc """ # Get a list of prereq tests this test may have try: with open(self.params['queue_template'], 'r') as f: content = f.read() with open(template['launch_script'], 'w') as queue_script: # Do all of the replacements for valid parameters for key in template.keys(): if key.upper() in content: content = content.replace('<' + key.upper() + '>', str(template[key])) # Strip out parameters that were not supplied for key in template.keys(): if key.upper() not in content: content = content.replace('<' + key.upper() + '>', '') queue_script.write(content) except IOError as e: print(e) sys.exit(1) def reserveSlots(self, job, j_lock): """ Inherited method from the Scheduler to handle slot allocation. QueueManager does not need an allocation system, so this method simply returns True """ return True def getBadArgs(self): """ Arguments which should be removed from the launch script invoking ./run_tests """ return [] def getBadKeyArgs(self): """ Key/Value arguments which should be removed from the launch script invoking ./run_tests """ return [] def getCores(self, job_data): """ iterate over Jobs and collect the maximum core requirement from the group of jobs which will run """ slots = 1 for job in [x for x in job_data.jobs.getJobs() if not x.isSkip()]: slots = max(slots, job.getSlots()) return slots def getMaxTime(self, job_data): """ iterate over Jobs and increment the total allowable time needed to complete the entire group """ total_time = 0 for job in [x for x in job_data.jobs.getJobs() if not x.isSkip()]: total_time += int(job.getMaxTime()) return total_time def addDirtyFiles(self, job, file_list=[]): """ append list of files which will be generated by derived scheduler """ job_data = job.getMetaData() file_list.extend(job_data.get('QUEUE_FILES', [])) job.addMetaData(QUEUE_FILES=file_list) def getDirtyFiles(self, job): """ return list of files not indigenous to the repository which was created by third party schedulers """ dirty_files = [] if self.options.results_storage and self.options.results_storage.get(job.getTestDir(), {}): dirty_files = self.options.results_storage[job.getTestDir()].get('QUEUE_FILES', []) return dirty_files def cleanAndModifyArgs(self): """ Filter out any arguments that will otherwise break the TestHarness when launched _within_ the third party scheduler (such as --pbs) """ # return cached args if we have already produced clean args if not self.__clean_args: current_args = list(sys.argv[1:]) # Ask derived schedulers for any additional args we should strip from sys.args bad_args = self.getBadArgs() bad_keyword_args = self.getBadKeyArgs() # Split keyword args so we can match/remove them (the key, and its value pair) key_value_args = [x for x in current_args if '=' in x] for arg in key_value_args: current_args.remove(arg) current_args.extend(arg.split('=')) # Note: we are removing cli-args/ignore because we need to re-encapsulate them below bad_keyword_args.extend(['--spec-file', '-i', '--cli-args', '-j', '-l', '-o', '--output-dir', '--ignore', '--re']) # remove the key=value pair argument for arg in bad_keyword_args: if arg in current_args: key = current_args.index(arg) del current_args[key:key+2] # Special: re-encapsulate --cli-args if self.options.cli_args: current_args.extend(['--cli-args', '"%s"' % self.options.cli_args]) if self.options.ignored_caveats: current_args.extend(['--ignore', '"%s"' % self.options.ignored_caveats]) if self.options.reg_exp: current_args.extend(['--re', '"%s"' % self.options.reg_exp]) # remove any specified positional arguments for arg in bad_args: if arg in current_args: current_args.remove(arg) self.__clean_args = current_args return self.__clean_args def getRunTestsCommand(self, job): """ return the command necessary to launch the TestHarness within the third party scheduler """ # Build ['/path/to/run_tests', '-j', '#'] command = [os.path.join(self.harness.run_tests_dir, 'run_tests'), '-j', str(job.getMetaData().get('QUEUEING_NCPUS', 1) )] # get current sys.args we are allowed to include when we launch run_tests args = list(self.cleanAndModifyArgs()) # Build [<args>, '--spec-file' ,/path/to/tests', '-o', '/path/to'] args.extend(['--spec-file', os.path.join(job.getTestDir(), self.options.input_file_name), '-o', job.getTestDir()]) # Build [<command>, <args>] command.extend(args) # Add the second results file we should remove when performing cleanup operations self.addDirtyFiles(job, [os.path.join(job.getTestDir(), self.__job_storage_file)]) return command def hasTimedOutOrFailed(self, job_data): """ return bool on exceeding walltime """ return False def _isProcessReady(self, job_data): """ Return bool on `run_tests --spec_file` submission results being available. Due to the way the TestHarness writes to this results file (when the TestHarness exits), this file, when available, means every test contained therein is finished in some form or another. If the result file does not exist, determine if it ever will exist. Tests which can fall into this group, are those which were: skipped, deleted, silent, etc during the initial launch phase. """ # No session file. Return immediately. if not job_data.json_data: return False is_ready = True # Job group exists in queue session and was apart of the queueing process if job_data.json_data and job_data.json_data.get(job_data.job_dir, {}).get('QUEUEING', {}): # result file exists (jobs are finished) if os.path.exists(os.path.join(job_data.job_dir, self.__job_storage_file)): pass # ask derived scheduler if this job has failed elif self.hasTimedOutOrFailed(job_data): for job in job_data.jobs.getJobs(): job.setStatus(job.error) is_ready = False # result does not yet exist but will in the future else: for job in job_data.jobs.getJobs(): tester = job.getTester() status, message, caveats = job.previousTesterStatus(self.options, job_data.json_data) tester.setStatus(status, message) if caveats: tester.addCaveats(caveats) status_message = tester.getStatusMessage() # This single job will enter the runner thread pool if status_message == "LAUNCHING": tester.setStatus(tester.queued) is_ready = False # Job group not originally launched else: for job in job_data.jobs.getJobs(): tester = job.getTester() status, message, caveats = job.previousTesterStatus(self.options, job_data.json_data) tester.setStatus(status, message) if caveats: tester.addCaveats(caveats) if tester.isNoStatus(): tester.setStatus(tester.silent) is_ready = False if not is_ready: for job in job_data.jobs.getJobs(): job.setStatus(job.finished) return is_ready def _isLaunchable(self, job_data): """ bool if jobs are ready to launch """ # results file exists (set during scheduler plugin initialization), so do no launch again if job_data.json_data: return False return True def _prepareJobs(self, job_data): """ Prepare jobs for launch. Grab an arbitrary job and record any necessary information the third party queueing systems requires for launch (walltime, ncpus, etc). Set all other jobs to a finished state. The arbitrary job selected will be the only job which enters the runner thread pool, and executes the commands neccessary for job submission. """ job_list = job_data.jobs.getJobs() # Clear any caveats set (except skips). As they do not apply during job submission for job in [x for x in job_list if not x.isSkip()]: job.clearCaveats() if job_list: launchable_jobs = [x for x in job_list if not x.isFinished()] if launchable_jobs: executor_job = job_list.pop(job_list.index(launchable_jobs.pop(0))) executor_job.addMetaData(QUEUEING=job_data.plugin, QUEUEING_NCPUS=self.getCores(job_data), QUEUEING_MAXTIME=self.getMaxTime(job_data)) executor_job.setStatus(executor_job.hold) for job in launchable_jobs: tester = job.getTester() tester.setStatus(tester.queued, 'LAUNCHING') job.setStatus(job.finished) def _setJobStatus(self, job_data): """ Read the json results file for the finished submitted job group, and match our job statuses with the results found therein. """ job_list = job_data.jobs.getJobs() if job_list: testdir_json = os.path.join(job_data.job_dir, self.__job_storage_file) with open(testdir_json, 'r') as f: try: results = json.load(f) except ValueError: print('Unable to parse json file: %s' % (testdir_json)) sys.exit(1) group_results = results[job_data.job_dir] # Continue to store previous third-party queueing data job_list[0].addMetaData(**{job_data.plugin : self.options.results_storage[job_data.job_dir][job_data.plugin]}) for job in job_list: job.setStatus(job.finished) tester = job.getTester() # Perhaps the user is filtering this job (--re, --failed-tests, etc) if tester.isSilent() and not tester.isDeleted(): continue if group_results.get(job.getTestName(), {}): job_results = group_results[job.getTestName()] status, message, caveats = job.previousTesterStatus(self.options, results) tester.setStatus(status, message) if caveats: tester.addCaveats(caveats) # Recover useful job information from job results job.setPreviousTime(job_results['TIMING']) job.setOutput(job_results['OUTPUT']) # This is a newly added test in the spec file, which was not a part of original launch else: tester.addCaveats('not originally launched') tester.setStatus(tester.skip) def _cleanupFiles(self, Jobs): """ Silence all Jobs and perform cleanup operations """ job_list = Jobs.getJobs() # Set each tester to be silent for job in job_list: tester = job.getTester() tester.setStatus(tester.silent) job.setStatus(job.finished) # Delete files generated by a job if job_list: for dirty_file in self.getDirtyFiles(job_list[0]): # Safty check. Any indigenous file generated by QueueManager should only exist in the tester directory if os.path.dirname(dirty_file) == job_list[0].getTestDir(): try: if os.path.isdir(dirty_file): shutil.rmtree(dirty_file) else: os.remove(dirty_file) except OSError: pass
nuclear-wizard/moose
python/TestHarness/schedulers/QueueManager.py
Python
lgpl-2.1
16,027
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements image pyramid functionalities. More details about image pyramids can be found on [this page.] (https://en.wikipedia.org/wiki/Pyramid_(image_processing)) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Callable, List, Optional, Tuple import numpy as np from six.moves import range import tensorflow as tf from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape from tensorflow_graphics.util import type_alias def _downsample(image: type_alias.TensorLike, kernel: type_alias.TensorLike) -> tf.Tensor: """Downsamples the image using a convolution with stride 2. Args: image: A tensor of shape `[B, H, W, C]`, where `B` is the batch size, `H` the height of the image, `W` the width of the image, and `C` the number of channels of the image. kernel: A tensor of shape `[H_k, W_k, C, C]`, where `H_k` and `W_k` are the height and width of the kernel. Returns: A tensor of shape `[B, H_d, W_d, C]`, where `H_d` and `W_d` are the height and width of the downsampled image. """ return tf.nn.conv2d( input=image, filters=kernel, strides=[1, 2, 2, 1], padding="SAME") def _binomial_kernel(num_channels: int, dtype: tf.DType = tf.float32) -> tf.Tensor: """Creates a 5x5 binomial kernel. Args: num_channels: The number of channels of the image to filter. dtype: The type of an element in the kernel. Returns: A tensor of shape `[5, 5, num_channels, num_channels]`. """ kernel = np.array((1., 4., 6., 4., 1.), dtype=dtype.as_numpy_dtype) kernel = np.outer(kernel, kernel) kernel /= np.sum(kernel) kernel = kernel[:, :, np.newaxis, np.newaxis] return tf.constant(kernel, dtype=dtype) * tf.eye(num_channels, dtype=dtype) def _build_pyramid(image: type_alias.TensorLike, sampler: Callable[ [type_alias.TensorLike, type_alias.TensorLike], type_alias.TensorLike], num_levels: int) -> List[tf.Tensor]: """Creates the different levels of the pyramid. Args: image: A tensor of shape `[B, H, W, C]`, where `B` is the batch size, `H` the height of the image, `W` the width of the image, and `C` the number of channels of the image. sampler: A function to execute for each level (_upsample or _downsample). num_levels: The number of levels. Returns: A list containing `num_levels` tensors of shape `[B, H_i, W_i, C]`, where `H_i` and `W_i` are the height and width of the image for the level i. """ kernel = _binomial_kernel(tf.shape(input=image)[3], dtype=image.dtype) levels = [image] for _ in range(num_levels): image = sampler(image, kernel) levels.append(image) return levels def _split(image: type_alias.TensorLike, kernel: type_alias.TensorLike) -> Tuple[tf.Tensor, tf.Tensor]: """Splits the image into high and low frequencies. This is achieved by smoothing the input image and substracting the smoothed version from the input. Args: image: A tensor of shape `[B, H, W, C]`, where `B` is the batch size, `H` the height of the image, `W` the width of the image, and `C` the number of channels of the image. kernel: A tensor of shape `[H_k, W_k, C, C]`, where `H_k` and `W_k` are the height and width of the kernel. Returns: A tuple of two tensors of shape `[B, H, W, C]` and `[B, H_d, W_d, C]`, where the first one contains the high frequencies of the image and the second one the low frequencies. `H_d` and `W_d` are the height and width of the downsampled low frequency image. """ low = _downsample(image, kernel) high = image - _upsample(low, kernel, tf.shape(input=image)) return high, low def _upsample(image: type_alias.TensorLike, kernel: type_alias.TensorLike, output_shape: Optional[type_alias.TensorLike] = None ) -> tf.Tensor: """Upsamples the image using a transposed convolution with stride 2. Args: image: A tensor of shape `[B, H, W, C]`, where `B` is the batch size, `H` the height of the image, `W` the width of the image, and `C` the number of channels of the image. kernel: A tensor of shape `[H_k, W_k, C, C]`, where `H_k` and `W_k` are the height and width of the kernel. output_shape: The output shape. Returns: A tensor of shape `[B, H_u, W_u, C]`, where `H_u` and `W_u` are the height and width of the upsampled image. """ if output_shape is None: output_shape = tf.shape(input=image) output_shape = (output_shape[0], output_shape[1] * 2, output_shape[2] * 2, output_shape[3]) return tf.nn.conv2d_transpose( image, kernel * 4.0, output_shape=output_shape, strides=[1, 2, 2, 1], padding="SAME") def downsample(image: type_alias.TensorLike, num_levels: int, name: str = "pyramid_downsample") -> List[tf.Tensor]: """Generates the different levels of the pyramid (downsampling). Args: image: A tensor of shape `[B, H, W, C]`, where `B` is the batch size, `H` the height of the image, `W` the width of the image, and `C` the number of channels of the image. num_levels: The number of levels to generate. name: A name for this op that defaults to "pyramid_downsample". Returns: A list containing `num_levels` tensors of shape `[B, H_i, W_i, C]`, where `H_i` and `W_i` are the height and width of the downsampled image for the level i. Raises: ValueError: If the shape of `image` is not supported. """ with tf.name_scope(name): image = tf.convert_to_tensor(value=image) shape.check_static(tensor=image, tensor_name="image", has_rank=4) return _build_pyramid(image, _downsample, num_levels) def merge(levels: List[type_alias.TensorLike], name: str = "pyramid_merge") -> tf.Tensor: """Merges the different levels of the pyramid back to an image. Args: levels: A list containing tensors of shape `[B, H_i, W_i, C]`, where `B` is the batch size, H_i and W_i are the height and width of the image for the level i, and `C` the number of channels of the image. name: A name for this op that defaults to "pyramid_merge". Returns: A tensor of shape `[B, H, W, C]`, where `B` is the batch size, `H` the height of the image, `W` the width of the image, and `C` the number of channels of the image. Raises: ValueError: If the shape of the elements of `levels` is not supported. """ with tf.name_scope(name): levels = [tf.convert_to_tensor(value=level) for level in levels] for index, level in enumerate(levels): shape.check_static( tensor=level, tensor_name="level {}".format(index), has_rank=4) image = levels[-1] kernel = _binomial_kernel(tf.shape(input=image)[3], dtype=image.dtype) for level in reversed(levels[:-1]): image = _upsample(image, kernel, tf.shape(input=level)) + level return image def split(image: type_alias.TensorLike, num_levels: int, name: str = "pyramid_split") -> List[tf.Tensor]: """Generates the different levels of the pyramid. Args: image: A tensor of shape `[B, H, W, C]`, where `B` is the batch size, `H` the height of the image, `W` the width of the image, and `C` the number of channels of the image. num_levels: The number of levels to generate. name: A name for this op that defaults to "pyramid_split". Returns: A list containing `num_levels` tensors of shape `[B, H_i, W_i, C]`, where `H_i` and `W_i` are the height and width of the image for the level i. Raises: ValueError: If the shape of `image` is not supported. """ with tf.name_scope(name): image = tf.convert_to_tensor(value=image) shape.check_static(tensor=image, tensor_name="image", has_rank=4) kernel = _binomial_kernel(tf.shape(input=image)[3], dtype=image.dtype) low = image levels = [] for _ in range(num_levels): high, low = _split(low, kernel) levels.append(high) levels.append(low) return levels def upsample(image: type_alias.TensorLike, num_levels: int, name: str = "pyramid_upsample") -> List[tf.Tensor]: """Generates the different levels of the pyramid (upsampling). Args: image: A tensor of shape `[B, H, W, C]`, where `B` is the batch size, `H` the height of the image, `W` the width of the image, and `C` the number of channels of the image. num_levels: The number of levels to generate. name: A name for this op that defaults to "pyramid_upsample". Returns: A list containing `num_levels` tensors of shape `[B, H_i, W_i, C]`, where `H_i` and `W_i` are the height and width of the upsampled image for the level i. Raises: ValueError: If the shape of `image` is not supported. """ with tf.name_scope(name): image = tf.convert_to_tensor(value=image) shape.check_static(tensor=image, tensor_name="image", has_rank=4) return _build_pyramid(image, _upsample, num_levels) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
tensorflow/graphics
tensorflow_graphics/image/pyramid.py
Python
apache-2.0
9,873
"""Compressed Sparse Row matrix format""" from __future__ import division, print_function, absolute_import __docformat__ = "restructuredtext en" __all__ = ['csr_matrix', 'isspmatrix_csr'] import numpy as np from scipy._lib.six import xrange from ._sparsetools import csr_tocsc, csr_tobsr, csr_count_blocks, \ get_csr_submatrix, csr_sample_values from .sputils import (upcast, isintlike, IndexMixin, issequence, get_index_dtype, ismatrix) from .compressed import _cs_matrix class csr_matrix(_cs_matrix, IndexMixin): """ Compressed Sparse Row matrix This can be instantiated in several ways: csr_matrix(D) with a dense matrix or rank-2 ndarray D csr_matrix(S) with another sparse matrix S (equivalent to S.tocsr()) csr_matrix((M, N), [dtype]) to construct an empty matrix with shape (M, N) dtype is optional, defaulting to dtype='d'. csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)]) where ``data``, ``row_ind`` and ``col_ind`` satisfy the relationship ``a[row_ind[k], col_ind[k]] = data[k]``. csr_matrix((data, indices, indptr), [shape=(M, N)]) is the standard CSR representation where the column indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``. If the shape parameter is not supplied, the matrix dimensions are inferred from the index arrays. Attributes ---------- dtype : dtype Data type of the matrix shape : 2-tuple Shape of the matrix ndim : int Number of dimensions (this is always 2) nnz Number of nonzero elements data CSR format data array of the matrix indices CSR format index array of the matrix indptr CSR format index pointer array of the matrix has_sorted_indices Whether indices are sorted Notes ----- Sparse matrices can be used in arithmetic operations: they support addition, subtraction, multiplication, division, and matrix power. Advantages of the CSR format - efficient arithmetic operations CSR + CSR, CSR * CSR, etc. - efficient row slicing - fast matrix vector products Disadvantages of the CSR format - slow column slicing operations (consider CSC) - changes to the sparsity structure are expensive (consider LIL or DOK) Examples -------- >>> import numpy as np >>> from scipy.sparse import csr_matrix >>> csr_matrix((3, 4), dtype=np.int8).toarray() array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], dtype=int8) >>> row = np.array([0, 0, 1, 2, 2, 2]) >>> col = np.array([0, 2, 2, 0, 1, 2]) >>> data = np.array([1, 2, 3, 4, 5, 6]) >>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray() array([[1, 0, 2], [0, 0, 3], [4, 5, 6]]) >>> indptr = np.array([0, 2, 3, 6]) >>> indices = np.array([0, 2, 2, 0, 1, 2]) >>> data = np.array([1, 2, 3, 4, 5, 6]) >>> csr_matrix((data, indices, indptr), shape=(3, 3)).toarray() array([[1, 0, 2], [0, 0, 3], [4, 5, 6]]) As an example of how to construct a CSR matrix incrementally, the following snippet builds a term-document matrix from texts: >>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]] >>> indptr = [0] >>> indices = [] >>> data = [] >>> vocabulary = {} >>> for d in docs: ... for term in d: ... index = vocabulary.setdefault(term, len(vocabulary)) ... indices.append(index) ... data.append(1) ... indptr.append(len(indices)) ... >>> csr_matrix((data, indices, indptr), dtype=int).toarray() array([[2, 1, 0, 0], [0, 1, 1, 1]]) """ def transpose(self, copy=False): from .csc import csc_matrix M,N = self.shape return csc_matrix((self.data,self.indices,self.indptr), shape=(N,M), copy=copy) def tolil(self): from .lil import lil_matrix lil = lil_matrix(self.shape,dtype=self.dtype) self.sort_indices() # lil_matrix needs sorted column indices ptr,ind,dat = self.indptr,self.indices,self.data rows, data = lil.rows, lil.data for n in xrange(self.shape[0]): start = ptr[n] end = ptr[n+1] rows[n] = ind[start:end].tolist() data[n] = dat[start:end].tolist() return lil def tocsr(self, copy=False): if copy: return self.copy() else: return self def tocsc(self): idx_dtype = get_index_dtype((self.indptr, self.indices), maxval=max(self.nnz, self.shape[0])) indptr = np.empty(self.shape[1] + 1, dtype=idx_dtype) indices = np.empty(self.nnz, dtype=idx_dtype) data = np.empty(self.nnz, dtype=upcast(self.dtype)) csr_tocsc(self.shape[0], self.shape[1], self.indptr.astype(idx_dtype), self.indices.astype(idx_dtype), self.data, indptr, indices, data) from .csc import csc_matrix A = csc_matrix((data, indices, indptr), shape=self.shape) A.has_sorted_indices = True return A def tobsr(self, blocksize=None, copy=True): from .bsr import bsr_matrix if blocksize is None: from .spfuncs import estimate_blocksize return self.tobsr(blocksize=estimate_blocksize(self)) elif blocksize == (1,1): arg1 = (self.data.reshape(-1,1,1),self.indices,self.indptr) return bsr_matrix(arg1, shape=self.shape, copy=copy) else: R,C = blocksize M,N = self.shape if R < 1 or C < 1 or M % R != 0 or N % C != 0: raise ValueError('invalid blocksize %s' % blocksize) blks = csr_count_blocks(M,N,R,C,self.indptr,self.indices) idx_dtype = get_index_dtype((self.indptr, self.indices), maxval=max(N//C, blks)) indptr = np.empty(M//R+1, dtype=idx_dtype) indices = np.empty(blks, dtype=idx_dtype) data = np.zeros((blks,R,C), dtype=self.dtype) csr_tobsr(M, N, R, C, self.indptr.astype(idx_dtype), self.indices.astype(idx_dtype), self.data, indptr, indices, data.ravel()) return bsr_matrix((data,indices,indptr), shape=self.shape) # these functions are used by the parent class (_cs_matrix) # to remove redudancy between csc_matrix and csr_matrix def _swap(self,x): """swap the members of x if this is a column-oriented matrix """ return (x[0],x[1]) def __getitem__(self, key): def asindices(x): try: x = np.asarray(x) # Check index contents, to avoid creating 64-bit arrays needlessly idx_dtype = get_index_dtype((x,), check_contents=True) if idx_dtype != x.dtype: x = x.astype(idx_dtype) except: raise IndexError('invalid index') else: return x def check_bounds(indices, N): if indices.size == 0: return (0, 0) max_indx = indices.max() if max_indx >= N: raise IndexError('index (%d) out of range' % max_indx) min_indx = indices.min() if min_indx < -N: raise IndexError('index (%d) out of range' % (N + min_indx)) return (min_indx,max_indx) def extractor(indices,N): """Return a sparse matrix P so that P*self implements slicing of the form self[[1,2,3],:] """ indices = asindices(indices) (min_indx,max_indx) = check_bounds(indices,N) if min_indx < 0: indices = indices.copy() indices[indices < 0] += N indptr = np.arange(len(indices)+1, dtype=indices.dtype) data = np.ones(len(indices), dtype=self.dtype) shape = (len(indices),N) return csr_matrix((data,indices,indptr), shape=shape) row, col = self._unpack_index(key) # First attempt to use original row optimized methods # [1, ?] if isintlike(row): # [i, j] if isintlike(col): return self._get_single_element(row, col) # [i, 1:2] elif isinstance(col, slice): return self._get_row_slice(row, col) # [i, [1, 2]] elif issequence(col): P = extractor(col,self.shape[1]).T return self[row, :] * P elif isinstance(row, slice): # [1:2,??] if ((isintlike(col) and row.step in (1, None)) or (isinstance(col, slice) and col.step in (1, None) and row.step in (1, None))): # col is int or slice with step 1, row is slice with step 1. return self._get_submatrix(row, col) elif issequence(col): # row is slice, col is sequence. P = extractor(col,self.shape[1]).T # [1:2,[1,2]] sliced = self if row != slice(None, None, None): sliced = sliced[row,:] return sliced * P elif issequence(row): # [[1,2],??] if isintlike(col) or isinstance(col,slice): P = extractor(row, self.shape[0]) # [[1,2],j] or [[1,2],1:2] extracted = P * self if col == slice(None, None, None): return extracted else: return extracted[:,col] elif ismatrix(row) and issequence(col): if len(row[0]) == 1 and isintlike(row[0][0]): # [[[1],[2]], [1,2]], outer indexing row = asindices(row) P_row = extractor(row[:,0], self.shape[0]) P_col = extractor(col, self.shape[1]).T return P_row * self * P_col if not (issequence(col) and issequence(row)): # Sample elementwise row, col = self._index_to_arrays(row, col) row = asindices(row) col = asindices(col) if row.shape != col.shape: raise IndexError('number of row and column indices differ') assert row.ndim <= 2 num_samples = np.size(row) if num_samples == 0: return csr_matrix(np.atleast_2d(row).shape, dtype=self.dtype) check_bounds(row, self.shape[0]) check_bounds(col, self.shape[1]) val = np.empty(num_samples, dtype=self.dtype) csr_sample_values(self.shape[0], self.shape[1], self.indptr, self.indices, self.data, num_samples, row.ravel(), col.ravel(), val) if row.ndim == 1: # row and col are 1d return np.asmatrix(val) return self.__class__(val.reshape(row.shape)) def getrow(self, i): """Returns a copy of row i of the matrix, as a (1 x n) CSR matrix (row vector). """ return self._get_submatrix(i, slice(None)) def getcol(self, i): """Returns a copy of column i of the matrix, as a (m x 1) CSR matrix (column vector). """ return self._get_submatrix(slice(None), i) def _get_row_slice(self, i, cslice): """Returns a copy of row self[i, cslice] """ if i < 0: i += self.shape[0] if i < 0 or i >= self.shape[0]: raise IndexError('index (%d) out of range' % i) start, stop, stride = cslice.indices(self.shape[1]) if stride == 1: # for stride == 1, _get_submatrix is ~30% faster than below row_slice = self._get_submatrix(i, cslice) else: # other strides need new code row_indices = self.indices[self.indptr[i]:self.indptr[i + 1]] row_data = self.data[self.indptr[i]:self.indptr[i + 1]] if stride > 0: ind = (row_indices >= start) & (row_indices < stop) elif stride < 0: ind = (row_indices <= start) & (row_indices > stop) if abs(stride) > 1: ind = ind & ((row_indices - start) % stride == 0) row_indices = (row_indices[ind] - start) // stride row_data = row_data[ind] row_indptr = np.array([0, len(row_indices)]) if stride < 0: row_data = row_data[::-1] row_indices = abs(row_indices[::-1]) shape = (1, int(np.ceil(float(stop - start) / stride))) row_slice = csr_matrix((row_data, row_indices, row_indptr), shape=shape) return row_slice def _get_submatrix(self, row_slice, col_slice): """Return a submatrix of this matrix (new matrix is created).""" M,N = self.shape def process_slice(sl, num): if isinstance(sl, slice): if sl.step not in (1, None): raise ValueError('slicing with step != 1 not supported') i0, i1 = sl.start, sl.stop if i0 is None: i0 = 0 elif i0 < 0: i0 = num + i0 if i1 is None: i1 = num elif i1 < 0: i1 = num + i1 return i0, i1 elif isintlike(sl): if sl < 0: sl += num return sl, sl + 1 else: raise TypeError('expected slice or scalar') def check_bounds(i0, i1, num): if not (0 <= i0 <= num) or not (0 <= i1 <= num) or not (i0 <= i1): raise IndexError( "index out of bounds: 0 <= %d <= %d, 0 <= %d <= %d," " %d <= %d" % (i0, num, i1, num, i0, i1)) i0, i1 = process_slice(row_slice, M) j0, j1 = process_slice(col_slice, N) check_bounds(i0, i1, M) check_bounds(j0, j1, N) indptr, indices, data = get_csr_submatrix(M, N, self.indptr, self.indices, self.data, int(i0), int(i1), int(j0), int(j1)) shape = (i1 - i0, j1 - j0) return self.__class__((data,indices,indptr), shape=shape) def isspmatrix_csr(x): return isinstance(x, csr_matrix)
jlcarmic/producthunt_simulator
venv/lib/python2.7/site-packages/scipy/sparse/csr.py
Python
mit
14,939
import decimal import logging from .adx import ADXTrader LOGGER = logging.getLogger(__name__) class PercentageTrader(ADXTrader): def __init__(self, percentage, *args, **kwargs): super().__init__(*args, **kwargs) self.percentage = percentage def __str__(self): return '{}{}<{}>'.format(self.__class__.__name__, self.percentage, str(self.feed)) def sell(self): for position in self.positions: profit = position.amount * self.feed.price profit -= profit * decimal.Decimal('0.025') if position.amount > 0 and profit > position.price * position.amount: if position.amount < decimal.Decimal('0.01'): LOGGER.info('{} Liquidating {:.8f} at {:.2f} bought at {:.2f}'.format( self, position.amount, self.feed.price, position.price)) self.liquidity += profit self.sells += 1 self.volume += position.amount position.amount = decimal.Decimal('0') else: profit = profit * self.percentage LOGGER.info('{} Selling {:.8f} at {:.2f} bought at {:.2f}'.format( self, position.amount, self.feed.price, position.price)) self.liquidity += profit position.amount *= decimal.Decimal('1') - self.percentage position.price = self.feed.price self.volume += position.amount self.sells += 1 self.summary() self.clean_positions()
CaptainBriot/prosperpy
prosperpy/traders/perc.py
Python
mit
1,630
# -*- coding: utf-8 -*- """ Author: Bernhard Scheirle """ from __future__ import unicode_literals import os from pelican.contents import Content from pelican.utils import slugify from . import avatars class Comment(Content): mandatory_properties = ('author', 'date') default_template = 'None' def __init__(self, content, metadata, settings, source_path, context): # Strip the path off the full filename. name = os.path.split(source_path)[1] if not hasattr(self, 'slug'): # compute the slug before initializing the base Content object, so # it doesn't get set there # This is required because we need a slug containing the file # extension. self.slug = slugify(name, settings.get('SLUG_SUBSTITUTIONS', ())) super(Comment, self).__init__(content, metadata, settings, source_path, context) self.replies = [] # Strip the extension from the filename. name = os.path.splitext(name)[0] self.avatar = avatars.getAvatarPath(name, metadata) self.title = "Posted by: {}".format(metadata['author']) def addReply(self, comment): self.replies.append(comment) def getReply(self, slug): for reply in self.replies: if reply.slug == slug: return reply else: deepReply = reply.getReply(slug) if deepReply is not None: return deepReply return None def __lt__(self, other): return self.metadata['date'] < other.metadata['date'] def sortReplies(self): for r in self.replies: r.sortReplies() self.replies = sorted(self.replies) def countReplies(self): amount = 0 for r in self.replies: amount += r.countReplies() return amount + len(self.replies)
tohuw/tohuwnet-pelican
plugins/pelican_comment_system/comment.py
Python
apache-2.0
1,929
from flask_security import current_user from flask_principal import Need, Permission, identity_loaded accept_suit_need = Need('accept_suit', True) accept_suit_permission = Permission(accept_suit_need) make_admin_need = Need('make_admin', True) make_admin_permission = Permission(make_admin_need) def grant_permissions(sender, identity): if hasattr(current_user, 'is_superadmin'): if current_user.is_superadmin: identity.provides.add(make_admin_need) if hasattr(current_user, 'can_accept_suits'): if current_user.can_accept_suits: identity.provides.add(accept_suit_need) def setup_permissions(state): identity_loaded.connect_via(state.app)(grant_permissions)
crossgovernmentservices/sue-my-brother
app/main/permissions.py
Python
mit
717
# coding: utf8 class BinaryTree(): def __init__(self, value): self.parent = self.left = self.right = None self.value = value def insertLeft(self, T): T.parent = self self.left = T def insertRight(self, T): T.parent = self self.right = T def deleteLeft(self): if self.left is None: self.left.deleteLeft() self.left.deleteRight() del self.lest self.left = None def deleteRight(self): if self.right is None: self.right.deleteLeft() self.right.deleteRight() del right right = None
eduSan/pyAsd
albero/BinaryTree.py
Python
gpl-3.0
663
#!/usr/bin/env python import argparse import logging import re import serial import time logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser(description="Test and calibrate the Re:load Pro") parser.add_argument('--baud', metavar='BAUD', type=int, help="Baud rate", default=115200) parser.add_argument('port', metavar='PORT', help="Serial port") parser.add_argument('--current', '-i', metavar='I', type=int, help="Calibration current in microamps") parser.add_argument('--voltage', '-v', metavar='V', type=int, help="Calibration voltage in microvolts") class QuitError(Exception): pass def expect(value, expectation): if value != expectation: logging.error("Expected %r, got %r", expectation, value) raise QuitError() def read_adcs(ser): ser.write("read\n") line = ser.readline() match = re.search("^read (-?\d+) (-?\d+)\r\n$", line) if not match: logging.error("Expected read response, got %r", line) raise QuitError() return map(int, match.groups()) def basic_test(args, ser): volts, amps = read_adcs(ser) if abs(volts) > 10000: logging.error("Offset voltage %d is greater than 10mV", volts) raise QuitError() if abs(amps) > 10000: logging.error("Offset current %d is greater than 10mA", amps) raise QuitError() logging.info("Communications okay") logging.info("Offsets okay") def calibrate_offset(args, ser): ser.write("set 0\n") expect(ser.readline(), "set 0\r\n") ser.write("cal o\n") expect(ser.readline(), "ok\r\n") logging.info("Calibrated offsets") def calibrate_voltage(args, ser): raw_input("Connect voltage source and press enter to continue.") volts, amps = read_adcs(ser) if args.voltage * 0.8 < volts < args.voltage * 1.2: logging.error("Initial voltage more than 20% out: %d", volts) raise QuitError() ser.write("cal v %d\n" % (args.voltage,)) expect(ser.readline(), "ok\r\n") logging.info("Calibrated voltage") def calibrate_current(args, ser): ser.write("set 6000\n") expect(ser.readline(), "set 6000\r\n") time.sleep(2.0) volts, amps = read_adcs(ser) if args.current * 0.8 < amps < args.current * 1.2: logging.error("Initial current more than 20% out: %d", amps) raise QuitError() ser.write("cal i %d\n" % (args.current,)) expect(ser.readline(), "ok\r\n") logging.info("Calibrated current") def calibrate_dacs(args, ser): ser.write("cal d %d\n" % (args.current * 0.8,)) expect(ser.readline(), "ok\r\n") time.sleep(2.0) logging.info("Calibrated DACs") def main(args): ser = serial.Serial(args.port, args.baud, timeout=1) basic_test(args, ser) calibrate_offset(args, ser) calibrate_voltage(args, ser) calibrate_current(args, ser) calibrate_dacs(args, ser) logging.info("Done!") if __name__ == '__main__': try: main(parser.parse_args()) except QuitError: pass
Ralim/reload-pro
tools/calibrate.py
Python
apache-2.0
2,793
############################################################################## # Parte do livro Introdução à Programação com Python # Autor: Nilo Ney Coutinho Menezes # Editora Novatec (c) 2010-2014 # Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8 # Primeira reimpressão - Outubro/2011 # Segunda reimpressão - Novembro/1012 # Terceira reimpressão - Agosto/2013 # Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3 # Site: http://python.nilo.pro.br/ # # Arquivo: exercicios_resolvidos\capitulo 05\exercicio-05-22.py ############################################################################## while True: print(""" Menu ---- 1 - Adição 2 - Subtração 3 - Divisão 4 - Multiplicação 5 - Sair """) opção =int(input("Escolha uma opção:")) if opção == 5: break elif opção >=1 and opção <5: n = int(input("Tabuada de:")) x = 1 while x<=10: if opção == 1: print("%d + %d = %d" % (n, x, n + x)) elif opção == 2: print("%d - %d = %d" % (n, x, n - x)) elif opção == 3: print("%d / %d = %5.4f" % (n, x, n / x)) elif opção == 4: print("%d x %d = %d" % (n, x, n * x)) x=x+1 else: print("Opção inválida!")
laenderoliveira/exerclivropy
exercicios_resolvidos/capitulo 05/exercicio-05-22.py
Python
mit
1,331
# Copyright 2012 10gen, 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. # This file will be used with PyPi in order to package and distribute the final # product. """ Module with code to setup cluster and test oplog_manager functions. This is the main tester method. All the functions can be called by finaltests.py """ import os import sys import inspect file = inspect.getfile(inspect.currentframe()) cmd_folder = os.path.realpath(os.path.abspath(os.path.split(file)[0])) cmd_folder = cmd_folder.rsplit("/", 1)[0] cmd_folder += "/mongo-connector" if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) import subprocess import time import json import unittest import re from doc_managers.doc_manager_simulator import DocManager from locking_dict import LockingDict from setup_cluster import killMongoProc, startMongoProc, start_cluster from optparse import OptionParser from pymongo import Connection from pymongo.errors import ConnectionFailure, OperationFailure from os import path from threading import Timer from oplog_manager import OplogThread from pysolr import Solr from util import (long_to_bson_ts, bson_ts_to_long, retry_until_ok) from bson.objectid import ObjectId """ Global path variables """ PORTS_ONE = {"PRIMARY": "27117", "SECONDARY": "27118", "ARBITER": "27119", "CONFIG": "27220", "MONGOS": "27217"} PORTS_TWO = {"PRIMARY": "27317", "SECONDARY": "27318", "ARBITER": "27319", "CONFIG": "27220", "MONGOS": "27217"} SETUP_DIR = path.expanduser("~/mongo-connector") DEMO_SERVER_DATA = SETUP_DIR + "/data" DEMO_SERVER_LOG = SETUP_DIR + "/logs" MONGOD_KSTR = " --dbpath " + DEMO_SERVER_DATA MONGOS_KSTR = "mongos --port " + PORTS_ONE["MONGOS"] AUTH_KEY = None AUTH_USERNAME = None def safe_mongo_op(func, arg1, arg2=None): """Performs the given operation with the safe argument """ count = 0 while True: time.sleep(1) count += 1 if (count > 60): string = 'Call to %s failed too many times' % func string += ' in safe_mongo_op' logging.error(string) sys.exit(1) try: if arg2: func(arg1, arg2, safe=True) else: func(arg1, safe=True) break except OperationFailure: pass class TestOplogManagerSharded(unittest.TestCase): """Defines all the testing methods for a sharded cluster """ def runTest(self): unittest.TestCase.__init__(self) def get_oplog_thread(self): """ Set up connection with mongo. Returns oplog, the connection and oplog collection. This function clears the oplog. """ primary_conn = Connection('localhost', int(PORTS_ONE["PRIMARY"])) if primary_conn['admin'].command("isMaster")['ismaster'] is False: primary_conn = Connection('localhost', int(PORTS_ONE["SECONDARY"])) mongos_addr = "localhost:" + PORTS_ONE["MONGOS"] mongos = Connection(mongos_addr) mongos['alpha']['foo'].drop() oplog_coll = primary_conn['local']['oplog.rs'] oplog_coll.drop() # reset the oplog primary_conn['local'].create_collection('oplog.rs', capped=True, size=1000000) namespace_set = ['test.test', 'alpha.foo'] doc_manager = DocManager() oplog = OplogThread(primary_conn, mongos_addr, oplog_coll, True, doc_manager, LockingDict(), namespace_set, AUTH_KEY, AUTH_USERNAME) return (oplog, primary_conn, oplog_coll, mongos) def get_new_oplog(self): """ Set up connection with mongo. Returns oplog, the connection and oplog collection This function does not clear the oplog """ primary_conn = Connection('localhost', int(PORTS_ONE["PRIMARY"])) if primary_conn['admin'].command("isMaster")['ismaster'] is False: primary_conn = Connection('localhost', int(PORTS_ONE["SECONDARY"])) mongos = "localhost:" + PORTS_ONE["MONGOS"] oplog_coll = primary_conn['local']['oplog.rs'] namespace_set = ['test.test', 'alpha.foo'] doc_manager = DocManager() oplog = OplogThread(primary_conn, mongos, oplog_coll, True, doc_manager, LockingDict(), namespace_set, AUTH_KEY, AUTH_USERNAME) return (oplog, primary_conn, oplog_coll, oplog.main_connection) def test_retrieve_doc(self): """Test retrieve_doc in oplog_manager. Assertion failure if it doesn't pass """ test_oplog, primary_conn, oplog_coll, mongos = self.get_oplog_thread() # testing for entry as none type entry = None assert (test_oplog.retrieve_doc(entry) is None) oplog_cursor = oplog_coll.find({}, tailable=True, await_data=True) assert (oplog_cursor.count() == 0) safe_mongo_op(mongos['alpha']['foo'].insert, {'name': 'paulie'}) last_oplog_entry = next(oplog_cursor) target_entry = mongos['alpha']['foo'].find_one() # testing for search after inserting a document assert (test_oplog.retrieve_doc(last_oplog_entry) == target_entry) safe_mongo_op(mongos['alpha']['foo'].update, {'name': 'paulie'}, {"$set": {'name': 'paul'}}) last_oplog_entry = next(oplog_cursor) target_entry = mongos['alpha']['foo'].find_one() # testing for search after updating a document assert (test_oplog.retrieve_doc(last_oplog_entry) == target_entry) safe_mongo_op(mongos['alpha']['foo'].remove, {'name': 'paul'}) last_oplog_entry = next(oplog_cursor) # testing for search after deleting a document assert (test_oplog.retrieve_doc(last_oplog_entry) is None) last_oplog_entry['o']['_id'] = 'badID' # testing for bad doc id as input assert (test_oplog.retrieve_doc(last_oplog_entry) is None) # test_oplog.stop() print("PASSED TEST RETRIEVE DOC") def test_get_oplog_cursor(self): """Test get_oplog_cursor in oplog_manager. Assertion failure if it doesn't pass """ test_oplog, primary_conn, oplog_coll, mongos = self.get_oplog_thread() # test None cursor assert (test_oplog.get_oplog_cursor(None) is None) # test with one document safe_mongo_op(mongos['alpha']['foo'].insert, {'name': 'paulie'}) ts = test_oplog.get_last_oplog_timestamp() cursor = test_oplog.get_oplog_cursor(ts) assert (cursor.count() == 1) # test with two documents, one after the ts safe_mongo_op(mongos['alpha']['foo'].insert, {'name': 'paul'}) cursor = test_oplog.get_oplog_cursor(ts) assert (cursor.count() == 2) print("PASSED TEST GET OPLOG CURSOR") def test_get_last_oplog_timestamp(self): """Test get_last_oplog_timestamp in oplog_manager. Assertion failure if it doesn't pass """ # test empty oplog test_oplog, primary_conn, oplog_coll, mongos = self.get_oplog_thread() assert (test_oplog.get_last_oplog_timestamp() is None) # test non-empty oplog oplog_cursor = oplog_coll.find({}, tailable=True, await_data=True) safe_mongo_op(mongos['alpha']['foo'].insert, {'name': 'paulie'}) last_oplog_entry = next(oplog_cursor) last_ts = last_oplog_entry['ts'] assert (test_oplog.get_last_oplog_timestamp() == last_ts) # test_oplog.stop() print("PASSED TEST GET OPLOG TIMESTAMP") def test_dump_collection(self): """Test dump_collection in oplog_manager. Assertion failure if it doesn't pass """ test_oplog, primary_conn, oplog_coll, mongos = self.get_oplog_thread() solr = DocManager() test_oplog.doc_manager = solr # with documents safe_mongo_op(mongos['alpha']['foo'].insert, {'name': 'paulie'}) search_ts = test_oplog.get_last_oplog_timestamp() test_oplog.dump_collection() test_oplog.doc_manager.commit() solr_results = solr._search() assert (len(solr_results) == 1) solr_doc = solr_results[0] assert (long_to_bson_ts(solr_doc['_ts']) == search_ts) assert (solr_doc['name'] == 'paulie') assert (solr_doc['ns'] == 'alpha.foo') print("PASSED TEST DUMP COLLECTION") def test_init_cursor(self): """Test init_cursor in oplog_manager. Assertion failure if it doesn't pass """ test_oplog, primary_conn, oplog_coll, mongos = self.get_oplog_thread() test_oplog.checkpoint = None # needed for these tests # initial tests with no config file and empty oplog assert (test_oplog.init_cursor() is None) # no config, single oplog entry safe_mongo_op(mongos['alpha']['foo'].insert, {'name': 'paulie'}) search_ts = test_oplog.get_last_oplog_timestamp() cursor = test_oplog.init_cursor() assert (cursor.count() == 1) assert (test_oplog.checkpoint == search_ts) # with config file, assert that size != 0 os.system('touch temp_config.txt') cursor = test_oplog.init_cursor() oplog_dict = test_oplog.oplog_progress.get_dict() assert(cursor.count() == 1) self.assertTrue(str(test_oplog.oplog) in oplog_dict) commit_ts = test_oplog.checkpoint self.assertTrue(oplog_dict[str(test_oplog.oplog)] == commit_ts) os.system('rm temp_config.txt') print("PASSED TEST INIT CURSOR") def test_rollback(self): """Test rollback in oplog_manager. Assertion failure if it doesn't pass We force a rollback by inserting a doc, killing primary, inserting another doc, killing the new primary, and then restarting both servers. """ os.system('rm config.txt; touch config.txt') start_cluster(sharded=True) test_oplog, primary_conn, oplog_coll, mongos = self.get_new_oplog() solr = DocManager() test_oplog.doc_manager = solr solr._delete() # equivalent to solr.delete(q='*:*') obj1 = ObjectId('4ff74db3f646462b38000001') safe_mongo_op(mongos['alpha']['foo'].remove, {}) safe_mongo_op(mongos['alpha']['foo'].insert, {'_id': obj1, 'name': 'paulie'}) cutoff_ts = test_oplog.get_last_oplog_timestamp() obj2 = ObjectId('4ff74db3f646462b38000002') first_doc = {'name': 'paulie', '_ts': bson_ts_to_long(cutoff_ts), 'ns': 'alpha.foo', '_id': obj1} # try kill one, try restarting killMongoProc(primary_conn.host, PORTS_ONE['PRIMARY']) new_primary_conn = Connection('localhost', int(PORTS_ONE['SECONDARY'])) admin_db = new_primary_conn['admin'] while admin_db.command("isMaster")['ismaster'] is False: time.sleep(1) time.sleep(5) count = 0 while True: try: mongos['alpha']['foo'].insert, {'_id': obj2, 'name': 'paul'} break except: time.sleep(1) count += 1 if count > 60: string = 'Insert failed too many times' string += ' in rollback' logging.error(string) sys.exit(1) continue killMongoProc(primary_conn.host, PORTS_ONE['SECONDARY']) startMongoProc(PORTS_ONE['PRIMARY'], "demo-repl", "/replset1a", "/replset1a.log", None) # wait for master to be established while primary_conn['admin'].command("isMaster")['ismaster'] is False: time.sleep(1) startMongoProc(PORTS_ONE['SECONDARY'], "demo-repl", "/replset1b", "/replset1b.log", None) # wait for secondary to be established admin_db = new_primary_conn['admin'] while admin_db.command("replSetGetStatus")['myState'] != 2: time.sleep(1) while retry_until_ok(mongos['alpha']['foo'].find().count) != 1: time.sleep(1) self.assertEqual(str(new_primary_conn.port), PORTS_ONE['SECONDARY']) self.assertEqual(str(primary_conn.port), PORTS_ONE['PRIMARY']) last_ts = test_oplog.get_last_oplog_timestamp() second_doc = {'name': 'paul', '_ts': bson_ts_to_long(last_ts), 'ns': 'alpha.foo', '_id': obj2} test_oplog.doc_manager.upsert(first_doc) test_oplog.doc_manager.upsert(second_doc) test_oplog.rollback() test_oplog.doc_manager.commit() results = solr._search() self.assertEqual(len(results), 1) results_doc = results[0] self.assertEqual(results_doc['name'], 'paulie') self.assertTrue(results_doc['_ts'] <= bson_ts_to_long(cutoff_ts)) print("PASSED TEST ROLLBACK") if __name__ == '__main__': os.system('rm config.txt; touch config.txt') parser = OptionParser() # -a is to specify the auth file. parser.add_option("-a", "--auth", action="store", type="string", dest="auth_file", default="") #-u is for the auth username parser.add_option("-u", "--username", action="store", type="string", dest="auth_user", default="__system") (options, args) = parser.parse_args() if options.auth_file != "": start_cluster(sharded=True, key_file=options.auth_file) try: file = open(options.auth_file) key = file.read() re.sub(r'\s', '', key) AUTH_KEY = key AUTH_USERNAME = options.auth_user except: # logger.error('Could not parse authentication file!') exit(1) else: start_cluster(sharded=True) conn = Connection('localhost:' + PORTS_ONE['MONGOS']) unittest.main(argv=[sys.argv[0]])
anuragkapur/mongo-connector
tests/test_oplog_manager_sharded.py
Python
apache-2.0
14,641
# Copyright 2014 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. import copy from tempest.lib.api_schema.response.compute.v2_1 import parameter_types create_server = { 'status_code': [202], 'response_body': { 'type': 'object', 'properties': { 'server': { 'type': 'object', 'properties': { 'id': {'type': 'string'}, 'security_groups': {'type': 'array'}, 'links': parameter_types.links, 'OS-DCF:diskConfig': {'type': 'string'} }, 'additionalProperties': False, # NOTE: OS-DCF:diskConfig & security_groups are API extension, # and some environments return a response without these # attributes.So they are not 'required'. 'required': ['id', 'links'] } }, 'additionalProperties': False, 'required': ['server'] } } create_server_with_admin_pass = copy.deepcopy(create_server) create_server_with_admin_pass['response_body']['properties']['server'][ 'properties'].update({'adminPass': {'type': 'string'}}) create_server_with_admin_pass['response_body']['properties']['server'][ 'required'].append('adminPass') list_servers = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'servers': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'id': {'type': 'string'}, 'links': parameter_types.links, 'name': {'type': 'string'} }, 'additionalProperties': False, 'required': ['id', 'links', 'name'] } }, 'servers_links': parameter_types.links }, 'additionalProperties': False, # NOTE(gmann): servers_links attribute is not necessary to be # present always So it is not 'required'. 'required': ['servers'] } } delete_server = { 'status_code': [204], } common_show_server = { 'type': 'object', 'properties': { 'id': {'type': 'string'}, 'name': {'type': 'string'}, 'status': {'type': 'string'}, 'image': {'oneOf': [ {'type': 'object', 'properties': { 'id': {'type': 'string'}, 'links': parameter_types.links }, 'additionalProperties': False, 'required': ['id', 'links']}, {'type': ['string', 'null']} ]}, 'flavor': { 'type': 'object', 'properties': { 'id': {'type': 'string'}, 'links': parameter_types.links }, # NOTE(gmann): This will be empty object if there is no # flavor info present in DB. This can happen when flavor info is # deleted after server creation. 'additionalProperties': False }, 'fault': { 'type': 'object', 'properties': { 'code': {'type': 'integer'}, 'created': {'type': 'string'}, 'message': {'type': 'string'}, 'details': {'type': 'string'}, }, 'additionalProperties': False, # NOTE(gmann): 'details' is not necessary to be present # in the 'fault'. So it is not defined as 'required'. 'required': ['code', 'created', 'message'] }, 'user_id': {'type': 'string'}, 'tenant_id': {'type': 'string'}, 'created': parameter_types.date_time, 'updated': parameter_types.date_time, 'progress': {'type': 'integer'}, 'metadata': {'type': 'object'}, 'links': parameter_types.links, 'addresses': parameter_types.addresses, 'hostId': {'type': 'string'}, 'OS-DCF:diskConfig': {'type': 'string'}, 'accessIPv4': parameter_types.access_ip_v4, 'accessIPv6': parameter_types.access_ip_v6 }, 'additionalProperties': False, # NOTE(GMann): 'progress' attribute is present in the response # only when server's status is one of the progress statuses # ("ACTIVE","BUILD", "REBUILD", "RESIZE","VERIFY_RESIZE") # 'fault' attribute is present in the response # only when server's status is one of the "ERROR", "DELETED". # OS-DCF:diskConfig and accessIPv4/v6 are API # extensions, and some environments return a response # without these attributes.So these are not defined as 'required'. 'required': ['id', 'name', 'status', 'image', 'flavor', 'user_id', 'tenant_id', 'created', 'updated', 'metadata', 'links', 'addresses', 'hostId'] } update_server = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'server': common_show_server }, 'additionalProperties': False, 'required': ['server'] } } server_detail = copy.deepcopy(common_show_server) server_detail['properties'].update({ 'key_name': {'type': ['string', 'null']}, 'security_groups': {'type': 'array'}, # NOTE: Non-admin users also can see "OS-SRV-USG" and "OS-EXT-AZ" # attributes. 'OS-SRV-USG:launched_at': {'type': ['string', 'null']}, 'OS-SRV-USG:terminated_at': {'type': ['string', 'null']}, 'OS-EXT-AZ:availability_zone': {'type': 'string'}, # NOTE: Admin users only can see "OS-EXT-STS" and "OS-EXT-SRV-ATTR" # attributes. 'OS-EXT-STS:task_state': {'type': ['string', 'null']}, 'OS-EXT-STS:vm_state': {'type': 'string'}, 'OS-EXT-STS:power_state': parameter_types.power_state, 'OS-EXT-SRV-ATTR:host': {'type': ['string', 'null']}, 'OS-EXT-SRV-ATTR:instance_name': {'type': 'string'}, 'OS-EXT-SRV-ATTR:hypervisor_hostname': {'type': ['string', 'null']}, 'os-extended-volumes:volumes_attached': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'id': {'type': 'string'} }, 'additionalProperties': False, }, }, 'config_drive': {'type': 'string'} }) server_detail['properties']['addresses']['patternProperties'][ '^[a-zA-Z0-9-_.]+$']['items']['properties'].update({ 'OS-EXT-IPS:type': {'type': 'string'}, 'OS-EXT-IPS-MAC:mac_addr': parameter_types.mac_address}) # NOTE(gmann): Update OS-EXT-IPS:type and OS-EXT-IPS-MAC:mac_addr # attributes in server address. Those are API extension, # and some environments return a response without # these attributes. So they are not 'required'. get_server = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'server': server_detail }, 'additionalProperties': False, 'required': ['server'] } } list_servers_detail = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'servers': { 'type': 'array', 'items': server_detail }, 'servers_links': parameter_types.links }, 'additionalProperties': False, # NOTE(gmann): servers_links attribute is not necessary to be # present always So it is not 'required'. 'required': ['servers'] } } rebuild_server = copy.deepcopy(update_server) rebuild_server['status_code'] = [202] rebuild_server_with_admin_pass = copy.deepcopy(rebuild_server) rebuild_server_with_admin_pass['response_body']['properties']['server'][ 'properties'].update({'adminPass': {'type': 'string'}}) rebuild_server_with_admin_pass['response_body']['properties']['server'][ 'required'].append('adminPass') rescue_server = { 'status_code': [200], 'response_body': { 'type': 'object', 'additionalProperties': False, } } rescue_server_with_admin_pass = copy.deepcopy(rescue_server) rescue_server_with_admin_pass['response_body'].update( {'properties': {'adminPass': {'type': 'string'}}}) rescue_server_with_admin_pass['response_body'].update( {'required': ['adminPass']}) list_virtual_interfaces = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'virtual_interfaces': { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'id': {'type': 'string'}, 'mac_address': parameter_types.mac_address, 'OS-EXT-VIF-NET:net_id': {'type': 'string'} }, 'additionalProperties': False, # 'OS-EXT-VIF-NET:net_id' is API extension So it is # not defined as 'required' 'required': ['id', 'mac_address'] } } }, 'additionalProperties': False, 'required': ['virtual_interfaces'] } } common_attach_volume_info = { 'type': 'object', 'properties': { 'id': {'type': 'string'}, 'device': {'type': ['string', 'null']}, 'volumeId': {'type': 'string'}, 'serverId': {'type': ['integer', 'string']} }, 'additionalProperties': False, # 'device' is optional in response. 'required': ['id', 'volumeId', 'serverId'] } attach_volume = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'volumeAttachment': common_attach_volume_info }, 'additionalProperties': False, 'required': ['volumeAttachment'] } } detach_volume = { 'status_code': [202] } show_volume_attachment = copy.deepcopy(attach_volume) show_volume_attachment['response_body']['properties'][ 'volumeAttachment']['properties'].update({'serverId': {'type': 'string'}}) list_volume_attachments = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'volumeAttachments': { 'type': 'array', 'items': common_attach_volume_info } }, 'additionalProperties': False, 'required': ['volumeAttachments'] } } list_volume_attachments['response_body']['properties'][ 'volumeAttachments']['items']['properties'].update( {'serverId': {'type': 'string'}}) list_addresses_by_network = { 'status_code': [200], 'response_body': parameter_types.addresses } list_addresses = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'addresses': parameter_types.addresses }, 'additionalProperties': False, 'required': ['addresses'] } } instance_actions = { 'type': 'object', 'properties': { 'action': {'type': 'string'}, 'request_id': {'type': 'string'}, 'user_id': {'type': 'string'}, 'project_id': {'type': 'string'}, 'start_time': parameter_types.date_time, 'message': {'type': ['string', 'null']}, 'instance_uuid': {'type': 'string'} }, 'additionalProperties': False, 'required': ['action', 'request_id', 'user_id', 'project_id', 'start_time', 'message', 'instance_uuid'] } instance_action_events = { 'type': 'array', 'items': { 'type': 'object', 'properties': { 'event': {'type': 'string'}, 'start_time': parameter_types.date_time, # The finish_time, result and optionally traceback are all # possibly None (null) until the event is actually finished. # The traceback would only be set if there was an error, but # when the event is complete both finish_time and result will # be set. 'finish_time': parameter_types.date_time_or_null, 'result': {'type': ['string', 'null']}, 'traceback': {'type': ['string', 'null']} }, 'additionalProperties': False, # NOTE(zhufl): events.traceback can only be seen by admin users # with default policy.json, so it shouldn't be a required field. 'required': ['event', 'start_time', 'finish_time', 'result'] } } list_instance_actions = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'instanceActions': { 'type': 'array', 'items': instance_actions } }, 'additionalProperties': False, 'required': ['instanceActions'] } } instance_actions_with_events = copy.deepcopy(instance_actions) instance_actions_with_events['properties'].update({ 'events': instance_action_events}) # 'events' does not come in response body always so it is not # defined as 'required' show_instance_action = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'instanceAction': instance_actions_with_events }, 'additionalProperties': False, 'required': ['instanceAction'] } } show_password = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'password': {'type': 'string'} }, 'additionalProperties': False, 'required': ['password'] } } get_vnc_console = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'console': { 'type': 'object', 'properties': { 'type': {'type': 'string'}, 'url': { 'type': 'string', 'format': 'uri' } }, 'additionalProperties': False, 'required': ['type', 'url'] } }, 'additionalProperties': False, 'required': ['console'] } } get_console_output = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'output': {'type': 'string'} }, 'additionalProperties': False, 'required': ['output'] } } set_server_metadata = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'metadata': { 'type': 'object', 'patternProperties': { '^.+$': {'type': 'string'} } } }, 'additionalProperties': False, 'required': ['metadata'] } } list_server_metadata = copy.deepcopy(set_server_metadata) update_server_metadata = copy.deepcopy(set_server_metadata) delete_server_metadata_item = { 'status_code': [204] } set_show_server_metadata_item = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'meta': { 'type': 'object', 'patternProperties': { '^.+$': {'type': 'string'} } } }, 'additionalProperties': False, 'required': ['meta'] } } server_actions_common_schema = { 'status_code': [202] } server_actions_delete_password = { 'status_code': [204] } server_actions_confirm_resize = copy.deepcopy( server_actions_delete_password) update_attached_volume = { 'status_code': [202] } evacuate_server = { 'status_code': [200] } evacuate_server_with_admin_pass = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'adminPass': {'type': 'string'} }, 'additionalProperties': False, 'required': ['adminPass'] } } show_server_diagnostics = { 'status_code': [200], 'response_body': { 'type': 'object' } }
cisco-openstack/tempest
tempest/lib/api_schema/response/compute/v2_1/servers.py
Python
apache-2.0
16,686
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from typing import Any, Union, cast from pandas.api.types import CategoricalDtype from pyspark.pandas.base import column_op, IndexOpsMixin from pyspark.pandas._typing import Dtype, IndexOpsLike, SeriesOrIndex from pyspark.pandas.data_type_ops.base import ( DataTypeOps, _as_categorical_type, _as_other_type, _as_string_type, _sanitize_list_like, ) from pyspark.pandas.spark import functions as SF from pyspark.pandas.typedef import pandas_on_spark_type from pyspark.sql import functions as F, Column from pyspark.sql.types import BinaryType, BooleanType, StringType class BinaryOps(DataTypeOps): """ The class for binary operations of pandas-on-Spark objects with BinaryType. """ @property def pretty_name(self) -> str: return "binaries" def add(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex: _sanitize_list_like(right) if isinstance(right, IndexOpsMixin) and isinstance(right.spark.data_type, BinaryType): return column_op(F.concat)(left, right) elif isinstance(right, bytes): return column_op(F.concat)(left, SF.lit(right)) else: raise TypeError( "Concatenation can not be applied to %s and the given type." % self.pretty_name ) def radd(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex: _sanitize_list_like(right) if isinstance(right, bytes): return cast( SeriesOrIndex, left._with_new_scol(F.concat(SF.lit(right), left.spark.column)) ) else: raise TypeError( "Concatenation can not be applied to %s and the given type." % self.pretty_name ) def lt(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex: from pyspark.pandas.base import column_op _sanitize_list_like(right) return column_op(Column.__lt__)(left, right) def le(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex: from pyspark.pandas.base import column_op _sanitize_list_like(right) return column_op(Column.__le__)(left, right) def ge(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex: from pyspark.pandas.base import column_op _sanitize_list_like(right) return column_op(Column.__ge__)(left, right) def gt(self, left: IndexOpsLike, right: Any) -> SeriesOrIndex: from pyspark.pandas.base import column_op _sanitize_list_like(right) return column_op(Column.__gt__)(left, right) def astype(self, index_ops: IndexOpsLike, dtype: Union[str, type, Dtype]) -> IndexOpsLike: dtype, spark_type = pandas_on_spark_type(dtype) if isinstance(dtype, CategoricalDtype): return _as_categorical_type(index_ops, dtype, spark_type) elif isinstance(spark_type, BooleanType): # Cannot cast binary to boolean in Spark. # We should cast binary to str first, and cast it to boolean return index_ops.astype(str).astype(bool) elif isinstance(spark_type, StringType): return _as_string_type(index_ops, dtype) else: return _as_other_type(index_ops, dtype, spark_type)
ueshin/apache-spark
python/pyspark/pandas/data_type_ops/binary_ops.py
Python
apache-2.0
4,022
# # Copyright Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://aws.amazon.com/apache2.0 # # or in the "license" file accompanying this file. This file 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. # """ Handshake tests using s2nc against Openssl s_server Openssl 1.1.0 removed SSLv3, 3DES, an RC4, so we won't have coverage there. """ import argparse import os import sys import subprocess import itertools import multiprocessing from multiprocessing.pool import ThreadPool from os import environ from s2n_test_constants import * from time import sleep PROTO_VERS_TO_S_SERVER_ARG = { S2N_TLS10: "-tls1", S2N_TLS11: "-tls1_1", S2N_TLS12: "-tls1_2", } use_corked_io=False def cleanup_processes(*processes): for p in processes: p.kill() p.wait() def validate_version(expected_version, line): return ACTUAL_VERSION_STR.format(expected_version or S2N_TLS12) in line def try_handshake(endpoint, port, cipher, ssl_version, server_cert=None, server_key=None, sig_algs=None, curves=None, dh_params=None, resume=False, no_ticket=False, fips_mode=False): """ Attempt to handshake against Openssl s_server listening on `endpoint` and `port` using s2nc :param int endpoint: endpoint for Openssl s_server to listen on :param int port: port for Openssl s_server to listen on :param str cipher: ciphers for Openssl s_server to use. See https://www.openssl.org/docs/man1.0.2/apps/ciphers.html :param int ssl_version: SSL version for Openssl s_server to use :param str server_cert: path to certificate for Openssl s_server to use :param str server_key: path to private key for Openssl s_server to use :param str sig_algs: Signature algorithms for Openssl s_server to accept :param str curves: Elliptic curves for Openssl s_server to accept :param str dh_params: path to DH params for Openssl s_server to use :param bool resume: if s2n client has to use reconnect option :param bool no_ticket: if s2n client has to not use session ticket :param fips_mode: if s2n client has to enable FIPS mode in the underlying crypto library :return: 0 on successfully negotiation(s), -1 on failure """ # Override certificate for ECDSA if unspecified. We can remove this when we # support multiple certificates if server_cert is None and cipher is not None and "ECDSA" in cipher: server_cert = TEST_ECDSA_CERT server_key = TEST_ECDSA_KEY if server_cert is None: server_cert = TEST_RSA_CERT server_key = TEST_RSA_KEY if dh_params is None: dh_params = TEST_DH_PARAMS # Start Openssl s_server s_server_cmd = ["openssl", "s_server", "-accept", str(port)] if ssl_version is not None: s_server_cmd.append(PROTO_VERS_TO_S_SERVER_ARG[ssl_version]) if server_cert is not None: s_server_cmd.extend(["-cert", server_cert]) if server_key is not None: s_server_cmd.extend(["-key", server_key]) if cipher is not None: s_server_cmd.extend(["-cipher", cipher]) if sig_algs is not None: s_server_cmd.extend(["-sigalgs", sig_algs]) if curves is not None: s_server_cmd.extend(["-curves", curves]) if dh_params is not None: s_server_cmd.extend(["-dhparam", dh_params]) # Fire up s_server s_server = subprocess.Popen(s_server_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8") # Make sure it's accepting found = 0 for line in s_server.stdout: if line.strip() == "ACCEPT": # Openssl first prints ACCEPT and only then actually binds the socket, so wait for a bit... sleep(0.1) found = 1 break if not found: sys.stderr.write("Failed to start s_server: {}\nSTDERR: {}\n".format(" ".join(s_server_cmd), s_server.stderr.read())) cleanup_processes(s_server) return -1 # Fire up s2nc s2nc_cmd = ["../../bin/s2nc", "-c", "test_all_tls12", "-i"] if resume: s2nc_cmd.append("-r") if no_ticket: s2nc_cmd.append("-T") if use_corked_io: s2nc_cmd.append("-C") if fips_mode: s2nc_cmd.append("--enter-fips-mode") s2nc_cmd.extend([str(endpoint), str(port)]) s2nc = subprocess.Popen(s2nc_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8") # Read from s2nc until we get successful connection message found = 0 seperators = 0 right_version = 0 if resume: for line in s2nc.stdout: if validate_version(ssl_version, line): right_version = 1 if line.startswith("Resumed session"): seperators += 1 if seperators == 5: found = 1 break else: for line in s2nc.stdout: if validate_version(ssl_version, line): right_version = 1 if line.strip() == "Connected to {}:{}".format(endpoint, port): found = 1 cleanup_processes(s2nc, s_server) if not found or not right_version: sys.stderr.write("= TEST FAILED =\ns_server cmd: {}\n s_server STDERR: {}\n\ns2nc cmd: {}\nSTDERR {}\n".format(" ".join(s_server_cmd), s_server.stderr.read(), " ".join(s2nc_cmd), s2nc.stderr.read())) return -1 return 0 def cert_path_to_str(cert_path): # Converts a path to a cert into a string usable for printing to test output # Example: "./test_certs/rsa_2048_sha256_client_cert.pem" => "RSA-2048-SHA256" return '-'.join(cert_path[cert_path.rfind('/')+1:].split('_')[:3]).upper() def print_result(result_prefix, return_code): suffix = "" if return_code == 0: if sys.stdout.isatty(): suffix = "\033[32;1mPASSED\033[0m" else: suffix = "PASSED" else: if sys.stdout.isatty(): suffix = "\033[31;1mFAILED\033[0m" else: suffix ="FAILED" print(result_prefix + suffix) def create_thread_pool(): threadpool_size = multiprocessing.cpu_count() * 2 #Multiply by 2 since performance improves slightly if CPU has hyperthreading print("\tCreating ThreadPool of size: " + str(threadpool_size)) threadpool = ThreadPool(processes=threadpool_size) return threadpool def run_handshake_test(host, port, ssl_version, cipher, fips_mode): cipher_name = cipher.openssl_name cipher_vers = cipher.min_tls_vers # Skip the cipher if openssl can't test it. 3DES/RC4 are disabled by default in 1.1.1 if not cipher.openssl_1_1_1_compatible: return 0 if ssl_version and ssl_version < cipher_vers: return 0 if fips_mode and not cipher.openssl_fips_compatible: return 0 ret = try_handshake(host, port, cipher_name, ssl_version, fips_mode=fips_mode) result_prefix = "Cipher: %-28s Vers: %-8s ... " % (cipher_name, S2N_PROTO_VERS_TO_STR[ssl_version]) print_result(result_prefix, ret) return ret def handshake_test(host, port, test_ciphers, fips_mode): """ Basic handshake tests using all valid combinations of supported cipher suites and TLS versions. """ print("\n\tRunning s2n Client handshake tests:") failed = 0 for ssl_version in [S2N_TLS10, S2N_TLS11, S2N_TLS12, None]: print("\n\tTesting ciphers using client version: " + S2N_PROTO_VERS_TO_STR[ssl_version]) threadpool = create_thread_pool() port_offset = 0 results = [] for cipher in test_ciphers: async_result = threadpool.apply_async(run_handshake_test, (host, port + port_offset, ssl_version, cipher, fips_mode)) port_offset += 1 results.append(async_result) threadpool.close() threadpool.join() for async_result in results: if async_result.get() != 0: failed = 1 return failed def handshake_resumption_test(host, port, no_ticket=False, fips_mode=False): """ Basic handshake tests for session resumption. """ if no_ticket: print("\n\tRunning s2n Client session resumption using session id tests:") else: print("\n\tRunning s2n Client session resumption using session ticket tests:") failed = 0 for ssl_version in [S2N_TLS10, S2N_TLS11, S2N_TLS12, None]: ret = try_handshake(host, port, None, ssl_version, resume=True, no_ticket=no_ticket, fips_mode=fips_mode) prefix = "Session Resumption for: %-40s ... " % (S2N_PROTO_VERS_TO_STR[ssl_version]) print_result(prefix, ret) if ret != 0: failed = 1 return failed supported_sigs = ["RSA+SHA1", "RSA+SHA224", "RSA+SHA256", "RSA+SHA384", "RSA+SHA512"] unsupported_sigs = ["ECDSA+SHA256", "ECDSA+SHA512"] def run_sigalg_test(host, port, cipher, ssl_version, permutation, fips_mode=False): # Put some unsupported algs in front to make sure we gracefully skip them mixed_sigs = unsupported_sigs + list(permutation) mixed_sigs_str = ':'.join(mixed_sigs) ret = try_handshake(host, port, cipher.openssl_name, ssl_version, sig_algs=mixed_sigs_str, fips_mode=fips_mode) # Trim the RSA part off for brevity. User should know we are only supported RSA at the moment. prefix = "Digests: %-35s Vers: %-8s... " % (':'.join([x[4:] for x in permutation]), S2N_PROTO_VERS_TO_STR[S2N_TLS12]) print_result(prefix, ret) return ret def sigalg_test(host, port, fips_mode=False): """ Acceptance test for supported signature algorithms. Tests all possible supported sigalgs with unsupported ones mixed in for noise. """ failed = 0 print("\n\tRunning s2n Client signature algorithm tests:") print("\tExpected supported: " + str(supported_sigs)) print("\tExpected unsupported: " + str(unsupported_sigs)) for size in range(1, min(MAX_ITERATION_DEPTH, len(supported_sigs)) + 1): print("\n\t\tTesting ciphers using signature preferences of size: " + str(size)) threadpool = create_thread_pool() portOffset = 0 results = [] # Produce permutations of every accepted signature algorithm in every possible order for permutation in itertools.permutations(supported_sigs, size): for cipher in ALL_TEST_CIPHERS: # Try an ECDHE cipher suite and a DHE one if cipher.openssl_name == "ECDHE-RSA-AES128-GCM-SHA256" or cipher.openssl_name == "DHE-RSA-AES128-GCM-SHA256": async_result = threadpool.apply_async(run_sigalg_test, (host, port + portOffset, cipher, None, permutation, fips_mode)) portOffset = portOffset + 1 results.append(async_result) threadpool.close() threadpool.join() for async_result in results: if async_result.get() != 0: failed = 1 return failed def elliptic_curve_test(host, port, libcrypto_version, fips_mode=False): """ Acceptance test for supported elliptic curves. Tests all possible supported curves with unsupported curves mixed in for noise. """ supported_curves = ["P-256", "P-384", "P-521"] unsupported_curves = ["B-163", "K-409"] print("\n\tRunning s2n Client elliptic curve tests:") print("\tExpected supported: " + str(supported_curves)) print("\tExpected unsupported: " + str(unsupported_curves)) failed = 0 for size in range(1, min(MAX_ITERATION_DEPTH, len(supported_curves)) + 1): print("\n\t\tTesting ciphers using curve list of size: " + str(size)) # Produce permutations of every accepted curve in every possible order for permutation in itertools.permutations(supported_curves, size): # Put some unsupported curves in front to make sure we gracefully skip them mixed_curves = unsupported_curves + list(permutation) mixed_curves_str = ':'.join(mixed_curves) for cipher in filter(lambda x: x.openssl_name == "ECDHE-RSA-AES128-GCM-SHA256" or x.openssl_name == "ECDHE-RSA-AES128-SHA", ALL_TEST_CIPHERS): ret = try_handshake(host, port, cipher.openssl_name, None, curves=mixed_curves_str, fips_mode=fips_mode) prefix = "Curves: %-40s Vers: %10s ... " % (':'.join(list(permutation)), S2N_PROTO_VERS_TO_STR[None]) print_result(prefix, ret) if ret != 0: failed = 1 return failed def main(): parser = argparse.ArgumentParser(description='Runs TLS server integration tests against Openssl s_server using s2nc') parser.add_argument('host', help='The host for s2nc to connect to') parser.add_argument('port', type=int, help='The port for s_server to bind to') parser.add_argument('--use_corked_io', action='store_true', help='Turn corked IO on/off') parser.add_argument('--libcrypto', default='openssl-1.1.1', choices=S2N_LIBCRYPTO_CHOICES, help="""The Libcrypto that s2n was built with. s2n supports different cipher suites depending on libcrypto version. Defaults to openssl-1.1.1.""") args = parser.parse_args() use_corked_io = args.use_corked_io # Retrieve the test ciphers to use based on the libcrypto version s2n was built with test_ciphers = S2N_LIBCRYPTO_TO_TEST_CIPHERS[args.libcrypto] host = args.host port = args.port libcrypto_version = args.libcrypto print("\nRunning s2n Client tests with: " + os.popen('openssl version').read()) if use_corked_io == True: print("Corked IO is on") fips_mode = False if environ.get("S2N_TEST_IN_FIPS_MODE") is not None: fips_mode = True print("\nRunning s2nd in FIPS mode.") failed = 0 failed += handshake_test(host, port, test_ciphers, fips_mode=fips_mode) failed += handshake_resumption_test(host, port, no_ticket=True, fips_mode=fips_mode) failed += handshake_resumption_test(host, port, fips_mode=fips_mode) failed += sigalg_test(host, port, fips_mode=fips_mode) failed += elliptic_curve_test(host, port, libcrypto_version, fips_mode=fips_mode) return failed if __name__ == "__main__": sys.exit(main())
wcs1only/s2n
tests/integration/s2n_handshake_test_s_server.py
Python
apache-2.0
14,531
from vsg import token from vsg.rules import move_token_left_to_next_non_whitespace_token as Rule oToken = token.generic_clause.semicolon class rule_021(Rule): ''' This rule checks the semicolon is not on it's own line. **Violation** .. code-block:: vhdl U_FIFO : FIFO generic ( G_WIDTH : integer ) ; **Fix** .. code-block:: vhdl U_FIFO : FIFO generic ( G_WIDTH : integer ); ''' def __init__(self): Rule.__init__(self, 'generic', '021', oToken) self.bInsertWhitespace = False
jeremiah-c-leary/vhdl-style-guide
vsg/rules/generic/rule_021.py
Python
gpl-3.0
616
from socket import * import threading def echo_server(address): sock = socket(AF_INET, SOCK_STREAM) sock.bind(address) sock.listen(1) while True: client, addr = sock.accept() print('Connection from', addr) t = threading.Thread(target=echo_handler, args=(client,)) t.start() def echo_handler(client): while True: data = client.recv(100000) if not data: break client.sendall(b'Got:' + data) print('Connection closed') client.close() if __name__ == '__main__': echo_server(('', 25000))
jcontesti/python-programming-language-livelessons-projects
15/echoserv.py
Python
gpl-3.0
615
# Copyright (c) 2017 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """ Meteogram ========= Plots time series data as a meteogram. """ import datetime as dt import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from metpy.calc import dewpoint_rh from metpy.cbook import get_test_data from metpy.plots import add_metpy_logo from metpy.units import units def calc_mslp(t, p, h): return p * (1 - (0.0065 * h) / (t + 0.0065 * h + 273.15)) ** (-5.257) # Make meteogram plot class Meteogram(object): """ Plot a time series of meteorological data from a particular station as a meteogram with standard variables to visualize, including thermodynamic, kinematic, and pressure. The functions below control the plotting of each variable. TO DO: Make the subplot creation dynamic so the number of rows is not static as it is currently. """ def __init__(self, fig, dates, probeid, time=None, axis=0): """ Required input: fig: figure object dates: array of dates corresponding to the data probeid: ID of the station Optional Input: time: Time the data is to be plotted axis: number that controls the new axis to be plotted (FOR FUTURE) """ if not time: time = dt.datetime.utcnow() self.start = dates[0] self.fig = fig self.end = dates[-1] self.axis_num = 0 self.dates = mpl.dates.date2num(dates) self.time = time.strftime('%Y-%m-%d %H:%M UTC') self.title = 'Latest Ob Time: {0}\nProbe ID: {1}'.format(self.time, probeid) def plot_winds(self, ws, wd, wsmax, plot_range=None): """ Required input: ws: Wind speeds (knots) wd: Wind direction (degrees) wsmax: Wind gust (knots) Optional Input: plot_range: Data range for making figure (list of (min,max,step)) """ # PLOT WIND SPEED AND WIND DIRECTION self.ax1 = fig.add_subplot(4, 1, 1) ln1 = self.ax1.plot(self.dates, ws, label='Wind Speed') plt.fill_between(self.dates, ws, 0) self.ax1.set_xlim(self.start, self.end) if not plot_range: plot_range = [0, 20, 1] plt.ylabel('Wind Speed (knots)', multialignment='center') self.ax1.set_ylim(plot_range[0], plot_range[1], plot_range[2]) plt.grid(b=True, which='major', axis='y', color='k', linestyle='--', linewidth=0.5) ln2 = self.ax1.plot(self.dates, wsmax, '.r', label='3-sec Wind Speed Max') plt.setp(self.ax1.get_xticklabels(), visible=True) ax7 = self.ax1.twinx() ln3 = ax7.plot(self.dates, wd, '.k', linewidth=0.5, label='Wind Direction') plt.ylabel('Wind\nDirection\n(degrees)', multialignment='center') plt.ylim(0, 360) plt.yticks(np.arange(45, 405, 90), ['NE', 'SE', 'SW', 'NW']) lns = ln1 + ln2 + ln3 labs = [l.get_label() for l in lns] plt.gca().xaxis.set_major_formatter(mpl.dates.DateFormatter('%d/%H UTC')) ax7.legend(lns, labs, loc='upper center', bbox_to_anchor=(0.5, 1.2), ncol=3, prop={'size': 12}) def plot_thermo(self, t, td, plot_range=None): """ Required input: T: Temperature (deg F) TD: Dewpoint (deg F) Optional Input: plot_range: Data range for making figure (list of (min,max,step)) """ # PLOT TEMPERATURE AND DEWPOINT if not plot_range: plot_range = [10, 90, 2] self.ax2 = fig.add_subplot(4, 1, 2, sharex=self.ax1) ln4 = self.ax2.plot(self.dates, t, 'r-', label='Temperature') plt.fill_between(self.dates, t, td, color='r') plt.setp(self.ax2.get_xticklabels(), visible=True) plt.ylabel('Temperature\n(F)', multialignment='center') plt.grid(b=True, which='major', axis='y', color='k', linestyle='--', linewidth=0.5) self.ax2.set_ylim(plot_range[0], plot_range[1], plot_range[2]) ln5 = self.ax2.plot(self.dates, td, 'g-', label='Dewpoint') plt.fill_between(self.dates, td, plt.ylim()[0], color='g') ax_twin = self.ax2.twinx() # ax_twin.set_ylim(20,90,2) ax_twin.set_ylim(plot_range[0], plot_range[1], plot_range[2]) lns = ln4 + ln5 labs = [l.get_label() for l in lns] plt.gca().xaxis.set_major_formatter(mpl.dates.DateFormatter('%d/%H UTC')) self.ax2.legend(lns, labs, loc='upper center', bbox_to_anchor=(0.5, 1.2), ncol=2, prop={'size': 12}) def plot_rh(self, rh, plot_range=None): """ Required input: RH: Relative humidity (%) Optional Input: plot_range: Data range for making figure (list of (min,max,step)) """ # PLOT RELATIVE HUMIDITY if not plot_range: plot_range = [0, 100, 4] self.ax3 = fig.add_subplot(4, 1, 3, sharex=self.ax1) self.ax3.plot(self.dates, rh, 'g-', label='Relative Humidity') self.ax3.legend(loc='upper center', bbox_to_anchor=(0.5, 1.22), prop={'size': 12}) plt.setp(self.ax3.get_xticklabels(), visible=True) plt.grid(b=True, which='major', axis='y', color='k', linestyle='--', linewidth=0.5) self.ax3.set_ylim(plot_range[0], plot_range[1], plot_range[2]) plt.fill_between(self.dates, rh, plt.ylim()[0], color='g') plt.ylabel('Relative Humidity\n(%)', multialignment='center') plt.gca().xaxis.set_major_formatter(mpl.dates.DateFormatter('%d/%H UTC')) axtwin = self.ax3.twinx() axtwin.set_ylim(plot_range[0], plot_range[1], plot_range[2]) def plot_pressure(self, p, plot_range=None): """ Required input: P: Mean Sea Level Pressure (hPa) Optional Input: plot_range: Data range for making figure (list of (min,max,step)) """ # PLOT PRESSURE if not plot_range: plot_range = [970, 1030, 2] self.ax4 = fig.add_subplot(4, 1, 4, sharex=self.ax1) self.ax4.plot(self.dates, p, 'm', label='Mean Sea Level Pressure') plt.ylabel('Mean Sea\nLevel Pressure\n(mb)', multialignment='center') plt.ylim(plot_range[0], plot_range[1], plot_range[2]) axtwin = self.ax4.twinx() axtwin.set_ylim(plot_range[0], plot_range[1], plot_range[2]) plt.fill_between(self.dates, p, plt.ylim()[0], color='m') plt.gca().xaxis.set_major_formatter(mpl.dates.DateFormatter('%d/%H UTC')) self.ax4.legend(loc='upper center', bbox_to_anchor=(0.5, 1.2), prop={'size': 12}) plt.grid(b=True, which='major', axis='y', color='k', linestyle='--', linewidth=0.5) plt.setp(self.ax4.get_xticklabels(), visible=True) # OTHER OPTIONAL AXES TO PLOT # plot_irradiance # plot_precipitation # set the starttime and endtime for plotting, 24 hour range endtime = dt.datetime(2016, 3, 31, 22, 0, 0, 0) starttime = endtime - dt.timedelta(hours=24) # Height of the station to calculate MSLP hgt_example = 292. # Parse dates from .csv file, knowing their format as a string and convert to datetime def parse_date(date): return dt.datetime.strptime(date.decode('ascii'), '%Y-%m-%d %H:%M:%S') testdata = np.genfromtxt(get_test_data('timeseries.csv', False), names=True, dtype=None, usecols=list(range(1, 8)), converters={'DATE': parse_date}, delimiter=',') # Temporary variables for ease temp = testdata['T'] pres = testdata['P'] rh = testdata['RH'] ws = testdata['WS'] wsmax = testdata['WSMAX'] wd = testdata['WD'] date = testdata['DATE'] # ID For Plotting on Meteogram probe_id = '0102A' data = {'wind_speed': (np.array(ws) * units('m/s')).to(units('knots')), 'wind_speed_max': (np.array(wsmax) * units('m/s')).to(units('knots')), 'wind_direction': np.array(wd) * units('degrees'), 'dewpoint': dewpoint_rh((np.array(temp) * units('degC')).to(units('K')), np.array(rh) / 100.).to(units('degF')), 'air_temperature': (np.array(temp) * units('degC')).to(units('degF')), 'mean_slp': calc_mslp(np.array(temp), np.array(pres), hgt_example) * units('hPa'), 'relative_humidity': np.array(rh), 'times': np.array(date)} fig = plt.figure(figsize=(20, 16)) add_metpy_logo(fig, 250, 180) meteogram = Meteogram(fig, data['times'], probe_id) meteogram.plot_winds(data['wind_speed'], data['wind_direction'], data['wind_speed_max']) meteogram.plot_thermo(data['air_temperature'], data['dewpoint']) meteogram.plot_rh(data['relative_humidity']) meteogram.plot_pressure(data['mean_slp']) fig.subplots_adjust(hspace=0.5) plt.show()
metpy/MetPy
v0.7/_downloads/meteogram_metpy.py
Python
bsd-3-clause
9,460
#===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===# # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # #===------------------------------------------------------------------------===# r""" Clang Indexing Library Bindings =============================== This module provides an interface to the Clang indexing library. It is a low-level interface to the indexing library which attempts to match the Clang API directly while also being "pythonic". Notable differences from the C API are: * string results are returned as Python strings, not CXString objects. * null cursors are translated to None. * access to child cursors is done via iteration, not visitation. The major indexing objects are: Index The top-level object which manages some global library state. TranslationUnit High-level object encapsulating the AST for a single translation unit. These can be loaded from .ast files or parsed on the fly. Cursor Generic object for representing a node in the AST. SourceRange, SourceLocation, and File Objects representing information about the input source. Most object information is exposed using properties, when the underlying API call is efficient. """ from __future__ import absolute_import, division, print_function # TODO # ==== # # o API support for invalid translation units. Currently we can't even get the # diagnostics on failure because they refer to locations in an object that # will have been invalidated. # # o fix memory management issues (currently client must hold on to index and # translation unit, or risk crashes). # # o expose code completion APIs. # # o cleanup ctypes wrapping, would be nice to separate the ctypes details more # clearly, and hide from the external interface (i.e., help(cindex)). # # o implement additional SourceLocation, SourceRange, and File methods. from ctypes import * import collections import clang.enumerations import os import sys if sys.version_info[0] == 3: # Python 3 strings are unicode, translate them to/from utf8 for C-interop. class c_interop_string(c_char_p): def __init__(self, p=None): if p is None: p = "" if isinstance(p, str): p = p.encode("utf8") super(c_char_p, self).__init__(p) def __str__(self): return self.value @property def value(self): if super(c_char_p, self).value is None: return None return super(c_char_p, self).value.decode("utf8") @classmethod def from_param(cls, param): if isinstance(param, str): return cls(param) if isinstance(param, bytes): return cls(param) if param is None: # Support passing null to C functions expecting char arrays return None raise TypeError("Cannot convert '{}' to '{}'".format(type(param).__name__, cls.__name__)) @staticmethod def to_python_string(x, *args): return x.value def b(x): if isinstance(x, bytes): return x return x.encode('utf8') elif sys.version_info[0] == 2: # Python 2 strings are utf8 byte strings, no translation is needed for # C-interop. c_interop_string = c_char_p def _to_python_string(x, *args): return x c_interop_string.to_python_string = staticmethod(_to_python_string) def b(x): return x # We only support PathLike objects on Python version with os.fspath present # to be consistent with the Python standard library. On older Python versions # we only support strings and we have dummy fspath to just pass them through. try: fspath = os.fspath except AttributeError: def fspath(x): return x # ctypes doesn't implicitly convert c_void_p to the appropriate wrapper # object. This is a problem, because it means that from_parameter will see an # integer and pass the wrong value on platforms where int != void*. Work around # this by marshalling object arguments as void**. c_object_p = POINTER(c_void_p) callbacks = {} ### Exception Classes ### class TranslationUnitLoadError(Exception): """Represents an error that occurred when loading a TranslationUnit. This is raised in the case where a TranslationUnit could not be instantiated due to failure in the libclang library. FIXME: Make libclang expose additional error information in this scenario. """ pass class TranslationUnitSaveError(Exception): """Represents an error that occurred when saving a TranslationUnit. Each error has associated with it an enumerated value, accessible under e.save_error. Consumers can compare the value with one of the ERROR_ constants in this class. """ # Indicates that an unknown error occurred. This typically indicates that # I/O failed during save. ERROR_UNKNOWN = 1 # Indicates that errors during translation prevented saving. The errors # should be available via the TranslationUnit's diagnostics. ERROR_TRANSLATION_ERRORS = 2 # Indicates that the translation unit was somehow invalid. ERROR_INVALID_TU = 3 def __init__(self, enumeration, message): assert isinstance(enumeration, int) if enumeration < 1 or enumeration > 3: raise Exception("Encountered undefined TranslationUnit save error " "constant: %d. Please file a bug to have this " "value supported." % enumeration) self.save_error = enumeration Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) ### Structures and Utility Classes ### class CachedProperty(object): """Decorator that lazy-loads the value of a property. The first time the property is accessed, the original property function is executed. The value it returns is set as the new value of that instance's property, replacing the original method. """ def __init__(self, wrapped): self.wrapped = wrapped try: self.__doc__ = wrapped.__doc__ except: pass def __get__(self, instance, instance_type=None): if instance is None: return self value = self.wrapped(instance) setattr(instance, self.wrapped.__name__, value) return value class _CXString(Structure): """Helper for transforming CXString results.""" _fields_ = [("spelling", c_char_p), ("free", c_int)] def __del__(self): conf.lib.clang_disposeString(self) @staticmethod def from_result(res, fn=None, args=None): assert isinstance(res, _CXString) return conf.lib.clang_getCString(res) class SourceLocation(Structure): """ A SourceLocation represents a particular location within a source file. """ _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)] _data = None def _get_instantiation(self): if self._data is None: f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint() conf.lib.clang_getInstantiationLocation(self, byref(f), byref(l), byref(c), byref(o)) if f: f = File(f) else: f = None self._data = (f, int(l.value), int(c.value), int(o.value)) return self._data @staticmethod def from_position(tu, file, line, column): """ Retrieve the source location associated with a given file/line/column in a particular translation unit. """ return conf.lib.clang_getLocation(tu, file, line, column) @staticmethod def from_offset(tu, file, offset): """Retrieve a SourceLocation from a given character offset. tu -- TranslationUnit file belongs to file -- File instance to obtain offset from offset -- Integer character offset within file """ return conf.lib.clang_getLocationForOffset(tu, file, offset) @property def file(self): """Get the file represented by this source location.""" return self._get_instantiation()[0] @property def line(self): """Get the line represented by this source location.""" return self._get_instantiation()[1] @property def column(self): """Get the column represented by this source location.""" return self._get_instantiation()[2] @property def offset(self): """Get the file offset represented by this source location.""" return self._get_instantiation()[3] def __eq__(self, other): return conf.lib.clang_equalLocations(self, other) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): if self.file: filename = self.file.name else: filename = None return "<SourceLocation file %r, line %r, column %r>" % ( filename, self.line, self.column) class SourceRange(Structure): """ A SourceRange describes a range of source locations within the source code. """ _fields_ = [ ("ptr_data", c_void_p * 2), ("begin_int_data", c_uint), ("end_int_data", c_uint)] # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes # object. @staticmethod def from_locations(start, end): return conf.lib.clang_getRange(start, end) @property def start(self): """ Return a SourceLocation representing the first character within a source range. """ return conf.lib.clang_getRangeStart(self) @property def end(self): """ Return a SourceLocation representing the last character within a source range. """ return conf.lib.clang_getRangeEnd(self) def __eq__(self, other): return conf.lib.clang_equalRanges(self, other) def __ne__(self, other): return not self.__eq__(other) def __contains__(self, other): """Useful to detect the Token/Lexer bug""" if not isinstance(other, SourceLocation): return False if other.file is None and self.start.file is None: pass elif ( self.start.file.name != other.file.name or other.file.name != self.end.file.name): # same file name return False # same file, in between lines if self.start.line < other.line < self.end.line: return True elif self.start.line == other.line: # same file first line if self.start.column <= other.column: return True elif other.line == self.end.line: # same file last line if other.column <= self.end.column: return True return False def __repr__(self): return "<SourceRange start %r, end %r>" % (self.start, self.end) class Diagnostic(object): """ A Diagnostic is a single instance of a Clang diagnostic. It includes the diagnostic severity, the message, the location the diagnostic occurred, as well as additional source ranges and associated fix-it hints. """ Ignored = 0 Note = 1 Warning = 2 Error = 3 Fatal = 4 DisplaySourceLocation = 0x01 DisplayColumn = 0x02 DisplaySourceRanges = 0x04 DisplayOption = 0x08 DisplayCategoryId = 0x10 DisplayCategoryName = 0x20 _FormatOptionsMask = 0x3f def __init__(self, ptr): self.ptr = ptr def __del__(self): conf.lib.clang_disposeDiagnostic(self) @property def severity(self): return conf.lib.clang_getDiagnosticSeverity(self) @property def location(self): return conf.lib.clang_getDiagnosticLocation(self) @property def spelling(self): return conf.lib.clang_getDiagnosticSpelling(self) @property def ranges(self): class RangeIterator(object): def __init__(self, diag): self.diag = diag def __len__(self): return int(conf.lib.clang_getDiagnosticNumRanges(self.diag)) def __getitem__(self, key): if (key >= len(self)): raise IndexError return conf.lib.clang_getDiagnosticRange(self.diag, key) return RangeIterator(self) @property def fixits(self): class FixItIterator(object): def __init__(self, diag): self.diag = diag def __len__(self): return int(conf.lib.clang_getDiagnosticNumFixIts(self.diag)) def __getitem__(self, key): range = SourceRange() value = conf.lib.clang_getDiagnosticFixIt(self.diag, key, byref(range)) if len(value) == 0: raise IndexError return FixIt(range, value) return FixItIterator(self) @property def children(self): class ChildDiagnosticsIterator(object): def __init__(self, diag): self.diag_set = conf.lib.clang_getChildDiagnostics(diag) def __len__(self): return int(conf.lib.clang_getNumDiagnosticsInSet(self.diag_set)) def __getitem__(self, key): diag = conf.lib.clang_getDiagnosticInSet(self.diag_set, key) if not diag: raise IndexError return Diagnostic(diag) return ChildDiagnosticsIterator(self) @property def category_number(self): """The category number for this diagnostic or 0 if unavailable.""" return conf.lib.clang_getDiagnosticCategory(self) @property def category_name(self): """The string name of the category for this diagnostic.""" return conf.lib.clang_getDiagnosticCategoryText(self) @property def option(self): """The command-line option that enables this diagnostic.""" return conf.lib.clang_getDiagnosticOption(self, None) @property def disable_option(self): """The command-line option that disables this diagnostic.""" disable = _CXString() conf.lib.clang_getDiagnosticOption(self, byref(disable)) return _CXString.from_result(disable) def format(self, options=None): """ Format this diagnostic for display. The options argument takes Diagnostic.Display* flags, which can be combined using bitwise OR. If the options argument is not provided, the default display options will be used. """ if options is None: options = conf.lib.clang_defaultDiagnosticDisplayOptions() if options & ~Diagnostic._FormatOptionsMask: raise ValueError('Invalid format options') return conf.lib.clang_formatDiagnostic(self, options) def __repr__(self): return "<Diagnostic severity %r, location %r, spelling %r>" % ( self.severity, self.location, self.spelling) def __str__(self): return self.format() def from_param(self): return self.ptr class FixIt(object): """ A FixIt represents a transformation to be applied to the source to "fix-it". The fix-it shouldbe applied by replacing the given source range with the given value. """ def __init__(self, range, value): self.range = range self.value = value def __repr__(self): return "<FixIt range %r, value %r>" % (self.range, self.value) class TokenGroup(object): """Helper class to facilitate token management. Tokens are allocated from libclang in chunks. They must be disposed of as a collective group. One purpose of this class is for instances to represent groups of allocated tokens. Each token in a group contains a reference back to an instance of this class. When all tokens from a group are garbage collected, it allows this class to be garbage collected. When this class is garbage collected, it calls the libclang destructor which invalidates all tokens in the group. You should not instantiate this class outside of this module. """ def __init__(self, tu, memory, count): self._tu = tu self._memory = memory self._count = count def __del__(self): conf.lib.clang_disposeTokens(self._tu, self._memory, self._count) @staticmethod def get_tokens(tu, extent): """Helper method to return all tokens in an extent. This functionality is needed multiple places in this module. We define it here because it seems like a logical place. """ tokens_memory = POINTER(Token)() tokens_count = c_uint() conf.lib.clang_tokenize(tu, extent, byref(tokens_memory), byref(tokens_count)) count = int(tokens_count.value) # If we get no tokens, no memory was allocated. Be sure not to return # anything and potentially call a destructor on nothing. if count < 1: return tokens_array = cast(tokens_memory, POINTER(Token * count)).contents token_group = TokenGroup(tu, tokens_memory, tokens_count) for i in range(0, count): token = Token() token.int_data = tokens_array[i].int_data token.ptr_data = tokens_array[i].ptr_data token._tu = tu token._group = token_group yield token class TokenKind(object): """Describes a specific type of a Token.""" _value_map = {} # int -> TokenKind def __init__(self, value, name): """Create a new TokenKind instance from a numeric value and a name.""" self.value = value self.name = name def __repr__(self): return 'TokenKind.%s' % (self.name,) @staticmethod def from_value(value): """Obtain a registered TokenKind instance from its value.""" result = TokenKind._value_map.get(value, None) if result is None: raise ValueError('Unknown TokenKind: %d' % value) return result @staticmethod def register(value, name): """Register a new TokenKind enumeration. This should only be called at module load time by code within this package. """ if value in TokenKind._value_map: raise ValueError('TokenKind already registered: %d' % value) kind = TokenKind(value, name) TokenKind._value_map[value] = kind setattr(TokenKind, name, kind) ### Cursor Kinds ### class BaseEnumeration(object): """ Common base class for named enumerations held in sync with Index.h values. Subclasses must define their own _kinds and _name_map members, as: _kinds = [] _name_map = None These values hold the per-subclass instances and value-to-name mappings, respectively. """ def __init__(self, value): if value >= len(self.__class__._kinds): self.__class__._kinds += [None] * (value - len(self.__class__._kinds) + 1) if self.__class__._kinds[value] is not None: raise ValueError('{0} value {1} already loaded'.format( str(self.__class__), value)) self.value = value self.__class__._kinds[value] = self self.__class__._name_map = None def from_param(self): return self.value @property def name(self): """Get the enumeration name of this cursor kind.""" if self._name_map is None: self._name_map = {} for key, value in self.__class__.__dict__.items(): if isinstance(value, self.__class__): self._name_map[value] = key return self._name_map[self] @classmethod def from_id(cls, id): if id >= len(cls._kinds) or cls._kinds[id] is None: raise ValueError('Unknown template argument kind %d' % id) return cls._kinds[id] def __repr__(self): return '%s.%s' % (self.__class__, self.name,) class CursorKind(BaseEnumeration): """ A CursorKind describes the kind of entity that a cursor points to. """ # The required BaseEnumeration declarations. _kinds = [] _name_map = None @staticmethod def get_all_kinds(): """Return all CursorKind enumeration instances.""" return [x for x in CursorKind._kinds if not x is None] def is_declaration(self): """Test if this is a declaration kind.""" return conf.lib.clang_isDeclaration(self) def is_reference(self): """Test if this is a reference kind.""" return conf.lib.clang_isReference(self) def is_expression(self): """Test if this is an expression kind.""" return conf.lib.clang_isExpression(self) def is_statement(self): """Test if this is a statement kind.""" return conf.lib.clang_isStatement(self) def is_attribute(self): """Test if this is an attribute kind.""" return conf.lib.clang_isAttribute(self) def is_invalid(self): """Test if this is an invalid kind.""" return conf.lib.clang_isInvalid(self) def is_translation_unit(self): """Test if this is a translation unit kind.""" return conf.lib.clang_isTranslationUnit(self) def is_preprocessing(self): """Test if this is a preprocessing kind.""" return conf.lib.clang_isPreprocessing(self) def is_unexposed(self): """Test if this is an unexposed kind.""" return conf.lib.clang_isUnexposed(self) def __repr__(self): return 'CursorKind.%s' % (self.name,) ### # Declaration Kinds # A declaration whose specific kind is not exposed via this interface. # # Unexposed declarations have the same operations as any other kind of # declaration; one can extract their location information, spelling, find their # definitions, etc. However, the specific kind of the declaration is not # reported. CursorKind.UNEXPOSED_DECL = CursorKind(1) # A C or C++ struct. CursorKind.STRUCT_DECL = CursorKind(2) # A C or C++ union. CursorKind.UNION_DECL = CursorKind(3) # A C++ class. CursorKind.CLASS_DECL = CursorKind(4) # An enumeration. CursorKind.ENUM_DECL = CursorKind(5) # A field (in C) or non-static data member (in C++) in a struct, union, or C++ # class. CursorKind.FIELD_DECL = CursorKind(6) # An enumerator constant. CursorKind.ENUM_CONSTANT_DECL = CursorKind(7) # A function. CursorKind.FUNCTION_DECL = CursorKind(8) # A variable. CursorKind.VAR_DECL = CursorKind(9) # A function or method parameter. CursorKind.PARM_DECL = CursorKind(10) # An Objective-C @interface. CursorKind.OBJC_INTERFACE_DECL = CursorKind(11) # An Objective-C @interface for a category. CursorKind.OBJC_CATEGORY_DECL = CursorKind(12) # An Objective-C @protocol declaration. CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13) # An Objective-C @property declaration. CursorKind.OBJC_PROPERTY_DECL = CursorKind(14) # An Objective-C instance variable. CursorKind.OBJC_IVAR_DECL = CursorKind(15) # An Objective-C instance method. CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16) # An Objective-C class method. CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17) # An Objective-C @implementation. CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18) # An Objective-C @implementation for a category. CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19) # A typedef. CursorKind.TYPEDEF_DECL = CursorKind(20) # A C++ class method. CursorKind.CXX_METHOD = CursorKind(21) # A C++ namespace. CursorKind.NAMESPACE = CursorKind(22) # A linkage specification, e.g. 'extern "C"'. CursorKind.LINKAGE_SPEC = CursorKind(23) # A C++ constructor. CursorKind.CONSTRUCTOR = CursorKind(24) # A C++ destructor. CursorKind.DESTRUCTOR = CursorKind(25) # A C++ conversion function. CursorKind.CONVERSION_FUNCTION = CursorKind(26) # A C++ template type parameter CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27) # A C++ non-type template parameter. CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28) # A C++ template template parameter. CursorKind.TEMPLATE_TEMPLATE_PARAMETER = CursorKind(29) # A C++ function template. CursorKind.FUNCTION_TEMPLATE = CursorKind(30) # A C++ class template. CursorKind.CLASS_TEMPLATE = CursorKind(31) # A C++ class template partial specialization. CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32) # A C++ namespace alias declaration. CursorKind.NAMESPACE_ALIAS = CursorKind(33) # A C++ using directive CursorKind.USING_DIRECTIVE = CursorKind(34) # A C++ using declaration CursorKind.USING_DECLARATION = CursorKind(35) # A Type alias decl. CursorKind.TYPE_ALIAS_DECL = CursorKind(36) # A Objective-C synthesize decl CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37) # A Objective-C dynamic decl CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38) # A C++ access specifier decl. CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39) ### # Reference Kinds CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40) CursorKind.OBJC_PROTOCOL_REF = CursorKind(41) CursorKind.OBJC_CLASS_REF = CursorKind(42) # A reference to a type declaration. # # A type reference occurs anywhere where a type is named but not # declared. For example, given: # typedef unsigned size_type; # size_type size; # # The typedef is a declaration of size_type (CXCursor_TypedefDecl), # while the type of the variable "size" is referenced. The cursor # referenced by the type of size is the typedef for size_type. CursorKind.TYPE_REF = CursorKind(43) CursorKind.CXX_BASE_SPECIFIER = CursorKind(44) # A reference to a class template, function template, template # template parameter, or class template partial specialization. CursorKind.TEMPLATE_REF = CursorKind(45) # A reference to a namespace or namepsace alias. CursorKind.NAMESPACE_REF = CursorKind(46) # A reference to a member of a struct, union, or class that occurs in # some non-expression context, e.g., a designated initializer. CursorKind.MEMBER_REF = CursorKind(47) # A reference to a labeled statement. CursorKind.LABEL_REF = CursorKind(48) # A reference to a set of overloaded functions or function templates # that has not yet been resolved to a specific function or function template. CursorKind.OVERLOADED_DECL_REF = CursorKind(49) # A reference to a variable that occurs in some non-expression # context, e.g., a C++ lambda capture list. CursorKind.VARIABLE_REF = CursorKind(50) ### # Invalid/Error Kinds CursorKind.INVALID_FILE = CursorKind(70) CursorKind.NO_DECL_FOUND = CursorKind(71) CursorKind.NOT_IMPLEMENTED = CursorKind(72) CursorKind.INVALID_CODE = CursorKind(73) ### # Expression Kinds # An expression whose specific kind is not exposed via this interface. # # Unexposed expressions have the same operations as any other kind of # expression; one can extract their location information, spelling, children, # etc. However, the specific kind of the expression is not reported. CursorKind.UNEXPOSED_EXPR = CursorKind(100) # An expression that refers to some value declaration, such as a function, # variable, or enumerator. CursorKind.DECL_REF_EXPR = CursorKind(101) # An expression that refers to a member of a struct, union, class, Objective-C # class, etc. CursorKind.MEMBER_REF_EXPR = CursorKind(102) # An expression that calls a function. CursorKind.CALL_EXPR = CursorKind(103) # An expression that sends a message to an Objective-C object or class. CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104) # An expression that represents a block literal. CursorKind.BLOCK_EXPR = CursorKind(105) # An integer literal. CursorKind.INTEGER_LITERAL = CursorKind(106) # A floating point number literal. CursorKind.FLOATING_LITERAL = CursorKind(107) # An imaginary number literal. CursorKind.IMAGINARY_LITERAL = CursorKind(108) # A string literal. CursorKind.STRING_LITERAL = CursorKind(109) # A character literal. CursorKind.CHARACTER_LITERAL = CursorKind(110) # A parenthesized expression, e.g. "(1)". # # This AST node is only formed if full location information is requested. CursorKind.PAREN_EXPR = CursorKind(111) # This represents the unary-expression's (except sizeof and # alignof). CursorKind.UNARY_OPERATOR = CursorKind(112) # [C99 6.5.2.1] Array Subscripting. CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113) # A builtin binary operation expression such as "x + y" or # "x <= y". CursorKind.BINARY_OPERATOR = CursorKind(114) # Compound assignment such as "+=". CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115) # The ?: ternary operator. CursorKind.CONDITIONAL_OPERATOR = CursorKind(116) # An explicit cast in C (C99 6.5.4) or a C-style cast in C++ # (C++ [expr.cast]), which uses the syntax (Type)expr. # # For example: (int)f. CursorKind.CSTYLE_CAST_EXPR = CursorKind(117) # [C99 6.5.2.5] CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118) # Describes an C or C++ initializer list. CursorKind.INIT_LIST_EXPR = CursorKind(119) # The GNU address of label extension, representing &&label. CursorKind.ADDR_LABEL_EXPR = CursorKind(120) # This is the GNU Statement Expression extension: ({int X=4; X;}) CursorKind.StmtExpr = CursorKind(121) # Represents a C11 generic selection. CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122) # Implements the GNU __null extension, which is a name for a null # pointer constant that has integral type (e.g., int or long) and is the same # size and alignment as a pointer. # # The __null extension is typically only used by system headers, which define # NULL as __null in C++ rather than using 0 (which is an integer that may not # match the size of a pointer). CursorKind.GNU_NULL_EXPR = CursorKind(123) # C++'s static_cast<> expression. CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124) # C++'s dynamic_cast<> expression. CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125) # C++'s reinterpret_cast<> expression. CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126) # C++'s const_cast<> expression. CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127) # Represents an explicit C++ type conversion that uses "functional" # notion (C++ [expr.type.conv]). # # Example: # \code # x = int(0.5); # \endcode CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128) # A C++ typeid expression (C++ [expr.typeid]). CursorKind.CXX_TYPEID_EXPR = CursorKind(129) # [C++ 2.13.5] C++ Boolean Literal. CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130) # [C++0x 2.14.7] C++ Pointer Literal. CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131) # Represents the "this" expression in C++ CursorKind.CXX_THIS_EXPR = CursorKind(132) # [C++ 15] C++ Throw Expression. # # This handles 'throw' and 'throw' assignment-expression. When # assignment-expression isn't present, Op will be null. CursorKind.CXX_THROW_EXPR = CursorKind(133) # A new expression for memory allocation and constructor calls, e.g: # "new CXXNewExpr(foo)". CursorKind.CXX_NEW_EXPR = CursorKind(134) # A delete expression for memory deallocation and destructor calls, # e.g. "delete[] pArray". CursorKind.CXX_DELETE_EXPR = CursorKind(135) # Represents a unary expression. CursorKind.CXX_UNARY_EXPR = CursorKind(136) # ObjCStringLiteral, used for Objective-C string literals i.e. "foo". CursorKind.OBJC_STRING_LITERAL = CursorKind(137) # ObjCEncodeExpr, used for in Objective-C. CursorKind.OBJC_ENCODE_EXPR = CursorKind(138) # ObjCSelectorExpr used for in Objective-C. CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139) # Objective-C's protocol expression. CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140) # An Objective-C "bridged" cast expression, which casts between # Objective-C pointers and C pointers, transferring ownership in the process. # # \code # NSString *str = (__bridge_transfer NSString *)CFCreateString(); # \endcode CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141) # Represents a C++0x pack expansion that produces a sequence of # expressions. # # A pack expansion expression contains a pattern (which itself is an # expression) followed by an ellipsis. For example: CursorKind.PACK_EXPANSION_EXPR = CursorKind(142) # Represents an expression that computes the length of a parameter # pack. CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143) # Represents a C++ lambda expression that produces a local function # object. # # \code # void abssort(float *x, unsigned N) { # std::sort(x, x + N, # [](float a, float b) { # return std::abs(a) < std::abs(b); # }); # } # \endcode CursorKind.LAMBDA_EXPR = CursorKind(144) # Objective-c Boolean Literal. CursorKind.OBJ_BOOL_LITERAL_EXPR = CursorKind(145) # Represents the "self" expression in a ObjC method. CursorKind.OBJ_SELF_EXPR = CursorKind(146) # OpenMP 4.0 [2.4, Array Section]. CursorKind.OMP_ARRAY_SECTION_EXPR = CursorKind(147) # Represents an @available(...) check. CursorKind.OBJC_AVAILABILITY_CHECK_EXPR = CursorKind(148) # A statement whose specific kind is not exposed via this interface. # # Unexposed statements have the same operations as any other kind of statement; # one can extract their location information, spelling, children, etc. However, # the specific kind of the statement is not reported. CursorKind.UNEXPOSED_STMT = CursorKind(200) # A labelled statement in a function. CursorKind.LABEL_STMT = CursorKind(201) # A compound statement CursorKind.COMPOUND_STMT = CursorKind(202) # A case statement. CursorKind.CASE_STMT = CursorKind(203) # A default statement. CursorKind.DEFAULT_STMT = CursorKind(204) # An if statement. CursorKind.IF_STMT = CursorKind(205) # A switch statement. CursorKind.SWITCH_STMT = CursorKind(206) # A while statement. CursorKind.WHILE_STMT = CursorKind(207) # A do statement. CursorKind.DO_STMT = CursorKind(208) # A for statement. CursorKind.FOR_STMT = CursorKind(209) # A goto statement. CursorKind.GOTO_STMT = CursorKind(210) # An indirect goto statement. CursorKind.INDIRECT_GOTO_STMT = CursorKind(211) # A continue statement. CursorKind.CONTINUE_STMT = CursorKind(212) # A break statement. CursorKind.BREAK_STMT = CursorKind(213) # A return statement. CursorKind.RETURN_STMT = CursorKind(214) # A GNU-style inline assembler statement. CursorKind.ASM_STMT = CursorKind(215) # Objective-C's overall @try-@catch-@finally statement. CursorKind.OBJC_AT_TRY_STMT = CursorKind(216) # Objective-C's @catch statement. CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217) # Objective-C's @finally statement. CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218) # Objective-C's @throw statement. CursorKind.OBJC_AT_THROW_STMT = CursorKind(219) # Objective-C's @synchronized statement. CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220) # Objective-C's autorealease pool statement. CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221) # Objective-C's for collection statement. CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222) # C++'s catch statement. CursorKind.CXX_CATCH_STMT = CursorKind(223) # C++'s try statement. CursorKind.CXX_TRY_STMT = CursorKind(224) # C++'s for (* : *) statement. CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225) # Windows Structured Exception Handling's try statement. CursorKind.SEH_TRY_STMT = CursorKind(226) # Windows Structured Exception Handling's except statement. CursorKind.SEH_EXCEPT_STMT = CursorKind(227) # Windows Structured Exception Handling's finally statement. CursorKind.SEH_FINALLY_STMT = CursorKind(228) # A MS inline assembly statement extension. CursorKind.MS_ASM_STMT = CursorKind(229) # The null statement. CursorKind.NULL_STMT = CursorKind(230) # Adaptor class for mixing declarations with statements and expressions. CursorKind.DECL_STMT = CursorKind(231) # OpenMP parallel directive. CursorKind.OMP_PARALLEL_DIRECTIVE = CursorKind(232) # OpenMP SIMD directive. CursorKind.OMP_SIMD_DIRECTIVE = CursorKind(233) # OpenMP for directive. CursorKind.OMP_FOR_DIRECTIVE = CursorKind(234) # OpenMP sections directive. CursorKind.OMP_SECTIONS_DIRECTIVE = CursorKind(235) # OpenMP section directive. CursorKind.OMP_SECTION_DIRECTIVE = CursorKind(236) # OpenMP single directive. CursorKind.OMP_SINGLE_DIRECTIVE = CursorKind(237) # OpenMP parallel for directive. CursorKind.OMP_PARALLEL_FOR_DIRECTIVE = CursorKind(238) # OpenMP parallel sections directive. CursorKind.OMP_PARALLEL_SECTIONS_DIRECTIVE = CursorKind(239) # OpenMP task directive. CursorKind.OMP_TASK_DIRECTIVE = CursorKind(240) # OpenMP master directive. CursorKind.OMP_MASTER_DIRECTIVE = CursorKind(241) # OpenMP critical directive. CursorKind.OMP_CRITICAL_DIRECTIVE = CursorKind(242) # OpenMP taskyield directive. CursorKind.OMP_TASKYIELD_DIRECTIVE = CursorKind(243) # OpenMP barrier directive. CursorKind.OMP_BARRIER_DIRECTIVE = CursorKind(244) # OpenMP taskwait directive. CursorKind.OMP_TASKWAIT_DIRECTIVE = CursorKind(245) # OpenMP flush directive. CursorKind.OMP_FLUSH_DIRECTIVE = CursorKind(246) # Windows Structured Exception Handling's leave statement. CursorKind.SEH_LEAVE_STMT = CursorKind(247) # OpenMP ordered directive. CursorKind.OMP_ORDERED_DIRECTIVE = CursorKind(248) # OpenMP atomic directive. CursorKind.OMP_ATOMIC_DIRECTIVE = CursorKind(249) # OpenMP for SIMD directive. CursorKind.OMP_FOR_SIMD_DIRECTIVE = CursorKind(250) # OpenMP parallel for SIMD directive. CursorKind.OMP_PARALLELFORSIMD_DIRECTIVE = CursorKind(251) # OpenMP target directive. CursorKind.OMP_TARGET_DIRECTIVE = CursorKind(252) # OpenMP teams directive. CursorKind.OMP_TEAMS_DIRECTIVE = CursorKind(253) # OpenMP taskgroup directive. CursorKind.OMP_TASKGROUP_DIRECTIVE = CursorKind(254) # OpenMP cancellation point directive. CursorKind.OMP_CANCELLATION_POINT_DIRECTIVE = CursorKind(255) # OpenMP cancel directive. CursorKind.OMP_CANCEL_DIRECTIVE = CursorKind(256) # OpenMP target data directive. CursorKind.OMP_TARGET_DATA_DIRECTIVE = CursorKind(257) # OpenMP taskloop directive. CursorKind.OMP_TASK_LOOP_DIRECTIVE = CursorKind(258) # OpenMP taskloop simd directive. CursorKind.OMP_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(259) # OpenMP distribute directive. CursorKind.OMP_DISTRIBUTE_DIRECTIVE = CursorKind(260) # OpenMP target enter data directive. CursorKind.OMP_TARGET_ENTER_DATA_DIRECTIVE = CursorKind(261) # OpenMP target exit data directive. CursorKind.OMP_TARGET_EXIT_DATA_DIRECTIVE = CursorKind(262) # OpenMP target parallel directive. CursorKind.OMP_TARGET_PARALLEL_DIRECTIVE = CursorKind(263) # OpenMP target parallel for directive. CursorKind.OMP_TARGET_PARALLELFOR_DIRECTIVE = CursorKind(264) # OpenMP target update directive. CursorKind.OMP_TARGET_UPDATE_DIRECTIVE = CursorKind(265) # OpenMP distribute parallel for directive. CursorKind.OMP_DISTRIBUTE_PARALLELFOR_DIRECTIVE = CursorKind(266) # OpenMP distribute parallel for simd directive. CursorKind.OMP_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(267) # OpenMP distribute simd directive. CursorKind.OMP_DISTRIBUTE_SIMD_DIRECTIVE = CursorKind(268) # OpenMP target parallel for simd directive. CursorKind.OMP_TARGET_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(269) # OpenMP target simd directive. CursorKind.OMP_TARGET_SIMD_DIRECTIVE = CursorKind(270) # OpenMP teams distribute directive. CursorKind.OMP_TEAMS_DISTRIBUTE_DIRECTIVE = CursorKind(271) # OpenMP teams distrbute simd directive CursorKind.OMP_TEAMS_DISTRIBUTE_SIMD_DIRECTIVE = CursorKind(272) # OpenMP teams distrbute parallel for simd directive CursorKind.OMP_TEAMS_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(273) # OpenMP teams distribute parallel for directive CursorKind.OMP_TEAMS_DISTRIBUTE_PARALLEL_FOR_DIRECTIVE = CursorKind(274) ### # Other Kinds # Cursor that represents the translation unit itself. # # The translation unit cursor exists primarily to act as the root cursor for # traversing the contents of a translation unit. CursorKind.TRANSLATION_UNIT = CursorKind(300) ### # Attributes # An attribute whoe specific kind is note exposed via this interface CursorKind.UNEXPOSED_ATTR = CursorKind(400) CursorKind.IB_ACTION_ATTR = CursorKind(401) CursorKind.IB_OUTLET_ATTR = CursorKind(402) CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403) CursorKind.CXX_FINAL_ATTR = CursorKind(404) CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405) CursorKind.ANNOTATE_ATTR = CursorKind(406) CursorKind.ASM_LABEL_ATTR = CursorKind(407) CursorKind.PACKED_ATTR = CursorKind(408) CursorKind.PURE_ATTR = CursorKind(409) CursorKind.CONST_ATTR = CursorKind(410) CursorKind.NODUPLICATE_ATTR = CursorKind(411) CursorKind.CUDACONSTANT_ATTR = CursorKind(412) CursorKind.CUDADEVICE_ATTR = CursorKind(413) CursorKind.CUDAGLOBAL_ATTR = CursorKind(414) CursorKind.CUDAHOST_ATTR = CursorKind(415) CursorKind.CUDASHARED_ATTR = CursorKind(416) CursorKind.VISIBILITY_ATTR = CursorKind(417) CursorKind.DLLEXPORT_ATTR = CursorKind(418) CursorKind.DLLIMPORT_ATTR = CursorKind(419) ### # Preprocessing CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500) CursorKind.MACRO_DEFINITION = CursorKind(501) CursorKind.MACRO_INSTANTIATION = CursorKind(502) CursorKind.INCLUSION_DIRECTIVE = CursorKind(503) ### # Extra declaration # A module import declaration. CursorKind.MODULE_IMPORT_DECL = CursorKind(600) # A type alias template declaration CursorKind.TYPE_ALIAS_TEMPLATE_DECL = CursorKind(601) # A static_assert or _Static_assert node CursorKind.STATIC_ASSERT = CursorKind(602) # A friend declaration CursorKind.FRIEND_DECL = CursorKind(603) # A code completion overload candidate. CursorKind.OVERLOAD_CANDIDATE = CursorKind(700) ### Template Argument Kinds ### class TemplateArgumentKind(BaseEnumeration): """ A TemplateArgumentKind describes the kind of entity that a template argument represents. """ # The required BaseEnumeration declarations. _kinds = [] _name_map = None TemplateArgumentKind.NULL = TemplateArgumentKind(0) TemplateArgumentKind.TYPE = TemplateArgumentKind(1) TemplateArgumentKind.DECLARATION = TemplateArgumentKind(2) TemplateArgumentKind.NULLPTR = TemplateArgumentKind(3) TemplateArgumentKind.INTEGRAL = TemplateArgumentKind(4) ### Exception Specification Kinds ### class ExceptionSpecificationKind(BaseEnumeration): """ An ExceptionSpecificationKind describes the kind of exception specification that a function has. """ # The required BaseEnumeration declarations. _kinds = [] _name_map = None def __repr__(self): return 'ExceptionSpecificationKind.{}'.format(self.name) ExceptionSpecificationKind.NONE = ExceptionSpecificationKind(0) ExceptionSpecificationKind.DYNAMIC_NONE = ExceptionSpecificationKind(1) ExceptionSpecificationKind.DYNAMIC = ExceptionSpecificationKind(2) ExceptionSpecificationKind.MS_ANY = ExceptionSpecificationKind(3) ExceptionSpecificationKind.BASIC_NOEXCEPT = ExceptionSpecificationKind(4) ExceptionSpecificationKind.COMPUTED_NOEXCEPT = ExceptionSpecificationKind(5) ExceptionSpecificationKind.UNEVALUATED = ExceptionSpecificationKind(6) ExceptionSpecificationKind.UNINSTANTIATED = ExceptionSpecificationKind(7) ExceptionSpecificationKind.UNPARSED = ExceptionSpecificationKind(8) ### Cursors ### class Cursor(Structure): """ The Cursor class represents a reference to an element within the AST. It acts as a kind of iterator. """ _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)] @staticmethod def from_location(tu, location): # We store a reference to the TU in the instance so the TU won't get # collected before the cursor. cursor = conf.lib.clang_getCursor(tu, location) cursor._tu = tu return cursor def __eq__(self, other): return conf.lib.clang_equalCursors(self, other) def __ne__(self, other): return not self.__eq__(other) def is_definition(self): """ Returns true if the declaration pointed at by the cursor is also a definition of that entity. """ return conf.lib.clang_isCursorDefinition(self) def is_const_method(self): """Returns True if the cursor refers to a C++ member function or member function template that is declared 'const'. """ return conf.lib.clang_CXXMethod_isConst(self) def is_converting_constructor(self): """Returns True if the cursor refers to a C++ converting constructor. """ return conf.lib.clang_CXXConstructor_isConvertingConstructor(self) def is_copy_constructor(self): """Returns True if the cursor refers to a C++ copy constructor. """ return conf.lib.clang_CXXConstructor_isCopyConstructor(self) def is_default_constructor(self): """Returns True if the cursor refers to a C++ default constructor. """ return conf.lib.clang_CXXConstructor_isDefaultConstructor(self) def is_move_constructor(self): """Returns True if the cursor refers to a C++ move constructor. """ return conf.lib.clang_CXXConstructor_isMoveConstructor(self) def is_default_method(self): """Returns True if the cursor refers to a C++ member function or member function template that is declared '= default'. """ return conf.lib.clang_CXXMethod_isDefaulted(self) def is_mutable_field(self): """Returns True if the cursor refers to a C++ field that is declared 'mutable'. """ return conf.lib.clang_CXXField_isMutable(self) def is_pure_virtual_method(self): """Returns True if the cursor refers to a C++ member function or member function template that is declared pure virtual. """ return conf.lib.clang_CXXMethod_isPureVirtual(self) def is_static_method(self): """Returns True if the cursor refers to a C++ member function or member function template that is declared 'static'. """ return conf.lib.clang_CXXMethod_isStatic(self) def is_virtual_method(self): """Returns True if the cursor refers to a C++ member function or member function template that is declared 'virtual'. """ return conf.lib.clang_CXXMethod_isVirtual(self) def is_abstract_record(self): """Returns True if the cursor refers to a C++ record declaration that has pure virtual member functions. """ return conf.lib.clang_CXXRecord_isAbstract(self) def is_scoped_enum(self): """Returns True if the cursor refers to a scoped enum declaration. """ return conf.lib.clang_EnumDecl_isScoped(self) def get_definition(self): """ If the cursor is a reference to a declaration or a declaration of some entity, return a cursor that points to the definition of that entity. """ # TODO: Should probably check that this is either a reference or # declaration prior to issuing the lookup. return conf.lib.clang_getCursorDefinition(self) def get_usr(self): """Return the Unified Symbol Resolution (USR) for the entity referenced by the given cursor (or None). A Unified Symbol Resolution (USR) is a string that identifies a particular entity (function, class, variable, etc.) within a program. USRs can be compared across translation units to determine, e.g., when references in one translation refer to an entity defined in another translation unit.""" return conf.lib.clang_getCursorUSR(self) def get_included_file(self): """Returns the File that is included by the current inclusion cursor.""" assert self.kind == CursorKind.INCLUSION_DIRECTIVE return conf.lib.clang_getIncludedFile(self) @property def kind(self): """Return the kind of this cursor.""" return CursorKind.from_id(self._kind_id) @property def spelling(self): """Return the spelling of the entity pointed at by the cursor.""" if not hasattr(self, '_spelling'): self._spelling = conf.lib.clang_getCursorSpelling(self) return self._spelling @property def displayname(self): """ Return the display name for the entity referenced by this cursor. The display name contains extra information that helps identify the cursor, such as the parameters of a function or template or the arguments of a class template specialization. """ if not hasattr(self, '_displayname'): self._displayname = conf.lib.clang_getCursorDisplayName(self) return self._displayname @property def mangled_name(self): """Return the mangled name for the entity referenced by this cursor.""" if not hasattr(self, '_mangled_name'): self._mangled_name = conf.lib.clang_Cursor_getMangling(self) return self._mangled_name @property def location(self): """ Return the source location (the starting character) of the entity pointed at by the cursor. """ if not hasattr(self, '_loc'): self._loc = conf.lib.clang_getCursorLocation(self) return self._loc @property def linkage(self): """Return the linkage of this cursor.""" if not hasattr(self, '_linkage'): self._linkage = conf.lib.clang_getCursorLinkage(self) return LinkageKind.from_id(self._linkage) @property def tls_kind(self): """Return the thread-local storage (TLS) kind of this cursor.""" if not hasattr(self, '_tls_kind'): self._tls_kind = conf.lib.clang_getCursorTLSKind(self) return TLSKind.from_id(self._tls_kind) @property def extent(self): """ Return the source range (the range of text) occupied by the entity pointed at by the cursor. """ if not hasattr(self, '_extent'): self._extent = conf.lib.clang_getCursorExtent(self) return self._extent @property def storage_class(self): """ Retrieves the storage class (if any) of the entity pointed at by the cursor. """ if not hasattr(self, '_storage_class'): self._storage_class = conf.lib.clang_Cursor_getStorageClass(self) return StorageClass.from_id(self._storage_class) @property def availability(self): """ Retrieves the availability of the entity pointed at by the cursor. """ if not hasattr(self, '_availability'): self._availability = conf.lib.clang_getCursorAvailability(self) return AvailabilityKind.from_id(self._availability) @property def access_specifier(self): """ Retrieves the access specifier (if any) of the entity pointed at by the cursor. """ if not hasattr(self, '_access_specifier'): self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self) return AccessSpecifier.from_id(self._access_specifier) @property def type(self): """ Retrieve the Type (if any) of the entity pointed at by the cursor. """ if not hasattr(self, '_type'): self._type = conf.lib.clang_getCursorType(self) return self._type @property def canonical(self): """Return the canonical Cursor corresponding to this Cursor. The canonical cursor is the cursor which is representative for the underlying entity. For example, if you have multiple forward declarations for the same class, the canonical cursor for the forward declarations will be identical. """ if not hasattr(self, '_canonical'): self._canonical = conf.lib.clang_getCanonicalCursor(self) return self._canonical @property def result_type(self): """Retrieve the Type of the result for this Cursor.""" if not hasattr(self, '_result_type'): self._result_type = conf.lib.clang_getCursorResultType(self) return self._result_type @property def exception_specification_kind(self): ''' Retrieve the exception specification kind, which is one of the values from the ExceptionSpecificationKind enumeration. ''' if not hasattr(self, '_exception_specification_kind'): exc_kind = conf.lib.clang_getCursorExceptionSpecificationType(self) self._exception_specification_kind = ExceptionSpecificationKind.from_id(exc_kind) return self._exception_specification_kind @property def underlying_typedef_type(self): """Return the underlying type of a typedef declaration. Returns a Type for the typedef this cursor is a declaration for. If the current cursor is not a typedef, this raises. """ if not hasattr(self, '_underlying_type'): assert self.kind.is_declaration() self._underlying_type = \ conf.lib.clang_getTypedefDeclUnderlyingType(self) return self._underlying_type @property def enum_type(self): """Return the integer type of an enum declaration. Returns a Type corresponding to an integer. If the cursor is not for an enum, this raises. """ if not hasattr(self, '_enum_type'): assert self.kind == CursorKind.ENUM_DECL self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self) return self._enum_type @property def enum_value(self): """Return the value of an enum constant.""" if not hasattr(self, '_enum_value'): assert self.kind == CursorKind.ENUM_CONSTANT_DECL # Figure out the underlying type of the enum to know if it # is a signed or unsigned quantity. underlying_type = self.type if underlying_type.kind == TypeKind.ENUM: underlying_type = underlying_type.get_declaration().enum_type if underlying_type.kind in (TypeKind.CHAR_U, TypeKind.UCHAR, TypeKind.CHAR16, TypeKind.CHAR32, TypeKind.USHORT, TypeKind.UINT, TypeKind.ULONG, TypeKind.ULONGLONG, TypeKind.UINT128): self._enum_value = \ conf.lib.clang_getEnumConstantDeclUnsignedValue(self) else: self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self) return self._enum_value @property def objc_type_encoding(self): """Return the Objective-C type encoding as a str.""" if not hasattr(self, '_objc_type_encoding'): self._objc_type_encoding = \ conf.lib.clang_getDeclObjCTypeEncoding(self) return self._objc_type_encoding @property def hash(self): """Returns a hash of the cursor as an int.""" if not hasattr(self, '_hash'): self._hash = conf.lib.clang_hashCursor(self) return self._hash @property def semantic_parent(self): """Return the semantic parent for this cursor.""" if not hasattr(self, '_semantic_parent'): self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self) return self._semantic_parent @property def lexical_parent(self): """Return the lexical parent for this cursor.""" if not hasattr(self, '_lexical_parent'): self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self) return self._lexical_parent @property def translation_unit(self): """Returns the TranslationUnit to which this Cursor belongs.""" # If this triggers an AttributeError, the instance was not properly # created. return self._tu @property def referenced(self): """ For a cursor that is a reference, returns a cursor representing the entity that it references. """ if not hasattr(self, '_referenced'): self._referenced = conf.lib.clang_getCursorReferenced(self) return self._referenced @property def brief_comment(self): """Returns the brief comment text associated with that Cursor""" return conf.lib.clang_Cursor_getBriefCommentText(self) @property def raw_comment(self): """Returns the raw comment text associated with that Cursor""" return conf.lib.clang_Cursor_getRawCommentText(self) def get_arguments(self): """Return an iterator for accessing the arguments of this cursor.""" num_args = conf.lib.clang_Cursor_getNumArguments(self) for i in range(0, num_args): yield conf.lib.clang_Cursor_getArgument(self, i) def get_num_template_arguments(self): """Returns the number of template args associated with this cursor.""" return conf.lib.clang_Cursor_getNumTemplateArguments(self) def get_template_argument_kind(self, num): """Returns the TemplateArgumentKind for the indicated template argument.""" return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num) def get_template_argument_type(self, num): """Returns the CXType for the indicated template argument.""" return conf.lib.clang_Cursor_getTemplateArgumentType(self, num) def get_template_argument_value(self, num): """Returns the value of the indicated arg as a signed 64b integer.""" return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num) def get_template_argument_unsigned_value(self, num): """Returns the value of the indicated arg as an unsigned 64b integer.""" return conf.lib.clang_Cursor_getTemplateArgumentUnsignedValue(self, num) def get_children(self): """Return an iterator for accessing the children of this cursor.""" # FIXME: Expose iteration from CIndex, PR6125. def visitor(child, parent, children): # FIXME: Document this assertion in API. # FIXME: There should just be an isNull method. assert child != conf.lib.clang_getNullCursor() # Create reference to TU so it isn't GC'd before Cursor. child._tu = self._tu children.append(child) return 1 # continue children = [] conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor), children) return iter(children) def walk_preorder(self): """Depth-first preorder walk over the cursor and its descendants. Yields cursors. """ yield self for child in self.get_children(): for descendant in child.walk_preorder(): yield descendant def get_tokens(self): """Obtain Token instances formulating that compose this Cursor. This is a generator for Token instances. It returns all tokens which occupy the extent this cursor occupies. """ return TokenGroup.get_tokens(self._tu, self.extent) def get_field_offsetof(self): """Returns the offsetof the FIELD_DECL pointed by this Cursor.""" return conf.lib.clang_Cursor_getOffsetOfField(self) def is_anonymous(self): """ Check if the record is anonymous. """ if self.kind == CursorKind.FIELD_DECL: return self.type.get_declaration().is_anonymous() return conf.lib.clang_Cursor_isAnonymous(self) def is_bitfield(self): """ Check if the field is a bitfield. """ return conf.lib.clang_Cursor_isBitField(self) def get_bitfield_width(self): """ Retrieve the width of a bitfield. """ return conf.lib.clang_getFieldDeclBitWidth(self) @staticmethod def from_result(res, fn, args): assert isinstance(res, Cursor) # FIXME: There should just be an isNull method. if res == conf.lib.clang_getNullCursor(): return None # Store a reference to the TU in the Python object so it won't get GC'd # before the Cursor. tu = None for arg in args: if isinstance(arg, TranslationUnit): tu = arg break if hasattr(arg, 'translation_unit'): tu = arg.translation_unit break assert tu is not None res._tu = tu return res @staticmethod def from_cursor_result(res, fn, args): assert isinstance(res, Cursor) if res == conf.lib.clang_getNullCursor(): return None res._tu = args[0]._tu return res class StorageClass(object): """ Describes the storage class of a declaration """ # The unique kind objects, index by id. _kinds = [] _name_map = None def __init__(self, value): if value >= len(StorageClass._kinds): StorageClass._kinds += [None] * (value - len(StorageClass._kinds) + 1) if StorageClass._kinds[value] is not None: raise ValueError('StorageClass already loaded') self.value = value StorageClass._kinds[value] = self StorageClass._name_map = None def from_param(self): return self.value @property def name(self): """Get the enumeration name of this storage class.""" if self._name_map is None: self._name_map = {} for key,value in StorageClass.__dict__.items(): if isinstance(value,StorageClass): self._name_map[value] = key return self._name_map[self] @staticmethod def from_id(id): if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]: raise ValueError('Unknown storage class %d' % id) return StorageClass._kinds[id] def __repr__(self): return 'StorageClass.%s' % (self.name,) StorageClass.INVALID = StorageClass(0) StorageClass.NONE = StorageClass(1) StorageClass.EXTERN = StorageClass(2) StorageClass.STATIC = StorageClass(3) StorageClass.PRIVATEEXTERN = StorageClass(4) StorageClass.OPENCLWORKGROUPLOCAL = StorageClass(5) StorageClass.AUTO = StorageClass(6) StorageClass.REGISTER = StorageClass(7) ### Availability Kinds ### class AvailabilityKind(BaseEnumeration): """ Describes the availability of an entity. """ # The unique kind objects, indexed by id. _kinds = [] _name_map = None def __repr__(self): return 'AvailabilityKind.%s' % (self.name,) AvailabilityKind.AVAILABLE = AvailabilityKind(0) AvailabilityKind.DEPRECATED = AvailabilityKind(1) AvailabilityKind.NOT_AVAILABLE = AvailabilityKind(2) AvailabilityKind.NOT_ACCESSIBLE = AvailabilityKind(3) ### C++ access specifiers ### class AccessSpecifier(BaseEnumeration): """ Describes the access of a C++ class member """ # The unique kind objects, index by id. _kinds = [] _name_map = None def from_param(self): return self.value def __repr__(self): return 'AccessSpecifier.%s' % (self.name,) AccessSpecifier.INVALID = AccessSpecifier(0) AccessSpecifier.PUBLIC = AccessSpecifier(1) AccessSpecifier.PROTECTED = AccessSpecifier(2) AccessSpecifier.PRIVATE = AccessSpecifier(3) AccessSpecifier.NONE = AccessSpecifier(4) ### Type Kinds ### class TypeKind(BaseEnumeration): """ Describes the kind of type. """ # The unique kind objects, indexed by id. _kinds = [] _name_map = None @property def spelling(self): """Retrieve the spelling of this TypeKind.""" return conf.lib.clang_getTypeKindSpelling(self.value) def __repr__(self): return 'TypeKind.%s' % (self.name,) TypeKind.INVALID = TypeKind(0) TypeKind.UNEXPOSED = TypeKind(1) TypeKind.VOID = TypeKind(2) TypeKind.BOOL = TypeKind(3) TypeKind.CHAR_U = TypeKind(4) TypeKind.UCHAR = TypeKind(5) TypeKind.CHAR16 = TypeKind(6) TypeKind.CHAR32 = TypeKind(7) TypeKind.USHORT = TypeKind(8) TypeKind.UINT = TypeKind(9) TypeKind.ULONG = TypeKind(10) TypeKind.ULONGLONG = TypeKind(11) TypeKind.UINT128 = TypeKind(12) TypeKind.CHAR_S = TypeKind(13) TypeKind.SCHAR = TypeKind(14) TypeKind.WCHAR = TypeKind(15) TypeKind.SHORT = TypeKind(16) TypeKind.INT = TypeKind(17) TypeKind.LONG = TypeKind(18) TypeKind.LONGLONG = TypeKind(19) TypeKind.INT128 = TypeKind(20) TypeKind.FLOAT = TypeKind(21) TypeKind.DOUBLE = TypeKind(22) TypeKind.LONGDOUBLE = TypeKind(23) TypeKind.NULLPTR = TypeKind(24) TypeKind.OVERLOAD = TypeKind(25) TypeKind.DEPENDENT = TypeKind(26) TypeKind.OBJCID = TypeKind(27) TypeKind.OBJCCLASS = TypeKind(28) TypeKind.OBJCSEL = TypeKind(29) TypeKind.FLOAT128 = TypeKind(30) TypeKind.HALF = TypeKind(31) TypeKind.COMPLEX = TypeKind(100) TypeKind.POINTER = TypeKind(101) TypeKind.BLOCKPOINTER = TypeKind(102) TypeKind.LVALUEREFERENCE = TypeKind(103) TypeKind.RVALUEREFERENCE = TypeKind(104) TypeKind.RECORD = TypeKind(105) TypeKind.ENUM = TypeKind(106) TypeKind.TYPEDEF = TypeKind(107) TypeKind.OBJCINTERFACE = TypeKind(108) TypeKind.OBJCOBJECTPOINTER = TypeKind(109) TypeKind.FUNCTIONNOPROTO = TypeKind(110) TypeKind.FUNCTIONPROTO = TypeKind(111) TypeKind.CONSTANTARRAY = TypeKind(112) TypeKind.VECTOR = TypeKind(113) TypeKind.INCOMPLETEARRAY = TypeKind(114) TypeKind.VARIABLEARRAY = TypeKind(115) TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116) TypeKind.MEMBERPOINTER = TypeKind(117) TypeKind.AUTO = TypeKind(118) TypeKind.ELABORATED = TypeKind(119) TypeKind.PIPE = TypeKind(120) TypeKind.OCLIMAGE1DRO = TypeKind(121) TypeKind.OCLIMAGE1DARRAYRO = TypeKind(122) TypeKind.OCLIMAGE1DBUFFERRO = TypeKind(123) TypeKind.OCLIMAGE2DRO = TypeKind(124) TypeKind.OCLIMAGE2DARRAYRO = TypeKind(125) TypeKind.OCLIMAGE2DDEPTHRO = TypeKind(126) TypeKind.OCLIMAGE2DARRAYDEPTHRO = TypeKind(127) TypeKind.OCLIMAGE2DMSAARO = TypeKind(128) TypeKind.OCLIMAGE2DARRAYMSAARO = TypeKind(129) TypeKind.OCLIMAGE2DMSAADEPTHRO = TypeKind(130) TypeKind.OCLIMAGE2DARRAYMSAADEPTHRO = TypeKind(131) TypeKind.OCLIMAGE3DRO = TypeKind(132) TypeKind.OCLIMAGE1DWO = TypeKind(133) TypeKind.OCLIMAGE1DARRAYWO = TypeKind(134) TypeKind.OCLIMAGE1DBUFFERWO = TypeKind(135) TypeKind.OCLIMAGE2DWO = TypeKind(136) TypeKind.OCLIMAGE2DARRAYWO = TypeKind(137) TypeKind.OCLIMAGE2DDEPTHWO = TypeKind(138) TypeKind.OCLIMAGE2DARRAYDEPTHWO = TypeKind(139) TypeKind.OCLIMAGE2DMSAAWO = TypeKind(140) TypeKind.OCLIMAGE2DARRAYMSAAWO = TypeKind(141) TypeKind.OCLIMAGE2DMSAADEPTHWO = TypeKind(142) TypeKind.OCLIMAGE2DARRAYMSAADEPTHWO = TypeKind(143) TypeKind.OCLIMAGE3DWO = TypeKind(144) TypeKind.OCLIMAGE1DRW = TypeKind(145) TypeKind.OCLIMAGE1DARRAYRW = TypeKind(146) TypeKind.OCLIMAGE1DBUFFERRW = TypeKind(147) TypeKind.OCLIMAGE2DRW = TypeKind(148) TypeKind.OCLIMAGE2DARRAYRW = TypeKind(149) TypeKind.OCLIMAGE2DDEPTHRW = TypeKind(150) TypeKind.OCLIMAGE2DARRAYDEPTHRW = TypeKind(151) TypeKind.OCLIMAGE2DMSAARW = TypeKind(152) TypeKind.OCLIMAGE2DARRAYMSAARW = TypeKind(153) TypeKind.OCLIMAGE2DMSAADEPTHRW = TypeKind(154) TypeKind.OCLIMAGE2DARRAYMSAADEPTHRW = TypeKind(155) TypeKind.OCLIMAGE3DRW = TypeKind(156) TypeKind.OCLSAMPLER = TypeKind(157) TypeKind.OCLEVENT = TypeKind(158) TypeKind.OCLQUEUE = TypeKind(159) TypeKind.OCLRESERVEID = TypeKind(160) class RefQualifierKind(BaseEnumeration): """Describes a specific ref-qualifier of a type.""" # The unique kind objects, indexed by id. _kinds = [] _name_map = None def from_param(self): return self.value def __repr__(self): return 'RefQualifierKind.%s' % (self.name,) RefQualifierKind.NONE = RefQualifierKind(0) RefQualifierKind.LVALUE = RefQualifierKind(1) RefQualifierKind.RVALUE = RefQualifierKind(2) class LinkageKind(BaseEnumeration): """Describes the kind of linkage of a cursor.""" # The unique kind objects, indexed by id. _kinds = [] _name_map = None def from_param(self): return self.value def __repr__(self): return 'LinkageKind.%s' % (self.name,) LinkageKind.INVALID = LinkageKind(0) LinkageKind.NO_LINKAGE = LinkageKind(1) LinkageKind.INTERNAL = LinkageKind(2) LinkageKind.UNIQUE_EXTERNAL = LinkageKind(3) LinkageKind.EXTERNAL = LinkageKind(4) class TLSKind(BaseEnumeration): """Describes the kind of thread-local storage (TLS) of a cursor.""" # The unique kind objects, indexed by id. _kinds = [] _name_map = None def from_param(self): return self.value def __repr__(self): return 'TLSKind.%s' % (self.name,) TLSKind.NONE = TLSKind(0) TLSKind.DYNAMIC = TLSKind(1) TLSKind.STATIC = TLSKind(2) class Type(Structure): """ The type of an element in the abstract syntax tree. """ _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)] @property def kind(self): """Return the kind of this type.""" return TypeKind.from_id(self._kind_id) def argument_types(self): """Retrieve a container for the non-variadic arguments for this type. The returned object is iterable and indexable. Each item in the container is a Type instance. """ class ArgumentsIterator(collections.Sequence): def __init__(self, parent): self.parent = parent self.length = None def __len__(self): if self.length is None: self.length = conf.lib.clang_getNumArgTypes(self.parent) return self.length def __getitem__(self, key): # FIXME Support slice objects. if not isinstance(key, int): raise TypeError("Must supply a non-negative int.") if key < 0: raise IndexError("Only non-negative indexes are accepted.") if key >= len(self): raise IndexError("Index greater than container length: " "%d > %d" % ( key, len(self) )) result = conf.lib.clang_getArgType(self.parent, key) if result.kind == TypeKind.INVALID: raise IndexError("Argument could not be retrieved.") return result assert self.kind == TypeKind.FUNCTIONPROTO return ArgumentsIterator(self) @property def element_type(self): """Retrieve the Type of elements within this Type. If accessed on a type that is not an array, complex, or vector type, an exception will be raised. """ result = conf.lib.clang_getElementType(self) if result.kind == TypeKind.INVALID: raise Exception('Element type not available on this type.') return result @property def element_count(self): """Retrieve the number of elements in this type. Returns an int. If the Type is not an array or vector, this raises. """ result = conf.lib.clang_getNumElements(self) if result < 0: raise Exception('Type does not have elements.') return result @property def translation_unit(self): """The TranslationUnit to which this Type is associated.""" # If this triggers an AttributeError, the instance was not properly # instantiated. return self._tu @staticmethod def from_result(res, fn, args): assert isinstance(res, Type) tu = None for arg in args: if hasattr(arg, 'translation_unit'): tu = arg.translation_unit break assert tu is not None res._tu = tu return res def get_num_template_arguments(self): return conf.lib.clang_Type_getNumTemplateArguments(self) def get_template_argument_type(self, num): return conf.lib.clang_Type_getTemplateArgumentAsType(self, num) def get_canonical(self): """ Return the canonical type for a Type. Clang's type system explicitly models typedefs and all the ways a specific type can be represented. The canonical type is the underlying type with all the "sugar" removed. For example, if 'T' is a typedef for 'int', the canonical type for 'T' would be 'int'. """ return conf.lib.clang_getCanonicalType(self) def is_const_qualified(self): """Determine whether a Type has the "const" qualifier set. This does not look through typedefs that may have added "const" at a different level. """ return conf.lib.clang_isConstQualifiedType(self) def is_volatile_qualified(self): """Determine whether a Type has the "volatile" qualifier set. This does not look through typedefs that may have added "volatile" at a different level. """ return conf.lib.clang_isVolatileQualifiedType(self) def is_restrict_qualified(self): """Determine whether a Type has the "restrict" qualifier set. This does not look through typedefs that may have added "restrict" at a different level. """ return conf.lib.clang_isRestrictQualifiedType(self) def is_function_variadic(self): """Determine whether this function Type is a variadic function type.""" assert self.kind == TypeKind.FUNCTIONPROTO return conf.lib.clang_isFunctionTypeVariadic(self) def get_address_space(self): return conf.lib.clang_getAddressSpace(self) def get_typedef_name(self): return conf.lib.clang_getTypedefName(self) def is_pod(self): """Determine whether this Type represents plain old data (POD).""" return conf.lib.clang_isPODType(self) def get_pointee(self): """ For pointer types, returns the type of the pointee. """ return conf.lib.clang_getPointeeType(self) def get_declaration(self): """ Return the cursor for the declaration of the given type. """ return conf.lib.clang_getTypeDeclaration(self) def get_result(self): """ Retrieve the result type associated with a function type. """ return conf.lib.clang_getResultType(self) def get_array_element_type(self): """ Retrieve the type of the elements of the array type. """ return conf.lib.clang_getArrayElementType(self) def get_array_size(self): """ Retrieve the size of the constant array. """ return conf.lib.clang_getArraySize(self) def get_class_type(self): """ Retrieve the class type of the member pointer type. """ return conf.lib.clang_Type_getClassType(self) def get_named_type(self): """ Retrieve the type named by the qualified-id. """ return conf.lib.clang_Type_getNamedType(self) def get_align(self): """ Retrieve the alignment of the record. """ return conf.lib.clang_Type_getAlignOf(self) def get_size(self): """ Retrieve the size of the record. """ return conf.lib.clang_Type_getSizeOf(self) def get_offset(self, fieldname): """ Retrieve the offset of a field in the record. """ return conf.lib.clang_Type_getOffsetOf(self, c_interop_string(b(fieldname))) def get_ref_qualifier(self): """ Retrieve the ref-qualifier of the type. """ return RefQualifierKind.from_id( conf.lib.clang_Type_getCXXRefQualifier(self)) def get_fields(self): """Return an iterator for accessing the fields of this type.""" def visitor(field, children): assert field != conf.lib.clang_getNullCursor() # Create reference to TU so it isn't GC'd before Cursor. field._tu = self._tu fields.append(field) return 1 # continue fields = [] conf.lib.clang_Type_visitFields(self, callbacks['fields_visit'](visitor), fields) return iter(fields) def get_exception_specification_kind(self): """ Return the kind of the exception specification; a value from the ExceptionSpecificationKind enumeration. """ return ExceptionSpecificationKind.from_id( conf.lib.clang.getExceptionSpecificationType(self)) @property def spelling(self): """Retrieve the spelling of this Type.""" return conf.lib.clang_getTypeSpelling(self) def __eq__(self, other): if type(other) != type(self): return False return conf.lib.clang_equalTypes(self, other) def __ne__(self, other): return not self.__eq__(other) ## CIndex Objects ## # CIndex objects (derived from ClangObject) are essentially lightweight # wrappers attached to some underlying object, which is exposed via CIndex as # a void*. class ClangObject(object): """ A helper for Clang objects. This class helps act as an intermediary for the ctypes library and the Clang CIndex library. """ def __init__(self, obj): assert isinstance(obj, c_object_p) and obj self.obj = self._as_parameter_ = obj def from_param(self): return self._as_parameter_ class _CXUnsavedFile(Structure): """Helper for passing unsaved file arguments.""" _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)] # Functions calls through the python interface are rather slow. Fortunately, # for most symboles, we do not need to perform a function call. Their spelling # never changes and is consequently provided by this spelling cache. SpellingCache = { # 0: CompletionChunk.Kind("Optional"), # 1: CompletionChunk.Kind("TypedText"), # 2: CompletionChunk.Kind("Text"), # 3: CompletionChunk.Kind("Placeholder"), # 4: CompletionChunk.Kind("Informative"), # 5 : CompletionChunk.Kind("CurrentParameter"), 6: '(', # CompletionChunk.Kind("LeftParen"), 7: ')', # CompletionChunk.Kind("RightParen"), 8: '[', # CompletionChunk.Kind("LeftBracket"), 9: ']', # CompletionChunk.Kind("RightBracket"), 10: '{', # CompletionChunk.Kind("LeftBrace"), 11: '}', # CompletionChunk.Kind("RightBrace"), 12: '<', # CompletionChunk.Kind("LeftAngle"), 13: '>', # CompletionChunk.Kind("RightAngle"), 14: ', ', # CompletionChunk.Kind("Comma"), # 15: CompletionChunk.Kind("ResultType"), 16: ':', # CompletionChunk.Kind("Colon"), 17: ';', # CompletionChunk.Kind("SemiColon"), 18: '=', # CompletionChunk.Kind("Equal"), 19: ' ', # CompletionChunk.Kind("HorizontalSpace"), # 20: CompletionChunk.Kind("VerticalSpace") } class CompletionChunk(object): class Kind(object): def __init__(self, name): self.name = name def __str__(self): return self.name def __repr__(self): return "<ChunkKind: %s>" % self def __init__(self, completionString, key): self.cs = completionString self.key = key self.__kindNumberCache = -1 def __repr__(self): return "{'" + self.spelling + "', " + str(self.kind) + "}" @CachedProperty def spelling(self): if self.__kindNumber in SpellingCache: return SpellingCache[self.__kindNumber] return conf.lib.clang_getCompletionChunkText(self.cs, self.key) # We do not use @CachedProperty here, as the manual implementation is # apparently still significantly faster. Please profile carefully if you # would like to add CachedProperty back. @property def __kindNumber(self): if self.__kindNumberCache == -1: self.__kindNumberCache = \ conf.lib.clang_getCompletionChunkKind(self.cs, self.key) return self.__kindNumberCache @CachedProperty def kind(self): return completionChunkKindMap[self.__kindNumber] @CachedProperty def string(self): res = conf.lib.clang_getCompletionChunkCompletionString(self.cs, self.key) if (res): return CompletionString(res) else: None def isKindOptional(self): return self.__kindNumber == 0 def isKindTypedText(self): return self.__kindNumber == 1 def isKindPlaceHolder(self): return self.__kindNumber == 3 def isKindInformative(self): return self.__kindNumber == 4 def isKindResultType(self): return self.__kindNumber == 15 completionChunkKindMap = { 0: CompletionChunk.Kind("Optional"), 1: CompletionChunk.Kind("TypedText"), 2: CompletionChunk.Kind("Text"), 3: CompletionChunk.Kind("Placeholder"), 4: CompletionChunk.Kind("Informative"), 5: CompletionChunk.Kind("CurrentParameter"), 6: CompletionChunk.Kind("LeftParen"), 7: CompletionChunk.Kind("RightParen"), 8: CompletionChunk.Kind("LeftBracket"), 9: CompletionChunk.Kind("RightBracket"), 10: CompletionChunk.Kind("LeftBrace"), 11: CompletionChunk.Kind("RightBrace"), 12: CompletionChunk.Kind("LeftAngle"), 13: CompletionChunk.Kind("RightAngle"), 14: CompletionChunk.Kind("Comma"), 15: CompletionChunk.Kind("ResultType"), 16: CompletionChunk.Kind("Colon"), 17: CompletionChunk.Kind("SemiColon"), 18: CompletionChunk.Kind("Equal"), 19: CompletionChunk.Kind("HorizontalSpace"), 20: CompletionChunk.Kind("VerticalSpace")} class CompletionString(ClangObject): class Availability(object): def __init__(self, name): self.name = name def __str__(self): return self.name def __repr__(self): return "<Availability: %s>" % self def __len__(self): return self.num_chunks @CachedProperty def num_chunks(self): return conf.lib.clang_getNumCompletionChunks(self.obj) def __getitem__(self, key): if self.num_chunks <= key: raise IndexError return CompletionChunk(self.obj, key) @property def priority(self): return conf.lib.clang_getCompletionPriority(self.obj) @property def availability(self): res = conf.lib.clang_getCompletionAvailability(self.obj) return availabilityKinds[res] @property def briefComment(self): if conf.function_exists("clang_getCompletionBriefComment"): return conf.lib.clang_getCompletionBriefComment(self.obj) return _CXString() def __repr__(self): return " | ".join([str(a) for a in self]) \ + " || Priority: " + str(self.priority) \ + " || Availability: " + str(self.availability) \ + " || Brief comment: " + str(self.briefComment) availabilityKinds = { 0: CompletionChunk.Kind("Available"), 1: CompletionChunk.Kind("Deprecated"), 2: CompletionChunk.Kind("NotAvailable"), 3: CompletionChunk.Kind("NotAccessible")} class CodeCompletionResult(Structure): _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)] def __repr__(self): return str(CompletionString(self.completionString)) @property def kind(self): return CursorKind.from_id(self.cursorKind) @property def string(self): return CompletionString(self.completionString) class CCRStructure(Structure): _fields_ = [('results', POINTER(CodeCompletionResult)), ('numResults', c_int)] def __len__(self): return self.numResults def __getitem__(self, key): if len(self) <= key: raise IndexError return self.results[key] class CodeCompletionResults(ClangObject): def __init__(self, ptr): assert isinstance(ptr, POINTER(CCRStructure)) and ptr self.ptr = self._as_parameter_ = ptr def from_param(self): return self._as_parameter_ def __del__(self): conf.lib.clang_disposeCodeCompleteResults(self) @property def results(self): return self.ptr.contents @property def diagnostics(self): class DiagnosticsItr(object): def __init__(self, ccr): self.ccr= ccr def __len__(self): return int(\ conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr)) def __getitem__(self, key): return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key) return DiagnosticsItr(self) class Index(ClangObject): """ The Index type provides the primary interface to the Clang CIndex library, primarily by providing an interface for reading and parsing translation units. """ @staticmethod def create(excludeDecls=False): """ Create a new Index. Parameters: excludeDecls -- Exclude local declarations from translation units. """ return Index(conf.lib.clang_createIndex(excludeDecls, 0)) def __del__(self): conf.lib.clang_disposeIndex(self) def read(self, path): """Load a TranslationUnit from the given AST file.""" return TranslationUnit.from_ast_file(path, self) def parse(self, path, args=None, unsaved_files=None, options = 0): """Load the translation unit from the given source code file by running clang and generating the AST before loading. Additional command line parameters can be passed to clang via the args parameter. In-memory contents for files can be provided by passing a list of pairs to as unsaved_files, the first item should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. If an error was encountered during parsing, a TranslationUnitLoadError will be raised. """ return TranslationUnit.from_source(path, args, unsaved_files, options, self) class TranslationUnit(ClangObject): """Represents a source code translation unit. This is one of the main types in the API. Any time you wish to interact with Clang's representation of a source file, you typically start with a translation unit. """ # Default parsing mode. PARSE_NONE = 0 # Instruct the parser to create a detailed processing record containing # metadata not normally retained. PARSE_DETAILED_PROCESSING_RECORD = 1 # Indicates that the translation unit is incomplete. This is typically used # when parsing headers. PARSE_INCOMPLETE = 2 # Instruct the parser to create a pre-compiled preamble for the translation # unit. This caches the preamble (included files at top of source file). # This is useful if the translation unit will be reparsed and you don't # want to incur the overhead of reparsing the preamble. PARSE_PRECOMPILED_PREAMBLE = 4 # Cache code completion information on parse. This adds time to parsing but # speeds up code completion. PARSE_CACHE_COMPLETION_RESULTS = 8 # Flags with values 16 and 32 are deprecated and intentionally omitted. # Do not parse function bodies. This is useful if you only care about # searching for declarations/definitions. PARSE_SKIP_FUNCTION_BODIES = 64 # Used to indicate that brief documentation comments should be included # into the set of code completions returned from this translation unit. PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128 # Used to indicate that the precompiled preamble should be created on # the first parse. Otherwise it will be created on the first reparse. This # trades runtime on the first parse (serializing the preamble takes time) for # reduced runtime on the second parse (can now reuse the preamble). CREATE_PREAMBLE_ON_FIRST_PARSE = 256 # Do not stop processing when fatal errors are encountered. # When fatal errors are encountered while parsing a translation unit, # semantic analysis is typically stopped early when compiling code. A common # source for fatal errors are unresolvable include files. For the # purposes of an IDE, this is undesirable behavior and as much information # as possible should be reported. Use this flag to enable this behavior. KEEP_GOING = 512 @classmethod def from_source(cls, filename, args=None, unsaved_files=None, options=0, index=None): """Create a TranslationUnit by parsing source. This is capable of processing source code both from files on the filesystem as well as in-memory contents. Command-line arguments that would be passed to clang are specified as a list via args. These can be used to specify include paths, warnings, etc. e.g. ["-Wall", "-I/path/to/include"]. In-memory file content can be provided via unsaved_files. This is an iterable of 2-tuples. The first element is the filename (str or PathLike). The second element defines the content. Content can be provided as str source code or as file objects (anything with a read() method). If a file object is being used, content will be read until EOF and the read cursor will not be reset to its original position. options is a bitwise or of TranslationUnit.PARSE_XXX flags which will control parsing behavior. index is an Index instance to utilize. If not provided, a new Index will be created for this TranslationUnit. To parse source from the filesystem, the filename of the file to parse is specified by the filename argument. Or, filename could be None and the args list would contain the filename(s) to parse. To parse source from an in-memory buffer, set filename to the virtual filename you wish to associate with this source (e.g. "test.c"). The contents of that file are then provided in unsaved_files. If an error occurs, a TranslationUnitLoadError is raised. Please note that a TranslationUnit with parser errors may be returned. It is the caller's responsibility to check tu.diagnostics for errors. Also note that Clang infers the source language from the extension of the input filename. If you pass in source code containing a C++ class declaration with the filename "test.c" parsing will fail. """ if args is None: args = [] if unsaved_files is None: unsaved_files = [] if index is None: index = Index.create() args_array = None if len(args) > 0: args_array = (c_char_p * len(args))(*[b(x) for x in args]) unsaved_array = None if len(unsaved_files) > 0: unsaved_array = (_CXUnsavedFile * len(unsaved_files))() for i, (name, contents) in enumerate(unsaved_files): if hasattr(contents, "read"): contents = contents.read() unsaved_array[i].name = b(fspath(name)) unsaved_array[i].contents = b(contents) unsaved_array[i].length = len(contents) ptr = conf.lib.clang_parseTranslationUnit(index, b(fspath(filename)) if filename is not None else None, args_array, len(args), unsaved_array, len(unsaved_files), options) if not ptr: raise TranslationUnitLoadError("Error parsing translation unit.") return cls(ptr, index=index) @classmethod def from_ast_file(cls, filename, index=None): """Create a TranslationUnit instance from a saved AST file. A previously-saved AST file (provided with -emit-ast or TranslationUnit.save()) is loaded from the filename specified. If the file cannot be loaded, a TranslationUnitLoadError will be raised. index is optional and is the Index instance to use. If not provided, a default Index will be created. filename can be str or PathLike. """ if index is None: index = Index.create() ptr = conf.lib.clang_createTranslationUnit(index, b(fspath(filename))) if not ptr: raise TranslationUnitLoadError(filename) return cls(ptr=ptr, index=index) def __init__(self, ptr, index): """Create a TranslationUnit instance. TranslationUnits should be created using one of the from_* @classmethod functions above. __init__ is only called internally. """ assert isinstance(index, Index) self.index = index ClangObject.__init__(self, ptr) def __del__(self): conf.lib.clang_disposeTranslationUnit(self) @property def cursor(self): """Retrieve the cursor that represents the given translation unit.""" return conf.lib.clang_getTranslationUnitCursor(self) @property def spelling(self): """Get the original translation unit source file name.""" return conf.lib.clang_getTranslationUnitSpelling(self) def get_includes(self): """ Return an iterable sequence of FileInclusion objects that describe the sequence of inclusions in a translation unit. The first object in this sequence is always the input file. Note that this method will not recursively iterate over header files included through precompiled headers. """ def visitor(fobj, lptr, depth, includes): if depth > 0: loc = lptr.contents includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) # Automatically adapt CIndex/ctype pointers to python objects includes = [] conf.lib.clang_getInclusions(self, callbacks['translation_unit_includes'](visitor), includes) return iter(includes) def get_file(self, filename): """Obtain a File from this translation unit.""" return File.from_name(self, filename) def get_location(self, filename, position): """Obtain a SourceLocation for a file in this translation unit. The position can be specified by passing: - Integer file offset. Initial file offset is 0. - 2-tuple of (line number, column number). Initial file position is (0, 0) """ f = self.get_file(filename) if isinstance(position, int): return SourceLocation.from_offset(self, f, position) return SourceLocation.from_position(self, f, position[0], position[1]) def get_extent(self, filename, locations): """Obtain a SourceRange from this translation unit. The bounds of the SourceRange must ultimately be defined by a start and end SourceLocation. For the locations argument, you can pass: - 2 SourceLocation instances in a 2-tuple or list. - 2 int file offsets via a 2-tuple or list. - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. e.g. get_extent('foo.c', (5, 10)) get_extent('foo.c', ((1, 1), (1, 15))) """ f = self.get_file(filename) if len(locations) < 2: raise Exception('Must pass object with at least 2 elements') start_location, end_location = locations if hasattr(start_location, '__len__'): start_location = SourceLocation.from_position(self, f, start_location[0], start_location[1]) elif isinstance(start_location, int): start_location = SourceLocation.from_offset(self, f, start_location) if hasattr(end_location, '__len__'): end_location = SourceLocation.from_position(self, f, end_location[0], end_location[1]) elif isinstance(end_location, int): end_location = SourceLocation.from_offset(self, f, end_location) assert isinstance(start_location, SourceLocation) assert isinstance(end_location, SourceLocation) return SourceRange.from_locations(start_location, end_location) @property def diagnostics(self): """ Return an iterable (and indexable) object containing the diagnostics. """ class DiagIterator(object): def __init__(self, tu): self.tu = tu def __len__(self): return int(conf.lib.clang_getNumDiagnostics(self.tu)) def __getitem__(self, key): diag = conf.lib.clang_getDiagnostic(self.tu, key) if not diag: raise IndexError return Diagnostic(diag) return DiagIterator(self) def reparse(self, unsaved_files=None, options=0): """ Reparse an already parsed translation unit. In-memory contents for files can be provided by passing a list of pairs as unsaved_files, the first items should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. """ if unsaved_files is None: unsaved_files = [] unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() for i,(name,value) in enumerate(unsaved_files): if not isinstance(value, str): # FIXME: It would be great to support an efficient version # of this, one day. value = value.read() print(value) if not isinstance(value, str): raise TypeError('Unexpected unsaved file contents.') unsaved_files_array[i].name = b(fspath(name)) unsaved_files_array[i].contents = b(value) unsaved_files_array[i].length = len(value) ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files), unsaved_files_array, options) def save(self, filename): """Saves the TranslationUnit to a file. This is equivalent to passing -emit-ast to the clang frontend. The saved file can be loaded back into a TranslationUnit. Or, if it corresponds to a header, it can be used as a pre-compiled header file. If an error occurs while saving, a TranslationUnitSaveError is raised. If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means the constructed TranslationUnit was not valid at time of save. In this case, the reason(s) why should be available via TranslationUnit.diagnostics(). filename -- The path to save the translation unit to (str or PathLike). """ options = conf.lib.clang_defaultSaveOptions(self) result = int(conf.lib.clang_saveTranslationUnit(self, b(fspath(filename)), options)) if result != 0: raise TranslationUnitSaveError(result, 'Error saving TranslationUnit.') def codeComplete(self, path, line, column, unsaved_files=None, include_macros=False, include_code_patterns=False, include_brief_comments=False): """ Code complete in this translation unit. In-memory contents for files can be provided by passing a list of pairs as unsaved_files, the first items should be the filenames to be mapped and the second should be the contents to be substituted for the file. The contents may be passed as strings or file objects. """ options = 0 if include_macros: options += 1 if include_code_patterns: options += 2 if include_brief_comments: options += 4 if unsaved_files is None: unsaved_files = [] unsaved_files_array = 0 if len(unsaved_files): unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() for i,(name,value) in enumerate(unsaved_files): if not isinstance(value, str): # FIXME: It would be great to support an efficient version # of this, one day. value = value.read() print(value) if not isinstance(value, str): raise TypeError('Unexpected unsaved file contents.') unsaved_files_array[i].name = b(fspath(name)) unsaved_files_array[i].contents = b(value) unsaved_files_array[i].length = len(value) ptr = conf.lib.clang_codeCompleteAt(self, b(fspath(path)), line, column, unsaved_files_array, len(unsaved_files), options) if ptr: return CodeCompletionResults(ptr) return None def get_tokens(self, locations=None, extent=None): """Obtain tokens in this translation unit. This is a generator for Token instances. The caller specifies a range of source code to obtain tokens for. The range can be specified as a 2-tuple of SourceLocation or as a SourceRange. If both are defined, behavior is undefined. """ if locations is not None: extent = SourceRange(start=locations[0], end=locations[1]) return TokenGroup.get_tokens(self, extent) class File(ClangObject): """ The File class represents a particular source file that is part of a translation unit. """ @staticmethod def from_name(translation_unit, file_name): """Retrieve a file handle within the given translation unit.""" return File(conf.lib.clang_getFile(translation_unit, b(fspath(file_name)))) @property def name(self): """Return the complete file and path name of the file.""" return conf.lib.clang_getFileName(self) @property def time(self): """Return the last modification time of the file.""" return conf.lib.clang_getFileTime(self) def __str__(self): return self.name def __repr__(self): return "<File: %s>" % (self.name) @staticmethod def from_result(res, fn, args): assert isinstance(res, c_object_p) res = File(res) # Copy a reference to the TranslationUnit to prevent premature GC. res._tu = args[0]._tu return res class FileInclusion(object): """ The FileInclusion class represents the inclusion of one source file by another via a '#include' directive or as the input file for the translation unit. This class provides information about the included file, the including file, the location of the '#include' directive and the depth of the included file in the stack. Note that the input file has depth 0. """ def __init__(self, src, tgt, loc, depth): self.source = src self.include = tgt self.location = loc self.depth = depth @property def is_input_file(self): """True if the included file is the input file.""" return self.depth == 0 class CompilationDatabaseError(Exception): """Represents an error that occurred when working with a CompilationDatabase Each error is associated to an enumerated value, accessible under e.cdb_error. Consumers can compare the value with one of the ERROR_ constants in this class. """ # An unknown error occurred ERROR_UNKNOWN = 0 # The database could not be loaded ERROR_CANNOTLOADDATABASE = 1 def __init__(self, enumeration, message): assert isinstance(enumeration, int) if enumeration > 1: raise Exception("Encountered undefined CompilationDatabase error " "constant: %d. Please file a bug to have this " "value supported." % enumeration) self.cdb_error = enumeration Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) class CompileCommand(object): """Represents the compile command used to build a file""" def __init__(self, cmd, ccmds): self.cmd = cmd # Keep a reference to the originating CompileCommands # to prevent garbage collection self.ccmds = ccmds @property def directory(self): """Get the working directory for this CompileCommand""" return conf.lib.clang_CompileCommand_getDirectory(self.cmd) @property def filename(self): """Get the working filename for this CompileCommand""" return conf.lib.clang_CompileCommand_getFilename(self.cmd) @property def arguments(self): """ Get an iterable object providing each argument in the command line for the compiler invocation as a _CXString. Invariant : the first argument is the compiler executable """ length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd) for i in range(length): yield conf.lib.clang_CompileCommand_getArg(self.cmd, i) class CompileCommands(object): """ CompileCommands is an iterable object containing all CompileCommand that can be used for building a specific file. """ def __init__(self, ccmds): self.ccmds = ccmds def __del__(self): conf.lib.clang_CompileCommands_dispose(self.ccmds) def __len__(self): return int(conf.lib.clang_CompileCommands_getSize(self.ccmds)) def __getitem__(self, i): cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i) if not cc: raise IndexError return CompileCommand(cc, self) @staticmethod def from_result(res, fn, args): if not res: return None return CompileCommands(res) class CompilationDatabase(ClangObject): """ The CompilationDatabase is a wrapper class around clang::tooling::CompilationDatabase It enables querying how a specific source file can be built. """ def __del__(self): conf.lib.clang_CompilationDatabase_dispose(self) @staticmethod def from_result(res, fn, args): if not res: raise CompilationDatabaseError(0, "CompilationDatabase loading failed") return CompilationDatabase(res) @staticmethod def fromDirectory(buildDir): """Builds a CompilationDatabase from the database found in buildDir""" errorCode = c_uint() try: cdb = conf.lib.clang_CompilationDatabase_fromDirectory(b(fspath(buildDir)), byref(errorCode)) except CompilationDatabaseError as e: raise CompilationDatabaseError(int(errorCode.value), "CompilationDatabase loading failed") return cdb def getCompileCommands(self, filename): """ Get an iterable object providing all the CompileCommands available to build filename. Returns None if filename is not found in the database. """ return conf.lib.clang_CompilationDatabase_getCompileCommands(self, b(fspath(filename))) def getAllCompileCommands(self): """ Get an iterable object providing all the CompileCommands available from the database. """ return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self) class Token(Structure): """Represents a single token from the preprocessor. Tokens are effectively segments of source code. Source code is first parsed into tokens before being converted into the AST and Cursors. Tokens are obtained from parsed TranslationUnit instances. You currently can't create tokens manually. """ _fields_ = [ ('int_data', c_uint * 4), ('ptr_data', c_void_p) ] @property def spelling(self): """The spelling of this token. This is the textual representation of the token in source. """ return conf.lib.clang_getTokenSpelling(self._tu, self) @property def kind(self): """Obtain the TokenKind of the current token.""" return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) @property def location(self): """The SourceLocation this Token occurs at.""" return conf.lib.clang_getTokenLocation(self._tu, self) @property def extent(self): """The SourceRange this Token occupies.""" return conf.lib.clang_getTokenExtent(self._tu, self) @property def cursor(self): """The Cursor this Token corresponds to.""" cursor = Cursor() cursor._tu = self._tu conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor)) return cursor # Now comes the plumbing to hook up the C library. # Register callback types in common container. callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p, POINTER(SourceLocation), c_uint, py_object) callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object) callbacks['fields_visit'] = CFUNCTYPE(c_int, Cursor, py_object) # Functions strictly alphabetical order. functionList = [ ("clang_annotateTokens", [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]), ("clang_CompilationDatabase_dispose", [c_object_p]), ("clang_CompilationDatabase_fromDirectory", [c_interop_string, POINTER(c_uint)], c_object_p, CompilationDatabase.from_result), ("clang_CompilationDatabase_getAllCompileCommands", [c_object_p], c_object_p, CompileCommands.from_result), ("clang_CompilationDatabase_getCompileCommands", [c_object_p, c_interop_string], c_object_p, CompileCommands.from_result), ("clang_CompileCommands_dispose", [c_object_p]), ("clang_CompileCommands_getCommand", [c_object_p, c_uint], c_object_p), ("clang_CompileCommands_getSize", [c_object_p], c_uint), ("clang_CompileCommand_getArg", [c_object_p, c_uint], _CXString, _CXString.from_result), ("clang_CompileCommand_getDirectory", [c_object_p], _CXString, _CXString.from_result), ("clang_CompileCommand_getFilename", [c_object_p], _CXString, _CXString.from_result), ("clang_CompileCommand_getNumArgs", [c_object_p], c_uint), ("clang_codeCompleteAt", [TranslationUnit, c_interop_string, c_int, c_int, c_void_p, c_int, c_int], POINTER(CCRStructure)), ("clang_codeCompleteGetDiagnostic", [CodeCompletionResults, c_int], Diagnostic), ("clang_codeCompleteGetNumDiagnostics", [CodeCompletionResults], c_int), ("clang_createIndex", [c_int, c_int], c_object_p), ("clang_createTranslationUnit", [Index, c_interop_string], c_object_p), ("clang_CXXConstructor_isConvertingConstructor", [Cursor], bool), ("clang_CXXConstructor_isCopyConstructor", [Cursor], bool), ("clang_CXXConstructor_isDefaultConstructor", [Cursor], bool), ("clang_CXXConstructor_isMoveConstructor", [Cursor], bool), ("clang_CXXField_isMutable", [Cursor], bool), ("clang_CXXMethod_isConst", [Cursor], bool), ("clang_CXXMethod_isDefaulted", [Cursor], bool), ("clang_CXXMethod_isPureVirtual", [Cursor], bool), ("clang_CXXMethod_isStatic", [Cursor], bool), ("clang_CXXMethod_isVirtual", [Cursor], bool), ("clang_CXXRecord_isAbstract", [Cursor], bool), ("clang_EnumDecl_isScoped", [Cursor], bool), ("clang_defaultDiagnosticDisplayOptions", [], c_uint), ("clang_defaultSaveOptions", [TranslationUnit], c_uint), ("clang_disposeCodeCompleteResults", [CodeCompletionResults]), # ("clang_disposeCXTUResourceUsage", # [CXTUResourceUsage]), ("clang_disposeDiagnostic", [Diagnostic]), ("clang_disposeIndex", [Index]), ("clang_disposeString", [_CXString]), ("clang_disposeTokens", [TranslationUnit, POINTER(Token), c_uint]), ("clang_disposeTranslationUnit", [TranslationUnit]), ("clang_equalCursors", [Cursor, Cursor], bool), ("clang_equalLocations", [SourceLocation, SourceLocation], bool), ("clang_equalRanges", [SourceRange, SourceRange], bool), ("clang_equalTypes", [Type, Type], bool), ("clang_formatDiagnostic", [Diagnostic, c_uint], _CXString, _CXString.from_result), ("clang_getArgType", [Type, c_uint], Type, Type.from_result), ("clang_getArrayElementType", [Type], Type, Type.from_result), ("clang_getArraySize", [Type], c_longlong), ("clang_getFieldDeclBitWidth", [Cursor], c_int), ("clang_getCanonicalCursor", [Cursor], Cursor, Cursor.from_cursor_result), ("clang_getCanonicalType", [Type], Type, Type.from_result), ("clang_getChildDiagnostics", [Diagnostic], c_object_p), ("clang_getCompletionAvailability", [c_void_p], c_int), ("clang_getCompletionBriefComment", [c_void_p], _CXString, _CXString.from_result), ("clang_getCompletionChunkCompletionString", [c_void_p, c_int], c_object_p), ("clang_getCompletionChunkKind", [c_void_p, c_int], c_int), ("clang_getCompletionChunkText", [c_void_p, c_int], _CXString, _CXString.from_result), ("clang_getCompletionPriority", [c_void_p], c_int), ("clang_getCString", [_CXString], c_interop_string, c_interop_string.to_python_string), ("clang_getCursor", [TranslationUnit, SourceLocation], Cursor), ("clang_getCursorAvailability", [Cursor], c_int), ("clang_getCursorDefinition", [Cursor], Cursor, Cursor.from_result), ("clang_getCursorDisplayName", [Cursor], _CXString, _CXString.from_result), ("clang_getCursorExtent", [Cursor], SourceRange), ("clang_getCursorLexicalParent", [Cursor], Cursor, Cursor.from_cursor_result), ("clang_getCursorLocation", [Cursor], SourceLocation), ("clang_getCursorReferenced", [Cursor], Cursor, Cursor.from_result), ("clang_getCursorReferenceNameRange", [Cursor, c_uint, c_uint], SourceRange), ("clang_getCursorResultType", [Cursor], Type, Type.from_result), ("clang_getCursorSemanticParent", [Cursor], Cursor, Cursor.from_cursor_result), ("clang_getCursorSpelling", [Cursor], _CXString, _CXString.from_result), ("clang_getCursorType", [Cursor], Type, Type.from_result), ("clang_getCursorUSR", [Cursor], _CXString, _CXString.from_result), ("clang_Cursor_getMangling", [Cursor], _CXString, _CXString.from_result), # ("clang_getCXTUResourceUsage", # [TranslationUnit], # CXTUResourceUsage), ("clang_getCXXAccessSpecifier", [Cursor], c_uint), ("clang_getDeclObjCTypeEncoding", [Cursor], _CXString, _CXString.from_result), ("clang_getDiagnostic", [c_object_p, c_uint], c_object_p), ("clang_getDiagnosticCategory", [Diagnostic], c_uint), ("clang_getDiagnosticCategoryText", [Diagnostic], _CXString, _CXString.from_result), ("clang_getDiagnosticFixIt", [Diagnostic, c_uint, POINTER(SourceRange)], _CXString, _CXString.from_result), ("clang_getDiagnosticInSet", [c_object_p, c_uint], c_object_p), ("clang_getDiagnosticLocation", [Diagnostic], SourceLocation), ("clang_getDiagnosticNumFixIts", [Diagnostic], c_uint), ("clang_getDiagnosticNumRanges", [Diagnostic], c_uint), ("clang_getDiagnosticOption", [Diagnostic, POINTER(_CXString)], _CXString, _CXString.from_result), ("clang_getDiagnosticRange", [Diagnostic, c_uint], SourceRange), ("clang_getDiagnosticSeverity", [Diagnostic], c_int), ("clang_getDiagnosticSpelling", [Diagnostic], _CXString, _CXString.from_result), ("clang_getElementType", [Type], Type, Type.from_result), ("clang_getEnumConstantDeclUnsignedValue", [Cursor], c_ulonglong), ("clang_getEnumConstantDeclValue", [Cursor], c_longlong), ("clang_getEnumDeclIntegerType", [Cursor], Type, Type.from_result), ("clang_getFile", [TranslationUnit, c_interop_string], c_object_p), ("clang_getFileName", [File], _CXString, _CXString.from_result), ("clang_getFileTime", [File], c_uint), ("clang_getIBOutletCollectionType", [Cursor], Type, Type.from_result), ("clang_getIncludedFile", [Cursor], c_object_p, File.from_result), ("clang_getInclusions", [TranslationUnit, callbacks['translation_unit_includes'], py_object]), ("clang_getInstantiationLocation", [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint), POINTER(c_uint)]), ("clang_getLocation", [TranslationUnit, File, c_uint, c_uint], SourceLocation), ("clang_getLocationForOffset", [TranslationUnit, File, c_uint], SourceLocation), ("clang_getNullCursor", None, Cursor), ("clang_getNumArgTypes", [Type], c_uint), ("clang_getNumCompletionChunks", [c_void_p], c_int), ("clang_getNumDiagnostics", [c_object_p], c_uint), ("clang_getNumDiagnosticsInSet", [c_object_p], c_uint), ("clang_getNumElements", [Type], c_longlong), ("clang_getNumOverloadedDecls", [Cursor], c_uint), ("clang_getOverloadedDecl", [Cursor, c_uint], Cursor, Cursor.from_cursor_result), ("clang_getPointeeType", [Type], Type, Type.from_result), ("clang_getRange", [SourceLocation, SourceLocation], SourceRange), ("clang_getRangeEnd", [SourceRange], SourceLocation), ("clang_getRangeStart", [SourceRange], SourceLocation), ("clang_getResultType", [Type], Type, Type.from_result), ("clang_getSpecializedCursorTemplate", [Cursor], Cursor, Cursor.from_cursor_result), ("clang_getTemplateCursorKind", [Cursor], c_uint), ("clang_getTokenExtent", [TranslationUnit, Token], SourceRange), ("clang_getTokenKind", [Token], c_uint), ("clang_getTokenLocation", [TranslationUnit, Token], SourceLocation), ("clang_getTokenSpelling", [TranslationUnit, Token], _CXString, _CXString.from_result), ("clang_getTranslationUnitCursor", [TranslationUnit], Cursor, Cursor.from_result), ("clang_getTranslationUnitSpelling", [TranslationUnit], _CXString, _CXString.from_result), ("clang_getTUResourceUsageName", [c_uint], c_interop_string, c_interop_string.to_python_string), ("clang_getTypeDeclaration", [Type], Cursor, Cursor.from_result), ("clang_getTypedefDeclUnderlyingType", [Cursor], Type, Type.from_result), ("clang_getTypedefName", [Type], _CXString, _CXString.from_result), ("clang_getTypeKindSpelling", [c_uint], _CXString, _CXString.from_result), ("clang_getTypeSpelling", [Type], _CXString, _CXString.from_result), ("clang_hashCursor", [Cursor], c_uint), ("clang_isAttribute", [CursorKind], bool), ("clang_isConstQualifiedType", [Type], bool), ("clang_isCursorDefinition", [Cursor], bool), ("clang_isDeclaration", [CursorKind], bool), ("clang_isExpression", [CursorKind], bool), ("clang_isFileMultipleIncludeGuarded", [TranslationUnit, File], bool), ("clang_isFunctionTypeVariadic", [Type], bool), ("clang_isInvalid", [CursorKind], bool), ("clang_isPODType", [Type], bool), ("clang_isPreprocessing", [CursorKind], bool), ("clang_isReference", [CursorKind], bool), ("clang_isRestrictQualifiedType", [Type], bool), ("clang_isStatement", [CursorKind], bool), ("clang_isTranslationUnit", [CursorKind], bool), ("clang_isUnexposed", [CursorKind], bool), ("clang_isVirtualBase", [Cursor], bool), ("clang_isVolatileQualifiedType", [Type], bool), ("clang_parseTranslationUnit", [Index, c_interop_string, c_void_p, c_int, c_void_p, c_int, c_int], c_object_p), ("clang_reparseTranslationUnit", [TranslationUnit, c_int, c_void_p, c_int], c_int), ("clang_saveTranslationUnit", [TranslationUnit, c_interop_string, c_uint], c_int), ("clang_tokenize", [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]), ("clang_visitChildren", [Cursor, callbacks['cursor_visit'], py_object], c_uint), ("clang_Cursor_getNumArguments", [Cursor], c_int), ("clang_Cursor_getArgument", [Cursor, c_uint], Cursor, Cursor.from_result), ("clang_Cursor_getNumTemplateArguments", [Cursor], c_int), ("clang_Cursor_getTemplateArgumentKind", [Cursor, c_uint], TemplateArgumentKind.from_id), ("clang_Cursor_getTemplateArgumentType", [Cursor, c_uint], Type, Type.from_result), ("clang_Cursor_getTemplateArgumentValue", [Cursor, c_uint], c_longlong), ("clang_Cursor_getTemplateArgumentUnsignedValue", [Cursor, c_uint], c_ulonglong), ("clang_Cursor_isAnonymous", [Cursor], bool), ("clang_Cursor_isBitField", [Cursor], bool), ("clang_Cursor_getBriefCommentText", [Cursor], _CXString, _CXString.from_result), ("clang_Cursor_getRawCommentText", [Cursor], _CXString, _CXString.from_result), ("clang_Cursor_getOffsetOfField", [Cursor], c_longlong), ("clang_Type_getAlignOf", [Type], c_longlong), ("clang_Type_getClassType", [Type], Type, Type.from_result), ("clang_Type_getNumTemplateArguments", [Type], c_int), ("clang_Type_getTemplateArgumentAsType", [Type, c_uint], Type, Type.from_result), ("clang_Type_getOffsetOf", [Type, c_interop_string], c_longlong), ("clang_Type_getSizeOf", [Type], c_longlong), ("clang_Type_getCXXRefQualifier", [Type], c_uint), ("clang_Type_getNamedType", [Type], Type, Type.from_result), ("clang_Type_visitFields", [Type, callbacks['fields_visit'], py_object], c_uint), ] class LibclangError(Exception): def __init__(self, message): self.m = message def __str__(self): return self.m def register_function(lib, item, ignore_errors): # A function may not exist, if these bindings are used with an older or # incompatible version of libclang.so. try: func = getattr(lib, item[0]) except AttributeError as e: msg = str(e) + ". Please ensure that your python bindings are "\ "compatible with your libclang.so version." if ignore_errors: return raise LibclangError(msg) if len(item) >= 2: func.argtypes = item[1] if len(item) >= 3: func.restype = item[2] if len(item) == 4: func.errcheck = item[3] def register_functions(lib, ignore_errors): """Register function prototypes with a libclang library instance. This must be called as part of library instantiation so Python knows how to call out to the shared library. """ def register(item): return register_function(lib, item, ignore_errors) for f in functionList: register(f) class Config(object): library_path = None library_file = None compatibility_check = True loaded = False @staticmethod def set_library_path(path): """Set the path in which to search for libclang""" if Config.loaded: raise Exception("library path must be set before before using " \ "any other functionalities in libclang.") Config.library_path = fspath(path) @staticmethod def set_library_file(filename): """Set the exact location of libclang""" if Config.loaded: raise Exception("library file must be set before before using " \ "any other functionalities in libclang.") Config.library_file = fspath(filename) @staticmethod def set_compatibility_check(check_status): """ Perform compatibility check when loading libclang The python bindings are only tested and evaluated with the version of libclang they are provided with. To ensure correct behavior a (limited) compatibility check is performed when loading the bindings. This check will throw an exception, as soon as it fails. In case these bindings are used with an older version of libclang, parts that have been stable between releases may still work. Users of the python bindings can disable the compatibility check. This will cause the python bindings to load, even though they are written for a newer version of libclang. Failures now arise if unsupported or incompatible features are accessed. The user is required to test themselves if the features they are using are available and compatible between different libclang versions. """ if Config.loaded: raise Exception("compatibility_check must be set before before " \ "using any other functionalities in libclang.") Config.compatibility_check = check_status @CachedProperty def lib(self): lib = self.get_cindex_library() register_functions(lib, not Config.compatibility_check) Config.loaded = True return lib def get_filename(self): if Config.library_file: return Config.library_file import platform name = platform.system() if name == 'Darwin': file = 'libclang.dylib' elif name == 'Windows': file = 'libclang.dll' else: file = 'libclang.so' if Config.library_path: file = Config.library_path + '/' + file return file def get_cindex_library(self): try: library = cdll.LoadLibrary(self.get_filename()) except OSError as e: msg = str(e) + ". To provide a path to libclang use " \ "Config.set_library_path() or " \ "Config.set_library_file()." raise LibclangError(msg) return library def function_exists(self, name): try: getattr(self.lib, name) except AttributeError: return False return True def register_enumerations(): for name, value in clang.enumerations.TokenKinds: TokenKind.register(value, name) conf = Config() register_enumerations() __all__ = [ 'AvailabilityKind', 'Config', 'CodeCompletionResults', 'CompilationDatabase', 'CompileCommands', 'CompileCommand', 'CursorKind', 'Cursor', 'Diagnostic', 'File', 'FixIt', 'Index', 'LinkageKind', 'SourceLocation', 'SourceRange', 'TLSKind', 'TokenKind', 'Token', 'TranslationUnitLoadError', 'TranslationUnit', 'TypeKind', 'Type', ]
arakashic/chromatica.nvim
rplugin/python3/clang/cindex.py
Python
mit
127,932
# -*- coding: utf-8 -*- import win32com.client from pywintypes import com_error from input import GRD_FILE_NAME acad = win32com.client.Dispatch("AutoCAD.Application") doc = acad.ActiveDocument # Document object def get_num(s): return float("".join(char for char in s if char.isdigit() or char in ["-", "+", "."])) f = open(GRD_FILE_NAME, "r") line = f.readline() while 1: try: line = f.readline() section = line.strip().split()[0] origin = doc.Utility.GetPoint(Prompt="Select origin of section %s (0,0 to skip this section):" % (section)) if origin[0] == origin[1] == 0.0: while line[0] != "*": line = f.readline() continue originHeight, point_clicked = doc.Utility.GetEntity(None, None, Prompt="Select text that includes origin height:") originHeight = get_num(originHeight.TextString) command = "pl " line = f.readline() while line[0] != "*": offset, h = line.strip().split() offset = float(offset) h = float(h) x = origin[0] + offset y = origin[1] + (h - originHeight) command = command + "%s,%s " % (x, y) line = f.readline() print "Drawing section %s" % (section) doc.SendCommand(command + " ") except ValueError: # raised when trying to read past EOF (why not IOError? - need to think on it) print "Program ended on ValueError" break except com_error: print "Program ended on com_error" break
Jimaklas/grd2section
grd2section.py
Python
gpl-3.0
1,572
#!/usr/bin/python #encoding: utf8 import mr_gov_il import time import pprint import json import os import copy import shutil import requesocks as requests #import requests from scrapy.selector import Selector import urllib3 import sys from datetime import datetime, timedelta class tender_extended_data_web_page(mr_gov_il.extended_data_web_page_base): def extract_page_data( self ): #start_time = time.time() sel = Selector(text=self.response.text) ret = {} if self.publication_id is not None: ret['publication_id'] = self.publication_id found_fields = 0 for field_name, xpath in [('description', '//*[@id="ctl00_PlaceHolderMain_lbl_PublicationName"]'), ('publisher', '//*[@id="ctl00_PlaceHolderMain_lbl_Publisher"]'), ('publish_date', '//*[@id="ctl00_PlaceHolderMain_lbl_PublishDate"]'), ('publication_id', '//*[@id="ctl00_PlaceHolderMain_lbl_SERIAL_NUMBER"]'), ('status', '//*[@id="ctl00_PlaceHolderMain_lbl_PublicationSTATUS"]'), ('last_update_date', '//*[@id="ctl00_PlaceHolderMain_lbl_UpdateDate"]'), ('subjects', '//*[@id="ctl00_PlaceHolderMain_lbl_PublicationSUBJECT"]'), ('claim_date', '//*[@id="ctl00_PlaceHolderMain_lbl_ClaimDate"]') ]: if len(sel.xpath(xpath+'/text()')) == 0: ret[field_name] = None else: found_fields += 1 try: ret[field_name] = sel.xpath(xpath+'/text()')[0].extract() except: print "failed %s %s" % (field_name, url) raise if found_fields == 0: raise mr_gov_il.NoSuchElementException('found_fields == 0') if None in [ret["last_update_date"]]: raise mr_gov_il.NoSuchElementException("last_update_date") ret['url'] = self.url ret['documents'] = [] links = sel.xpath('//*[@id="ctl00_PlaceHolderMain_pnl_Files"]/div/div/div[2]/a') update_times = sel.xpath('//*[@id="ctl00_PlaceHolderMain_pnl_Files"]/div/div/div[1]') if len(links) != len(update_times): raise mr_gov_il.NoSuchElementException('len(links) != len(update_times)') for i in xrange( len(links) ): ret['documents'].append( {'description':links[i].xpath('text()')[0].extract(), 'link':'http://www.mr.gov.il' + links[i].xpath('@href')[0].extract(), 'update_time':update_times.xpath('text()')[0].extract() } ) #print 'parsed exended data in %f secs' % (time.time() - start_time) return ret class tender_search_web_page(mr_gov_il.search_web_page_base): extended_data_web_page_cls = tender_extended_data_web_page search_page_url = 'http://www.mr.gov.il/OfficesTenders/Pages/SearchOfficeTenders.aspx' publisher_option_xpath = '//*[@id="ctl00_m_g_7b9ec4d5_a2ee_4fc4_8523_cd0a65f2d290_ctl00_ddlPublisher"]/option' results_table_base_xpath = '//*[@id="ctl00_m_g_7b9ec4d5_a2ee_4fc4_8523_cd0a65f2d290_ctl00_grvMichrazim"]' url_xpath = results_table_base_xpath + '/tr[%d]/td[2]/a/@href' expected_table_columns = 7 def fill_form( self, d={} ): form_data = { '__EVENTTARGET':'', '__EVENTARGUMENT':'', } for form_data_elem in self.must_exist_xpath('//*[@id="aspnetForm"]/input'): form_data[form_data_elem.xpath('@name')[0].extract()] = form_data_elem.xpath('@value')[0].extract() for form_data_elem in self.must_exist_xpath('//*[@id="WebPartWPQ3"]//select'): form_data[form_data_elem.xpath('@name')[0].extract()] = 0 for form_data_elem in self.must_exist_xpath('//*[@id="WebPartWPQ3"]//input'): form_data[form_data_elem.xpath('@name')[0].extract()] = '' if 'publisher_index' in self.search_params: form_data['ctl00$m$g_7b9ec4d5_a2ee_4fc4_8523_cd0a65f2d290$ctl00$ddlPublisher'] = self.search_params['publisher_index'] form_data.update( d ) # the clear button was not clicked form_data.pop( 'ctl00$m$g_7b9ec4d5_a2ee_4fc4_8523_cd0a65f2d290$ctl00$btnClear' ) # select all kinds of tenders form_data['ctl00$m$g_7b9ec4d5_a2ee_4fc4_8523_cd0a65f2d290$ctl00$chkCanceled'] = 'on' form_data['ctl00$m$g_7b9ec4d5_a2ee_4fc4_8523_cd0a65f2d290$ctl00$chkUpdate'] = 'on' form_data['ctl00$m$g_7b9ec4d5_a2ee_4fc4_8523_cd0a65f2d290$ctl00$chkNew'] = 'on' form_data['ctl00$m$g_7b9ec4d5_a2ee_4fc4_8523_cd0a65f2d290$ctl00$chkEnded'] = 'on' form_data['SearchFreeText'] = u'חפש' form_data['ctl00_PlaceHolderHorizontalNav_RadMenu1_ClientState'] = '' if form_data['__EVENTTARGET']: # if a page number was presses, the search button was not clicked form_data.pop( 'ctl00$m$g_7b9ec4d5_a2ee_4fc4_8523_cd0a65f2d290$ctl00$btnSearch' ) # for k in sorted(form_data.keys()): # v = form_data[k] # if len(str(v)) < 20: # print k, '=', repr(v) # else: # print k, '=', repr(v)[:20] + '...' self.request( 'post', data=form_data ) @classmethod def process_record( cls, record ): # empty_str_is_none( record, 'supplier_id' ) # field_to_int( record, 'supplier_id' ) # zero_is_none( record, 'supplier_id' ) cls.format_documents_time( record ) record['claim_time'], record['claim_date'] = record['claim_date'].split(' ') return record if __name__ == "__main__": from optparse import OptionParser parser = OptionParser( usage='usage: %prog [options] <output filename>' ) parser.add_option("--rescrape", dest="rescrape", action='store', help='rescrape the urls of a previous scrape', metavar='old_json', default=None) parser.add_option("--since", dest="since", action='store', help='since a date or one of: yesterday, last_week, last_year, all_time', default=None) (options, args) = parser.parse_args() if len(args) != 1: parser.error( 'must provide an output filename' ) if options.rescrape: tender_search_web_page.rescrape( input_filename=options.rescrape, output_filename=args[0] ) else: tender_search_web_page.scrape( output_filename=args[0], since=options.since )
OpenBudget/open-budget-data
tenders/tenders_scraper.py
Python
mit
6,597
# # Copyright (c) 2015 Intel Corporation # # Author: Julio Montes <[email protected]> # Author: Victor Morales <[email protected]> # # 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 mock import testtools from clearstack.sequence import Sequence class SequenceTest(testtools.TestCase): def setUp(self): super(SequenceTest, self).setUp() def test_run(self): mock_function = mock.Mock(return_value=False) mock_function.__name__ = 'Bar' seq = Sequence('test', mock_function) self.assertRaises(Exception, seq.run) seq = Sequence('test', mock_function, ["subsequence"]) self.assertRaises(Exception, seq.run)
clearlinux/clearstack
clearstack/tests/test_sequence.py
Python
apache-2.0
1,191
#!/usr/bin/env python # Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies build of an executable in three different configurations. """ import TestGyp test = TestGyp.TestGyp(formats=['msvs']) test.run_gyp('configurations.gyp') for platform in ['Win32', 'x64']: test.set_configuration('Debug|%s' % platform) test.build('configurations.gyp', rebuild=True) try: test.run_built_executable('configurations', stdout=('Running %s\n' % platform)) except WindowsError, e: # Assume the exe is 64-bit if it can't load on 32-bit systems. if platform == 'x64' and e.errno == 193: continue raise test.pass_test()
gvaf/breakpad
src/tools/gyp/test/configurations/x64/gyptest-x86.py
Python
bsd-3-clause
783
#!/usr/bin/env python # coding: utf-8 """MikroTik RouterOS backup and change manager""" import sys import re import socket import os HAS_SSHCLIENT = True SHELLMODE = False SHELLDEFS = { 'username': 'admin', 'password': '', 'timeout': 30, 'port': 22, 'export_dir': None, 'export_file' : None, 'backup_dir': None, 'timestamp': False, 'hide_sensitive': True, 'local_file': False, 'verbose': False } MIKROTIK_MODULE = '[github.com/nekitamo/ansible-mikrotik] v2017.03.28' DOCUMENTATION = """ --- module: mikrotik_export short_description: MikroTik RouterOS configuration export description: - Exports full router configuration to a text file in export directory - By default no local export file is created on the router (enable with local_file: yes) - If you create router user 'ansible' with ssh-key you can omit username/password in playbooks return_data: - identity - software_id - export_dir - export_file - backup_dir - backup_files options: export_dir: description: - Directory where export_file is written after export, created if not existing required: true default: null export_file: description: - The name of the exported file, existing files are overwritten required: false default: <identity>_<software_id>.rsc backup_dir: description: - Directory where all backups are downloaded, existing files are not overwritten required: false default: null timestamp: description: - Leave default timestamp in export file (first line), disabled for version tracking required: false default: false hide_sensitive: description: - Do not include passwords or other sensitive info in exported configuration file required: false default: true local_file: description: - Also write config as local file on device (ansible-export.rsc) before export - Exports via local_file option allways include timestamp in first line required: false default: false verbose: description: - Export verbose config including default option values (large export file) required: false default: false port: description: - SSH listening port of the MikroTik device required: false default: 22 hostname: description: - IP Address or hostname of the MikroTik device required: true default: null username: description: - Username used to login to the device required: false default: ansible password: description: - Password used to login to the device required: false default: null """ EXAMPLES = """ # example playbook --- - name: Export Mikrotik RouterOS config hosts: mikrotik_routers gather_facts: false connection: local tasks: - name: Export router configurations mikrotik_export: hostname: "{{ inventory_hostname }}" export_dir: exports hide_sensitive: false timestamp: true """ RETURN = """ identity: description: Returns device identity (system identity print) returned: always type: string software_id: description: Returns device software_id (system identity print) returned: always type: string export_dir: description: Returns full os path for export directory returned: always type: string export_file: description: Returns filename of exported configuration returned: always type: string backup_dir: description: Returns full os path where backups were downloaded returned: if backup_dir option was used type: string backup_files: description: Returns list of downloaded backups returned: if backup_dir option was used type: list """ SHELL_USAGE = """ mikrotik_export.py --hostname=<hostname> --export_dir=<path> [--export_file=<filename>] [--backup_dir=<path>] [--timestamp] [--hide_sensitive=no] [--verbose] [--local_file] [--timeout=<timeout>] [--port=<port>] [--username=<username>] [--password=<password>] """ try: import paramiko except ImportError as import_error: HAS_SSHCLIENT = False try: from ansible.module_utils.basic import AnsibleModule except ImportError: SHELLMODE = True else: # ansible parameters on stdin? if sys.stdin.isatty(): SHELLMODE = True def safe_fail(module, device=None, **kwargs): """closes device before module fail""" if device: device.close() module.fail_json(**kwargs) def safe_exit(module, device=None, **kwargs): """closes device before module exit""" if device: device.close() module.exit_json(**kwargs) def parse_opts(cmdline): """returns SHELLMODE command line options as dict""" options = SHELLDEFS for opt in cmdline: if opt.startswith('--'): try: arg, val = opt.split("=", 1) except ValueError: arg = opt val = True else: if val.lower() in ('no', 'false', '0'): val = False elif val.lower() in ('yes', 'true', '1'): val = True arg = arg[2:] if arg in options or arg == 'hostname': options[arg] = val else: print SHELL_USAGE sys.exit("Unknown option: --%s" % arg) if 'hostname' not in options: print SHELL_USAGE sys.exit("Hostname is required, specify with --hostname=<hostname>") return options def device_connect(module, device, rosdev): """open ssh connection with or without ssh keys""" try: rosdev['hostname'] = socket.gethostbyname(rosdev['hostname']) except socket.gaierror as dns_error: if SHELLMODE: sys.exit("Hostname error: " + str(dns_error)) safe_fail(module, device, msg=str(dns_error), description='error getting device address from hostname') if SHELLMODE: sys.stdout.write("Opening SSH connection to %s:%s... " % (rosdev['hostname'], rosdev['port'])) sys.stdout.flush() try: device.connect(rosdev['hostname'], username=rosdev['username'], password=rosdev['password'], port=rosdev['port'], timeout=rosdev['timeout']) except Exception: try: device.connect(rosdev['hostname'], username=rosdev['username'], password=rosdev['password'], port=rosdev['port'], timeout=rosdev['timeout'], allow_agent=False, look_for_keys=False) except Exception as ssh_error: if SHELLMODE: sys.exit("failed!\nSSH error: " + str(ssh_error)) safe_fail(module, device, msg=str(ssh_error), description='error opening ssh connection to %s' % rosdev['hostname']) if SHELLMODE: print "succes." def sshcmd(module, device, timeout, command): """executes a command on the device, returns string""" try: _stdin, stdout, _stderr = device.exec_command(command, timeout=timeout) except Exception as ssh_error: if SHELLMODE: sys.exit("SSH command error: " + str(ssh_error)) safe_fail(module, device, msg=str(ssh_error), description='SSH error while executing command') response = stdout.read() if 'bad command name ' not in response: if 'syntax error ' not in response: if 'failure: ' not in response: return response.rstrip() if SHELLMODE: print "Command: " + str(command) sys.exit("Error: " + str(response)) safe_fail(module, device, msg=str(ssh_error), description='bad command name or syntax error') def parse_terse(device, key, command): """executes a command and returns list""" _stdin, stdout, _stderr = device.exec_command(command) vals = [] for line in stdout.readlines(): if key in line: val = line.split(key+'=')[1] vals.append(val.split(' ')[0]) return vals def parse_facts(device, command, pfx=""): """executes a command and returns dict""" _stdin, stdout, _stderr = device.exec_command(command) facts = {} for line in stdout.readlines(): if ':' in line: fact, value = line.partition(":")[::2] fact = fact.replace('-', '_') if pfx not in fact: facts[pfx + fact.strip()] = str(value.strip()) else: facts[fact.strip()] = str(value.strip()) return facts def vercmp(ver1, ver2): """quick and dirty version comparison from stackoverflow""" def normalize(ver): return [int(x) for x in re.sub(r'(\.0+)*$', '', ver).split(".")] return cmp(normalize(ver1), normalize(ver2)) def main(): rosdev = {} backup_files = [] cmd_timeout = 30 changed = False if not SHELLMODE: module = AnsibleModule( argument_spec=dict( export_dir=dict(required=True, type='path'), export_file=dict(required=False, type='str'), backup_dir=dict(required=False, type='path'), timestamp=dict(default=False, type='bool'), hide_sensitive=dict(default=True, type='bool'), local_file=dict(default=False, type='bool'), verbose=dict(default=False, type='bool'), hostname=dict(required=True), username=dict(default='ansible', type='str'), password=dict(default='', type='str', no_log=True), port=dict(default=22, type='int'), timeout=dict(default=30, type='float') ), supports_check_mode=False ) if not HAS_SSHCLIENT: safe_fail(module, msg='There was a problem loading module: ', error=str(import_error)) export_dir = os.path.expanduser(module.params['export_dir']) export_file = module.params['export_file'] backup_dir = module.params['backup_dir'] timestamp = module.params['timestamp'] hide_sensitive = module.params['hide_sensitive'] local_file = module.params['local_file'] verbose = module.params['verbose'] rosdev['hostname'] = module.params['hostname'] rosdev['username'] = module.params['username'] rosdev['password'] = module.params['password'] rosdev['port'] = module.params['port'] rosdev['timeout'] = module.params['timeout'] else: if not HAS_SSHCLIENT: sys.exit("SSH client error: " + str(import_error)) if not SHELLOPTS['export_dir']: print SHELL_USAGE sys.exit("export_dir required, specify with --export_dir=<path>") export_dir = os.path.expanduser(SHELLOPTS['export_dir']) rosdev['hostname'] = SHELLOPTS['hostname'] rosdev['username'] = SHELLOPTS['username'] rosdev['password'] = SHELLOPTS['password'] rosdev['port'] = SHELLOPTS['port'] rosdev['timeout'] = SHELLOPTS['timeout'] hide_sensitive = SHELLOPTS['hide_sensitive'] export_file = SHELLOPTS['export_file'] backup_dir = SHELLOPTS['backup_dir'] timestamp = SHELLOPTS['timestamp'] local_file = SHELLOPTS['local_file'] verbose = SHELLOPTS['verbose'] module = None export_dir = os.path.realpath(export_dir) if not os.path.exists(export_dir): try: os.mkdir(export_dir, 0775) except OSError as mkdir_error: if SHELLMODE: sys.exit("Export directory error: " + str(mkdir_error)) safe_fail(module, msg=str(mkdir_error), description='error creating export directory') device = paramiko.SSHClient() device.set_missing_host_key_policy(paramiko.AutoAddPolicy()) device_connect(module, device, rosdev) version = sshcmd(module, device, cmd_timeout, ":put [/system resource get version]") response = sshcmd(module, device, cmd_timeout, "system identity print") identity = str(response.split(": ")[1]) identity = identity.strip() software_id = sshcmd(module, device, cmd_timeout, ":put [ /system license get software-id ]") if not software_id: software_id = rosdev['hostname'] if not export_file: export_file = identity + "_" + software_id + ".rsc" exportfull = os.path.join(export_dir, export_file) exportcmd = "export" if hide_sensitive: exportcmd += " hide-sensitive" if verbose: exportcmd += " verbose" if local_file: exportcmd += " file=ansible-export" changed = True response = sshcmd(module, device, cmd_timeout, exportcmd) if local_file: sftp = device.open_sftp() sftp.get("/ansible-export.rsc", exportfull) sftp.close() else: try: with open(exportfull, 'w') as exp: exp.write("# " + rosdev['username'] + "@" + identity + ", RouterOS " + version +": " + exportcmd + "\n") if timestamp: exp.write(response) else: no_ts = response.splitlines(1)[1:] exp.writelines(no_ts) exp.close() except Exception as export_error: if SHELLMODE: device.close() sys.exit("Export file error: " + str(export_error)) safe_fail(module, device, msg=str(export_error), description='error writing to export file') if backup_dir: backup_dir = os.path.expanduser(backup_dir) backup_dir = os.path.realpath(backup_dir) if not os.path.exists(backup_dir): try: os.mkdir(backup_dir, 0775) except OSError as mkdir_error: if SHELLMODE: device.close() sys.exit("Backup directory error: " + str(mkdir_error)) safe_fail(module, device, msg=str(mkdir_error), description='error creating backup directory') sftp = device.open_sftp() listdir = sftp.listdir() for item in listdir: if item.endswith('.backup'): bkp = os.path.join(backup_dir, item) if not os.path.exists(bkp): sftp.get(item, bkp) backup_files.append(item) sftp.close() if SHELLMODE: device.close() print "export_dir: %s" % export_dir print "export_file: %s" % export_file if backup_dir: print "backup_dir: %s" % backup_dir print "backup_files: %s" % ', '.join(backup_files) sys.exit(0) safe_exit(module, device, changed=changed, export_file=export_file, export_dir=export_dir, backup_files=backup_files, backup_dir=backup_dir, identity=identity, software_id=software_id) if __name__ == '__main__': if len(sys.argv) > 1 or SHELLMODE: print "Ansible MikroTik Library %s" % MIKROTIK_MODULE SHELLOPTS = parse_opts(sys.argv) SHELLMODE = True main()
nekitamo/ansible-mikrotik
library/mikrotik_export.py
Python
gpl-3.0
15,608
# # Python documentation build configuration file # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). import sys, os, time sys.path.append(os.path.abspath('tools/extensions')) # General configuration # --------------------- extensions = ['sphinx.ext.coverage', 'sphinx.ext.doctest', 'pyspecific', 'c_annotations'] # General substitutions. project = 'Python' copyright = '1990-%s, Python Software Foundation' % time.strftime('%Y') # We look for the Include/patchlevel.h file in the current Python source tree # and replace the values accordingly. import patchlevel version, release = patchlevel.get_version_info() # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # By default, highlight as Python 3. highlight_language = 'python3' # Require Sphinx 1.2 for build. needs_sphinx = '1.2' # Options for HTML output # ----------------------- # Use our custom theme. html_theme = 'pydoctheme' html_theme_path = ['tools'] html_theme_options = {'collapsiblesidebar': True} # Short title used e.g. for <title> HTML tags. html_short_title = '%s Documentation' % release # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # Path to find HTML templates. templates_path = ['tools/templates'] # Custom sidebar templates, filenames relative to this file. html_sidebars = { 'index': 'indexsidebar.html', } # Additional templates that should be rendered to pages. html_additional_pages = { 'download': 'download.html', 'index': 'indexcontent.html', } # Output an OpenSearch description file. html_use_opensearch = 'https://docs.python.org/' + version # Additional static files. html_static_path = ['tools/static'] # Output file base name for HTML help builder. htmlhelp_basename = 'python' + release.replace('.', '') # Split the index html_split_index = True # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). latex_paper_size = 'a4' # The font size ('10pt', '11pt' or '12pt'). latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). _stdauthor = r'Guido van Rossum\\and the Python development team' latex_documents = [ ('c-api/index', 'c-api.tex', 'The Python/C API', _stdauthor, 'manual'), ('distributing/index', 'distributing.tex', 'Distributing Python Modules', _stdauthor, 'manual'), ('extending/index', 'extending.tex', 'Extending and Embedding Python', _stdauthor, 'manual'), ('installing/index', 'installing.tex', 'Installing Python Modules', _stdauthor, 'manual'), ('library/index', 'library.tex', 'The Python Library Reference', _stdauthor, 'manual'), ('reference/index', 'reference.tex', 'The Python Language Reference', _stdauthor, 'manual'), ('tutorial/index', 'tutorial.tex', 'Python Tutorial', _stdauthor, 'manual'), ('using/index', 'using.tex', 'Python Setup and Usage', _stdauthor, 'manual'), ('faq/index', 'faq.tex', 'Python Frequently Asked Questions', _stdauthor, 'manual'), ('whatsnew/' + version, 'whatsnew.tex', 'What\'s New in Python', 'A. M. Kuchling', 'howto'), ] # Collect all HOWTOs individually latex_documents.extend(('howto/' + fn[:-4], 'howto-' + fn[:-4] + '.tex', '', _stdauthor, 'howto') for fn in os.listdir('howto') if fn.endswith('.rst') and fn != 'index.rst') # Additional stuff for the LaTeX preamble. latex_preamble = r''' \authoraddress{ \strong{Python Software Foundation}\\ Email: \email{[email protected]} } \let\Verbatim=\OriginalVerbatim \let\endVerbatim=\endOriginalVerbatim ''' # Documents to append as an appendix to all manuals. latex_appendices = ['glossary', 'about', 'license', 'copyright'] # Get LaTeX to handle Unicode correctly latex_elements = {'inputenc': r'\usepackage[utf8x]{inputenc}', 'utf8extra': ''} # Options for the coverage checker # -------------------------------- # The coverage checker will ignore all modules/functions/classes whose names # match any of the following regexes (using re.match). coverage_ignore_modules = [ r'[T|t][k|K]', r'Tix', r'distutils.*', ] coverage_ignore_functions = [ 'test($|_)', ] coverage_ignore_classes = [ ] # Glob patterns for C source files for C API coverage, relative to this directory. coverage_c_path = [ '../Include/*.h', ] # Regexes to find C items in the source files. coverage_c_regexes = { 'cfunction': (r'^PyAPI_FUNC\(.*\)\s+([^_][\w_]+)'), 'data': (r'^PyAPI_DATA\(.*\)\s+([^_][\w_]+)'), 'macro': (r'^#define ([^_][\w_]+)\(.*\)[\s|\\]'), } # The coverage checker will ignore all C items whose names match these regexes # (using re.match) -- the keys must be the same as in coverage_c_regexes. coverage_ignore_c_items = { # 'cfunction': [...] } # Options for the link checker # ---------------------------- # Ignore certain URLs. linkcheck_ignore = [r'https://bugs.python.org/(issue)?\d+', # Ignore PEPs for now, they all have permanent redirects. r'http://www.python.org/dev/peps/pep-\d+'] # Options for extensions # ---------------------- # Relative filename of the reference count data file. refcount_file = 'data/refcounts.dat'
robobrobro/ballin-octo-shame
lib/Python-3.4.3/Doc/conf.py
Python
mit
5,736
from django.db import models from django.core.urlresolvers import reverse from django.conf import settings import misaka from groups.models import Group # Create your models here. # POSTS MODELS.PY from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name='posts') created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name='posts', null=True, blank=True) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('posts:single', kwargs={'username': self.user.username, 'pk': self.pk}) class Meta: ordering = ['-created_at'] unique_together = ['user', 'message']
srijannnd/Login-and-Register-App-in-Django
simplesocial/posts/models.py
Python
mit
984
# Copyright (c) 2015 Huawei Technologies Co.,LTD. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import abc import six from neutron._i18n import _ from neutron.api import extensions from neutron.api.v2 import attributes as attr from neutron.api.v2 import base from neutron.common import exceptions as nexception from neutron import manager ADDRESS_SCOPE = 'address_scope' ADDRESS_SCOPES = '%ss' % ADDRESS_SCOPE ADDRESS_SCOPE_ID = 'address_scope_id' # Attribute Map RESOURCE_ATTRIBUTE_MAP = { ADDRESS_SCOPES: { 'id': {'allow_post': False, 'allow_put': False, 'validate': {'type:uuid': None}, 'is_visible': True, 'primary_key': True}, 'name': {'allow_post': True, 'allow_put': True, 'default': '', 'validate': {'type:string': attr.NAME_MAX_LEN}, 'is_visible': True}, 'tenant_id': {'allow_post': True, 'allow_put': False, 'validate': {'type:string': attr.TENANT_ID_MAX_LEN}, 'required_by_policy': True, 'is_visible': True}, attr.SHARED: {'allow_post': True, 'allow_put': True, 'default': False, 'convert_to': attr.convert_to_boolean, 'is_visible': True, 'required_by_policy': True, 'enforce_policy': True}, 'ip_version': {'allow_post': True, 'allow_put': False, 'convert_to': attr.convert_to_int, 'validate': {'type:values': [4, 6]}, 'is_visible': True}, }, attr.SUBNETPOOLS: { ADDRESS_SCOPE_ID: {'allow_post': True, 'allow_put': True, 'default': attr.ATTR_NOT_SPECIFIED, 'validate': {'type:uuid_or_none': None}, 'is_visible': True} } } class AddressScopeNotFound(nexception.NotFound): message = _("Address scope %(address_scope_id)s could not be found") class AddressScopeInUse(nexception.InUse): message = _("Unable to complete operation on " "address scope %(address_scope_id)s. There are one or more" " subnet pools in use on the address scope") class AddressScopeUpdateError(nexception.BadRequest): message = _("Unable to update address scope %(address_scope_id)s : " "%(reason)s") class Address_scope(extensions.ExtensionDescriptor): """Extension class supporting Address Scopes.""" @classmethod def get_name(cls): return "Address scope" @classmethod def get_alias(cls): return "address-scope" @classmethod def get_description(cls): return "Address scopes extension." @classmethod def get_updated(cls): return "2015-07-26T10:00:00-00:00" @classmethod def get_resources(cls): """Returns Ext Resources.""" my_plurals = [(key, key[:-1]) for key in RESOURCE_ATTRIBUTE_MAP.keys()] attr.PLURALS.update(dict(my_plurals)) plugin = manager.NeutronManager.get_plugin() collection_name = ADDRESS_SCOPES.replace('_', '-') params = RESOURCE_ATTRIBUTE_MAP.get(ADDRESS_SCOPES, dict()) controller = base.create_resource(collection_name, ADDRESS_SCOPE, plugin, params, allow_bulk=True, allow_pagination=True, allow_sorting=True) ex = extensions.ResourceExtension(collection_name, controller, attr_map=params) return [ex] def get_extended_resources(self, version): if version == "2.0": return RESOURCE_ATTRIBUTE_MAP else: return {} @six.add_metaclass(abc.ABCMeta) class AddressScopePluginBase(object): @abc.abstractmethod def create_address_scope(self, context, address_scope): pass @abc.abstractmethod def update_address_scope(self, context, id, address_scope): pass @abc.abstractmethod def get_address_scope(self, context, id, fields=None): pass @abc.abstractmethod def get_address_scopes(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): pass @abc.abstractmethod def delete_address_scope(self, context, id): pass def get_address_scopes_count(self, context, filters=None): raise NotImplementedError()
dims/neutron
neutron/extensions/address_scope.py
Python
apache-2.0
5,290
class check_privilege_revoke_all_fga_log(): """ check_privilege_revoke_all_fga_log Ensure 'ALL' Is Revoked from Unauthorized 'GRANTEE' on FGA_LOG$ The FGA_LOG$ table contains audit records for tables with a defined Fine Grained Auditing policy. """ # References: # http://www.davidlitchfield.com/AddendumtotheOracle12cCISGuidelines.pdf # http://www.davidlitchfield.com/oracle_backdoors.pdf TITLE = 'Revoke ALL from FGA_LOG$' CATEGORY = 'Privilege' TYPE = 'sql' SQL = "SELECT GRANTEE, PRIVILEGE FROM DBA_TAB_PRIVS WHERE TABLE_NAME = 'FGA_LOG$'" verbose = False skip = False result = {} def do_check(self, *results): self.result['level'] = 'GREEN' output = '' for rows in results: for row in rows: self.result['level'] = 'RED' output += row[0] + ' with ' + row[1] + 'on FGA_LOG$\n' if 'GREEN' == self.result['level']: output = 'No user with grants to FGA_LOG$.' self.result['output'] = output return self.result def __init__(self, parent): print('Performing check: ' + self.TITLE)
foospidy/DbDat
plugins/oracle/check_privilege_revoke_all_fga_log.py
Python
gpl-2.0
1,208
import pygame import random import os import sys from os import path from pygame.locals import * image_dir = path.join(path.dirname(__file__), 'images') sound_dir = path.join(path.dirname(__file__), 'sounds') pygame.init() pygame.mixer.init() # Initializing shooting sounds bulletSound1 = pygame.mixer.Sound(path.join(sound_dir, "fire1.wav")) bulletSound1.set_volume(0.1) bulletSound2 = pygame.mixer.Sound(path.join(sound_dir, "fire2.wav")) bulletSound2.set_volume(0.1) bulletSound3 = pygame.mixer.Sound(path.join(sound_dir, "fire3.wav")) bulletSound3.set_volume(0.1) bulletSound4 = pygame.mixer.Sound(path.join(sound_dir, "fire4.wav")) bulletSound4.set_volume(0.1) bulletSound5 = pygame.mixer.Sound(path.join(sound_dir, "fire5.wav")) bulletSound5.set_volume(0.5) bulletSound6 = pygame.mixer.Sound(path.join(sound_dir, "fire6.wav")) bulletSound6.set_volume(0.5) # Initializing bullet Images bullet1 = path.join(image_dir, "bullet1.png") bullet2 = path.join(image_dir, "bullet2.png") bullet3 = path.join(image_dir, "bullet3.png") bullet4 = path.join(image_dir, "bullet4.png") bullet5 = path.join(image_dir, "bullet5.png") bullet6 = path.join(image_dir, "dollar.png") # Initializing Dan sounds danSound1 = pygame.mixer.Sound(path.join(sound_dir, "dan1.wav")) danSound2 = pygame.mixer.Sound(path.join(sound_dir, "dan2.wav")) danSound3 = pygame.mixer.Sound(path.join(sound_dir, "dan3.wav")) danSound4 = pygame.mixer.Sound(path.join(sound_dir, "dan4.wav")) danSound5 = pygame.mixer.Sound(path.join(sound_dir, "dan5.wav")) danSounds = [danSound1, danSound2, danSound3, danSound4, danSound5] # Loading background music pygame.mixer.music.load(path.join(sound_dir, "song1.wav")) pygame.mixer.music.set_volume(0.2) # Setting up screen size for game display_width = 1024 display_height = 650 # Initializing colors black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) yellow = (255, 255, 0) navy = (0, 0, 128) cyan = (0, 255, 255) # Initializing fonts font = pygame.font.SysFont(None, 100) font2 = pygame.font.SysFont(None, 50) font3 = pygame.font.SysFont(None, 60) font4 = pygame.font.SysFont(None, 70) font5 = pygame.font.SysFont(None, 90) gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Humans vs Aliens') clock = pygame.time.Clock() # Initializing pictures level1 = path.join(image_dir, "level1.png") level2 = path.join(image_dir, "level2.gif") level3 = path.join(image_dir, "level3.png") level4 = path.join(image_dir, "level4.png") level5 = path.join(image_dir, "level5.png") level6 = path.join(image_dir, "level6.png") bernie = path.join(image_dir, "bernie.png") arnold = path.join(image_dir, "arnold.png") dan = path.join(image_dir, "dan.png") kim = path.join(image_dir, "kim.png") obama = path.join(image_dir, "obama.png") dirks = path.join(image_dir, "dirks.png") # Initializing background background = pygame.image.load(path.join(image_dir, "background.png")) rescaledBackground = pygame.transform.scale(background, (display_width, display_height) ) gameDisplay.blit(rescaledBackground, (0, 0)) # Human Object class Human(pygame.sprite.Sprite): def __init__(self, image, speed, bulletSpeed, bulletImg): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(image) self.rect = self.image.get_rect() self.rect.left = 0 self.speedy = speed self.radius = 57 self.bulletSpeed = bulletSpeed self.bulletImg = bulletImg # pygame.draw.circle(self.image, red, self.rect.center, self.radius) def update(self): keystate = pygame.key.get_pressed() if keystate[pygame.K_UP] or keystate[pygame.K_w]: self.rect.y -= self.speedy if keystate[pygame.K_DOWN] or keystate[pygame.K_s]: self.rect.y += self.speedy if self.rect.top < 30: self.rect.top = 30 if self.rect.bottom > display_height - 10: self.rect.bottom = display_height - 10 def shoot(self): bullet = Bullet(self.rect.centerx, self.rect.centery - 20, self.bulletSpeed, self.bulletImg) bullets.add(bullet) # Alien Object class Alien(pygame.sprite.Sprite): def __init__(self, image, speed): # (image type, speed) pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(image) self.rect = self.image.get_rect() self.radius = 41 # pygame.draw.circle(self.image, red, self.rect.center, self.radius) self.rect.x = random.randint(display_width + 20, display_width + 2000) self.rect.y = random.randrange(40, display_height - self.rect.height, 100) self.speedx = speed self.mask = pygame.mask.from_surface(self.image) def update(self): self.rect.x -= self.speedx if self.rect.left < -90: self.kill() # Bullet Object class Bullet(pygame.sprite.Sprite): def __init__(self, x, y, speed, bullet): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(bullet) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.speedx = speed self.mask = pygame.mask.from_surface(self.image) def update(self): self.rect.x += self.speedx if self.rect.right > display_width + 10: self.kill() # Putting sprites into their corresponding groups enemies = pygame.sprite.Group() enemies2 = pygame.sprite.Group() enemies3 = pygame.sprite.Group() enemies4 = pygame.sprite.Group() enemies5 = pygame.sprite.Group() enemies6 = pygame.sprite.Group() bullets = pygame.sprite.Group() human1 = pygame.sprite.Group() human2 = pygame.sprite.Group() human3 = pygame.sprite.Group() human4 = pygame.sprite.Group() human5 = pygame.sprite.Group() human6 = pygame.sprite.Group() # Making instaces of objects h1 = Human(bernie, 10, 10, bullet1) h2 = Human(arnold, 12, 15, bullet2) h3 = Human(dan, 14, 20, bullet3) h4 = Human(kim, 16, 25, bullet4) h5 = Human(obama, 18, 30, bullet5) h6 = Human(dirks, 20, 35, bullet6) human1.add(h1) human2.add(h2) human3.add(h3) human4.add(h4) human5.add(h5) human6.add(h6) # Spawning Alines for different levels # Bernie for i in range(25): a = Alien(level1, 6) enemies.add(a) # Arnold for i in range(30): b = Alien(level2, 8) enemies2.add(b) # Dan for i in range(35): c = Alien(level3, 10) enemies3.add(c) # Kim for i in range(32): d = Alien(level4, 10.5) enemies4.add(d) # Obama for i in range(33): e = Alien(level5, 11) enemies5.add(e) # Dirks for i in range(34): f = Alien(level6, 11.5) enemies6.add(f) # Drawing Lives def Live(health): font = pygame.font.SysFont(None, 30, bold=True) text = font.render("LIVES: " + str(health) + "/10", True, white) gameDisplay.blit(text, (10, 10)) # Drawing Score def score(score): font = pygame.font.SysFont(None, 30, bold=True) text = font.render("SCORE: " + str(score), True, white) gameDisplay.blit(text, (470, 10)) def draw_pause(): font = pygame.font.SysFont(None, 30, bold=True) text = font.render("'P' = PAUSE", True, cyan) text2 = font.render("'R' = RESTART", True, cyan) gameDisplay.blit(text, (850, 10)) gameDisplay.blit(text2, (850, 30)) # Drawing High Score def high_score(lastScore): font = pygame.font.SysFont("None", 30, bold=True) text = font.render("HIGH SCORE: " + lastScore, True, white) gameDisplay.blit(text, (620, 10)) # Drawing Aliens passed def aliens_passed(passed): font = pygame.font.SysFont(None, 30, bold=True) text = font.render("ALIENS PASSED: " + str(passed) + "/10", True, white) gameDisplay.blit(text, (185, 10)) def drawText(text, font, surface, x, y, color): textobj = font.render(text, 1, color) textrect = textobj.get_rect() textrect.topleft = (x, y) surface.blit(textobj, textrect) # Pause Function def paused(): pygame.mixer.music.pause() pause = True while pause: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() if event.key == pygame.K_RETURN: pygame.mixer.music.unpause() return gameDisplay.blit(rescaledBackground, (0, 0)) drawText('PAUSED', font, gameDisplay, 370, 200, black) drawText('PRESS ENTER TO CONTINUE', font2, gameDisplay, 260, 400, black) Live(lives) score(scoreCount) aliens_passed(aliensPassed) high_score(lastScore) pygame.display.update() clock.tick(15) # Game Intro screen def game_intro(): intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() if event.key == pygame.K_RETURN: return gameDisplay.blit(rescaledBackground, (0, 0)) drawText('HUMANS vs. ALIENS', font, gameDisplay, (170), (90), black) drawText('CS10 FINAL PROJECT', font2, gameDisplay, (display_width / 3) - 10, 230, blue) drawText('PRESS ENTER TO START', font3, gameDisplay, (display_width / 3) - 80, (display_height / 3) + 150, white) drawText('Space => Shoot Arrow Keys => Move', font2, gameDisplay, 150, 500, navy) pygame.display.update() # Game Over screen def gameOver(): pygame.mixer.music.stop() gameDisplay.blit(rescaledBackground, (0, 0)) drawText("HUMANS vs. ALIENS", font, gameDisplay, 170, 70, black) drawText("Oh no! Aliens have invaded your land!", font2, gameDisplay, 200, display_height / 2 - 120, black) drawText("PRESS ENTER TO RESTART OR ESCAPE TO EXIT", font2, gameDisplay, 90, 550, white) drawText("SCORE: " + str(scoreCount), font5, gameDisplay, 350, 300, black) drawText("HIGH SCORE: " + str(lastScore), font4, gameDisplay, 300, 430, navy) pygame.display.update() waiting = True while waiting: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() if event.key == pygame.K_RETURN: pygame.mixer.music.play(-1) waiting = False # WINNING SCREEN def winning(): pygame.mixer.music.stop() gameDisplay.blit(rescaledBackground, (0, 0)) drawText("HUMANS vs. ALIENS", font, gameDisplay, 170, 70, black) drawText("Congratulation! You have defeated the Aliens!", font2, gameDisplay, 150, display_height / 2 - 120, blue) drawText("Your land is safe now.", font2, gameDisplay, 340, display_height / 2 - 60, blue) drawText("PRESS ENTER TO RESTART OR ESCAPE TO EXIT", font2, gameDisplay, 90, 550, white) drawText("SCORE: " + str(scoreCount), font5, gameDisplay, 350, 350, black) drawText("HIGH SCORE: " + str(lastScore), font4, gameDisplay, 300, 450, navy) pygame.display.update() waiting = True while waiting: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() if event.key == pygame.K_RETURN: pygame.mixer.music.play(-1) waiting = False # Initializing variables and game_intro script game_intro() game_over = False win = False restarted = False global aliensPassed aliensPassed = 0 global killed killed = 0 global scoreCount scoreCount = 0 global lives lives = 10 # Game Loop while True: pygame.mixer.music.play(-1) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() if event.key == pygame.K_p: paused() if event.key == pygame.K_r: restarted = True if event.key == K_SPACE: if killed < 50: h1.shoot() bulletSound1.play() if killed >= 50 and killed < 120: h2.shoot() bulletSound2.play() if killed >= 120 and killed < 200: h3.shoot() bulletSound3.play() if killed >= 200 and killed < 300: h4.shoot() bulletSound4.play() if killed >= 300 and killed < 420: h5.shoot() bulletSound5.play() if killed >= 420 and killed < 550: h6.shoot() bulletSound6.play() bullets.update() enemies.update() human1.update() gameDisplay.blit(rescaledBackground, (0, 0)) bullets.draw(gameDisplay) enemies.draw(gameDisplay) human1.draw(gameDisplay) # Read high score text file; if the file is empty, write 0 with open("high_score.txt", "r+") as f: if os.stat("high_score.txt").st_size == 0: f.write("0") global lastScore lastScore = f.read() # LEVEL1 hits = pygame.sprite.groupcollide(enemies, bullets, True, True, pygame.sprite.collide_mask) for hit in hits: a1 = Alien(level1, 6) enemies.add(a1) killed += 1 scoreCount += 1 hits = pygame.sprite.spritecollide(h1, enemies, True, pygame.sprite.collide_circle) for hit in hits: lives -= 1 a1 = Alien(level1, 6) enemies.add(a1) if lives <= 0: game_over = True for i in enemies: if i.rect.right < 0: aliensPassed += 1 # LEVEL2 if killed >= 50 and killed < 120: enemies.remove() enemies.empty() human1.remove() human1.empty() enemies2.update() human2.update() enemies2.draw(gameDisplay) human2.draw(gameDisplay) hits = pygame.sprite.groupcollide(enemies2, bullets, True, True, pygame.sprite.collide_mask) for hit in hits: a2 = Alien(level2, 8) enemies2.add(a2) killed += 1 scoreCount += 1 hits = pygame.sprite.spritecollide(h2, enemies2, True, pygame.sprite.collide_circle) for hit in hits: lives -= 1 a2 = Alien(level2, 8) enemies2.add(a2) if lives <= 0: game_over = True for i in enemies2: if i.rect.right < 0: aliensPassed += 1 # LEVEL3 if killed >= 120 and killed < 200: enemies2.remove() enemies2.empty() human2.remove() human2.empty() enemies3.update() human3.update() enemies3.draw(gameDisplay) human3.draw(gameDisplay) hits = pygame.sprite.groupcollide(enemies3, bullets, True, True, pygame.sprite.collide_mask) for hit in hits: a3 = Alien(level3, 10) enemies3.add(a3) killed += 1 scoreCount += 1 hits = pygame.sprite.spritecollide(h3, enemies3, True, pygame.sprite.collide_circle) for hit in hits: random.choice(danSounds).play() lives -= 1 a3 = Alien(level3, 10) enemies3.add(a3) if lives <= 0: game_over = True for i in enemies3: if i.rect.right < 0: aliensPassed += 1 # Level 4 if killed >= 200 and killed < 300: enemies3.remove() enemies3.empty() human3.remove() human3.empty() enemies4.update() human4.update() enemies4.draw(gameDisplay) human4.draw(gameDisplay) hits = pygame.sprite.groupcollide(enemies4, bullets, True, True, pygame.sprite.collide_mask) for hit in hits: a4 = Alien(level4, 10.5) enemies4.add(a4) killed += 1 scoreCount += 1 hits = pygame.sprite.spritecollide(h4, enemies4, True, pygame.sprite.collide_circle) for hit in hits: lives -= 1 a4 = Alien(level4, 10.5) enemies4.add(a4) if lives <= 0: game_over = True for i in enemies4: if i.rect.right < 0: aliensPassed += 1 # Level 5 if killed >= 300 and killed < 420: enemies4.remove() enemies4.empty() human4.remove() human4.empty() enemies5.update() human5.update() enemies5.draw(gameDisplay) human5.draw(gameDisplay) hits = pygame.sprite.groupcollide(enemies5, bullets, True, True, pygame.sprite.collide_mask) for hit in hits: a5 = Alien(level5, 11) enemies5.add(a5) killed += 1 scoreCount += 1 hits = pygame.sprite.spritecollide(h5, enemies5, True, pygame.sprite.collide_circle) for hit in hits: lives -= 1 a5 = Alien(level5, 11) enemies5.add(a5) if lives <= 0: game_over = True for i in enemies5: if i.rect.right < 0: aliensPassed += 1 # Final Level if killed >= 420: enemies5.remove() enemies5.empty() human5.remove() human5.empty() enemies6.update() human6.update() enemies6.draw(gameDisplay) human6.draw(gameDisplay) hits = pygame.sprite.groupcollide(enemies6, bullets, True, True, pygame.sprite.collide_mask) for hit in hits: a6 = Alien(level6, 11.5) enemies6.add(a6) killed += 1 scoreCount += 1 hits = pygame.sprite.spritecollide(h6, enemies6, True, pygame.sprite.collide_circle) for hit in hits: lives -= 1 a6 = Alien(level6, 11.5) enemies6.add(a6) if lives <= 0: game_over = True for i in enemies6: if i.rect.right < 0: aliensPassed += 1 if scoreCount > int(lastScore): with open("high_score.txt", "w") as g: g.write(str(scoreCount)) # If 10 Aliens pass, the player loses if aliensPassed >= 10: game_over = True if killed >= 550: win = True # GAME OVER SCREEN AND RESTARTING if game_over: gameOver() game_over = False enemies = pygame.sprite.Group() enemies2 = pygame.sprite.Group() enemies3 = pygame.sprite.Group() enemies4 = pygame.sprite.Group() enemies5 = pygame.sprite.Group() enemies6 = pygame.sprite.Group() bullets = pygame.sprite.Group() human1 = pygame.sprite.Group() human2 = pygame.sprite.Group() human3 = pygame.sprite.Group() human4 = pygame.sprite.Group() human5 = pygame.sprite.Group() human6 = pygame.sprite.Group() h1 = Human(bernie, 10, 10, bullet1) h2 = Human(arnold, 12, 15, bullet2) h3 = Human(dan, 14, 20, bullet3) h4 = Human(kim, 16, 25, bullet4) h5 = Human(obama, 18, 30, bullet5) h6 = Human(dirks, 20, 35, bullet6) human1.add(h1) human2.add(h2) human3.add(h3) human4.add(h4) human5.add(h5) human6.add(h6) for i in range(25): a = Alien(level1, 6) enemies.add(a) for i in range(30): b = Alien(level2, 8) enemies2.add(b) for i in range(35): c = Alien(level3, 10) enemies3.add(c) for i in range(32): d = Alien(level4, 10.5) enemies4.add(d) for i in range(33): e = Alien(level5, 11) enemies5.add(e) for i in range(34): f = Alien(level6, 11.5) enemies6.add(f) aliensPassed = 0 killed = 0 scoreCount = 0 lives = 10 with open("high_score.txt", "r") as f: lastScore = f.read() # WINNING SCREEN AND RESTARTING if win: winning() win = False enemies = pygame.sprite.Group() enemies2 = pygame.sprite.Group() enemies3 = pygame.sprite.Group() enemies4 = pygame.sprite.Group() enemies5 = pygame.sprite.Group() enemies6 = pygame.sprite.Group() bullets = pygame.sprite.Group() human1 = pygame.sprite.Group() human2 = pygame.sprite.Group() human3 = pygame.sprite.Group() human4 = pygame.sprite.Group() human5 = pygame.sprite.Group() human6 = pygame.sprite.Group() h1 = Human(bernie, 10, 10, bullet1) h2 = Human(arnold, 12, 15, bullet2) h3 = Human(dan, 14, 20, bullet3) h4 = Human(kim, 16, 25, bullet4) h5 = Human(obama, 18, 30, bullet5) h6 = Human(dirks, 20, 35, bullet6) human1.add(h1) human2.add(h2) human3.add(h3) human4.add(h4) human5.add(h5) human6.add(h6) for i in range(25): a = Alien(level1, 6) enemies.add(a) for i in range(30): b = Alien(level2, 8) enemies2.add(b) for i in range(35): c = Alien(level3, 10) enemies3.add(c) for i in range(32): d = Alien(level4, 10.5) enemies4.add(d) for i in range(33): e = Alien(level5, 11) enemies5.add(e) for i in range(34): f = Alien(level6, 11.5) enemies6.add(f) aliensPassed = 0 killed = 0 scoreCount = 0 lives = 10 with open("high_score.txt", "r") as f: lastScore = f.read() # RESTART if restarted: restarted = False pygame.mixer.music.play(-1) enemies = pygame.sprite.Group() enemies2 = pygame.sprite.Group() enemies3 = pygame.sprite.Group() enemies4 = pygame.sprite.Group() enemies5 = pygame.sprite.Group() enemies6 = pygame.sprite.Group() bullets = pygame.sprite.Group() human1 = pygame.sprite.Group() human2 = pygame.sprite.Group() human3 = pygame.sprite.Group() human4 = pygame.sprite.Group() human5 = pygame.sprite.Group() human6 = pygame.sprite.Group() h1 = Human(bernie, 10, 10, bullet1) h2 = Human(arnold, 12, 15, bullet2) h3 = Human(dan, 14, 20, bullet3) h4 = Human(kim, 16, 25, bullet4) h5 = Human(obama, 18, 30, bullet5) h6 = Human(dirks, 20, 35, bullet6) human1.add(h1) human2.add(h2) human3.add(h3) human4.add(h4) human5.add(h5) human6.add(h6) for i in range(25): a = Alien(level1, 6) enemies.add(a) for i in range(30): b = Alien(level2, 8) enemies2.add(b) for i in range(35): c = Alien(level3, 10) enemies3.add(c) for i in range(32): d = Alien(level4, 10.5) enemies4.add(d) for i in range(33): e = Alien(level5, 11) enemies5.add(e) for i in range(34): f = Alien(level6, 11.5) enemies6.add(f) aliensPassed = 0 killed = 0 scoreCount = 0 lives = 10 with open("high_score.txt", "r") as f: lastScore = f.read() score(scoreCount) aliens_passed(aliensPassed) Live(lives) high_score(lastScore) draw_pause() pygame.display.update() clock.tick(60) pygame.quit() sys.exit()
Pedram26/Humans-vs-Aliens
HumansAliens.app/Contents/Resources/HumansAliens.py
Python
apache-2.0
26,473
"""""" # Set Global Attributes: __name__ = 'jhTAlib' __version__ = '20211230.0' __description__ = 'Technical Analysis Library Time-Series' __url__ = 'https://github.com/joosthoeks/jhTAlib' __author__ = 'Joost Hoeks' __author_email__ = '[email protected]' # Import Built-Ins: # Import Third-Party: # Import Homebrew: from .decorators import * from .helpers import * from .behavioral_techniques import * from .candlestick import * from .cycle_indicators import * from .data import * from .event_driven import * from .experimental import * from .general import * from .information import * from .math_functions import * from .momentum_indicators import * from .overlap_studies import * from .pattern_recognition import * from .price_transform import * from .statistic_functions import * from .uncategorised import * from .volatility_indicators import * from .volume_indicators import * from .example import *
joosthoeks/jhTAlib
jhtalib/__init__.py
Python
gpl-3.0
920
#! /usr/bin/env jython # start.py # This is a quick-and-dirty script to simplify running Grinder # agent and console from the command-line. usage = """Usage: jython start.py [agent|console] This script reads configuration from conf.py in the current directory. Please edit conf.py to fit your environment before running start.py. """ import os import sys # Get configuration from conf.py from conf import paths if __name__ == '__main__': if len(sys.argv) != 2: print(usage) sys.exit() arg = sys.argv[1] if arg not in ('agent', 'console'): print(usage) sys.exit() abs = os.path.abspath # Add java home directory to system path new_path = abs(paths['java']) + os.path.pathsep + os.getenv('PATH') os.putenv('PATH', new_path) # Add grinder.jar to Java's classpath grinder_jar = abs(os.path.join(paths['grinder'], 'lib', 'grinder.jar')) classpath = grinder_jar + os.path.pathsep + os.getenv('CLASSPATH', '') # Assemble the command-line cmd = 'java -cp ' + classpath # Add Jython path cmd += ' -Dgrinder.jvm.arguments=-Dpython.home=' + abs(paths['jython']) # Add library name for agent or console # (Agent needs grinder.properties, but console does not) if arg == 'agent': cmd += ' net.grinder.Grinder ' + abs(paths['properties']) else: cmd += ' net.grinder.Console' print("Running: %s" % cmd) try: os.system(cmd) except KeyboardInterrupt: print("Stopped Grinder %s" % arg)
a-e/grinder-webtest
start.py
Python
mit
1,535
tests=[ ("testExecs/testConformerParser.exe","",{}), ] longTests = [] if __name__=='__main__': import sys from rdkit import TestRunner failed,tests = TestRunner.RunScript('test_list.py',0,1) sys.exit(len(failed))
adalke/rdkit
Contrib/ConformerParser/test_list.py
Python
bsd-3-clause
228
from __future__ import unicode_literals # # Copyright 2005,2006,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr from gnuradio import eng_notation from gnuradio import digital from gnuradio import analog import copy import sys # ///////////////////////////////////////////////////////////////////////////// # receive path # ///////////////////////////////////////////////////////////////////////////// class receive_path(gr.hier_block2): def __init__(self, rx_callback, options): gr.hier_block2.__init__(self, "receive_path", gr.io_signature(1, 1, gr.sizeof_gr_complex), gr.io_signature(0, 0, 0)) options = copy.copy(options) # make a copy so we can destructively modify self._verbose = options.verbose self._log = options.log self._rx_callback = rx_callback # this callback is fired when there's a packet available # receiver self.ofdm_rx = digital.ofdm_demod(options, callback=self._rx_callback) # Carrier Sensing Blocks alpha = 0.001 thresh = 30 # in dB, will have to adjust self.probe = analog.probe_avg_mag_sqrd_c(thresh,alpha) self.connect(self, self.ofdm_rx) self.connect(self.ofdm_rx, self.probe) # Display some information about the setup if self._verbose: self._print_verbage() def carrier_sensed(self): """ Return True if we think carrier is present. """ #return self.probe.level() > X return self.probe.unmuted() def carrier_threshold(self): """ Return current setting in dB. """ return self.probe.threshold() def set_carrier_threshold(self, threshold_in_db): """ Set carrier threshold. Args: threshold_in_db: set detection threshold (float (dB)) """ self.probe.set_threshold(threshold_in_db) @staticmethod def add_options(normal, expert): """ Adds receiver-specific options to the Options Parser """ normal.add_option("-W", "--bandwidth", type="eng_float", default=500e3, help="set symbol bandwidth [default=%default]") normal.add_option("-v", "--verbose", action="store_true", default=False) expert.add_option("", "--log", action="store_true", default=False, help="Log all parts of flow graph to files (CAUTION: lots of data)") def _print_verbage(self): """ Prints information about the receive path """ pass
iohannez/gnuradio
gr-digital/examples/ofdm/receive_path.py
Python
gpl-3.0
3,483
""" Copyright 2015 Brocade Communications Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from pynos.versions.ver_7.ver_7_0_0.yang.brocade_interface \ import brocade_interface as brcd_intf from pynos.versions.ver_7.ver_7_0_0.yang.brocade_rbridge \ import brocade_rbridge as brcd_rbridge import pynos.utilities from pynos.versions.base.interface import Interface as InterfaceBase from pynos.versions.ver_7.ver_7_0_0.yang.brocade_mac_address_table \ import brocade_mac_address_table from pynos.exceptions import InvalidVlanId from ipaddress import ip_interface import xml.etree.ElementTree as ET class Interface(InterfaceBase): """ The Interface class holds all the actions assocaiated with the Interfaces of a NOS device. Attributes: None """ def __init__(self, callback): super(Interface, self).__init__(callback) self._interface = brcd_intf(callback=pynos.utilities.return_xml) self._rbridge = brcd_rbridge(callback=pynos.utilities.return_xml) self._mac_address_table = brocade_mac_address_table( callback=pynos.utilities.return_xml ) def ip_unnumbered(self, **kwargs): """Configure an unnumbered interface. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). name (str): Name of interface id. (For interface: 1/0/5, 1/0/10 etc). delete (bool): True is the IP address is added and False if its to be deleted (True, False). Default value will be False if not specified. donor_type (str): Interface type of the donor interface. donor_name (str): Interface name of the donor interface. get (bool): Get config instead of editing config. (True, False) callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if `int_type`, `name`, `donor_type`, or `donor_name` is not passed. ValueError: if `int_type`, `name`, `donor_type`, or `donor_name` are invalid. Examples: >>> import pynos.device >>> switches = ['10.24.39.230'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... output = dev.interface.ip_address(int_type='loopback', ... name='1', ip_addr='4.4.4.4/32', rbridge_id='230') ... int_type = 'tengigabitethernet' ... name = '230/0/20' ... donor_type = 'loopback' ... donor_name = '1' ... output = dev.interface.disable_switchport(inter_type= ... int_type, inter=name) ... output = dev.interface.ip_unnumbered(int_type=int_type, ... name=name, donor_type=donor_type, donor_name=donor_name) ... output = dev.interface.ip_unnumbered(int_type=int_type, ... name=name, donor_type=donor_type, donor_name=donor_name, ... get=True) ... output = dev.interface.ip_unnumbered(int_type=int_type, ... name=name, donor_type=donor_type, donor_name=donor_name, ... delete=True) ... output = dev.interface.ip_address(int_type='loopback', ... name='1', ip_addr='4.4.4.4/32', rbridge_id='230', ... delete=True) ... output = dev.interface.ip_unnumbered(int_type='hodor', ... donor_name=donor_name, donor_type=donor_type, name=name) ... # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ValueError """ kwargs['ip_donor_interface_name'] = kwargs.pop('donor_name') kwargs['ip_donor_interface_type'] = kwargs.pop('donor_type') kwargs['delete'] = kwargs.pop('delete', False) callback = kwargs.pop('callback', self._callback) valid_int_types = ['gigabitethernet', 'tengigabitethernet', 'fortygigabitethernet', 'hundredgigabitethernet'] if kwargs['int_type'] not in valid_int_types: raise ValueError('int_type must be one of: %s' % repr(valid_int_types)) unnumbered_type = self._ip_unnumbered_type(**kwargs) unnumbered_name = self._ip_unnumbered_name(**kwargs) if kwargs.pop('get', False): return self._get_ip_unnumbered(unnumbered_type, unnumbered_name) config = pynos.utilities.merge_xml(unnumbered_type, unnumbered_name) return callback(config) def _ip_unnumbered_name(self, **kwargs): """Return the `ip unnumbered` donor name XML. You should not use this method. You probably want `Interface.ip_unnumbered`. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). delete (bool): Remove the configuration if ``True``. ip_donor_interface_name (str): The donor interface name (1, 2, etc) Returns: XML to be passed to the switch. Raises: None """ method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\ 'interface_name' % kwargs['int_type'] ip_unnumbered_name = getattr(self._interface, method_name) config = ip_unnumbered_name(**kwargs) if kwargs['delete']: tag = 'ip-donor-interface-name' config.find('.//*%s' % tag).set('operation', 'delete') return config def _ip_unnumbered_type(self, **kwargs): """Return the `ip unnumbered` donor type XML. You should not use this method. You probably want `Interface.ip_unnumbered`. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). delete (bool): Remove the configuration if ``True``. ip_donor_interface_type (str): The donor interface type (loopback) Returns: XML to be passed to the switch. Raises: None """ method_name = 'interface_%s_ip_ip_config_unnumbered_ip_donor_'\ 'interface_type' % kwargs['int_type'] ip_unnumbered_type = getattr(self._interface, method_name) config = ip_unnumbered_type(**kwargs) if kwargs['delete']: tag = 'ip-donor-interface-type' config.find('.//*%s' % tag).set('operation', 'delete') return config def _get_ip_unnumbered(self, unnumbered_type, unnumbered_name): """Get and merge the `ip unnumbered` config from an interface. You should not use this method. You probably want `Interface.ip_unnumbered`. Args: unnumbered_type: XML document with the XML to get the donor type. unnumbered_name: XML document with the XML to get the donor name. Returns: Merged XML document. Raises: None """ unnumbered_type = self._callback(unnumbered_type, handler='get_config') unnumbered_name = self._callback(unnumbered_name, handler='get_config') unnumbered_type = pynos.utilities.return_xml(str(unnumbered_type)) unnumbered_name = pynos.utilities.return_xml(str(unnumbered_name)) return pynos.utilities.merge_xml(unnumbered_type, unnumbered_name) def anycast_mac(self, **kwargs): """Configure an anycast MAC address. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). mac (str): MAC address to configure (example: '0011.2233.4455'). delete (bool): True is the IP address is added and False if its to be deleted (True, False). Default value will be False if not specified. get (bool): Get config instead of editing config. (True, False) callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if `mac` is not passed. Examples: >>> import pynos.device >>> switches = ['10.24.39.230'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... output = dev.services.vrrp(ip_version='6', ... enabled=True, rbridge_id='230') ... output = dev.services.vrrp(enabled=True, ... rbridge_id='230') ... output = dev.services.vrrp(ip_version='6', ... enabled=False, rbridge_id='230') ... output = dev.services.vrrp(enabled=False, ... rbridge_id='230') ... output = dev.interface.anycast_mac(rbridge_id='230', ... mac='0011.2233.4455') ... output = dev.interface.anycast_mac(rbridge_id='230', ... mac='0011.2233.4455', get=True) ... output = dev.interface.anycast_mac(rbridge_id='230', ... mac='0011.2233.4455', delete=True) ... output = dev.services.vrrp(ip_version='6', enabled=True, ... rbridge_id='230') ... output = dev.services.vrrp(enabled=True, ... rbridge_id='230') """ callback = kwargs.pop('callback', self._callback) anycast_mac = getattr(self._rbridge, 'rbridge_id_ip_static_ag_ip_' 'config_anycast_gateway_mac_ip_anycast_' 'gateway_mac') config = anycast_mac(rbridge_id=kwargs.pop('rbridge_id', '1'), ip_anycast_gateway_mac=kwargs.pop('mac')) if kwargs.pop('get', False): return callback(config, handler='get_config') if kwargs.pop('delete', False): config.find('.//*anycast-gateway-mac').set('operation', 'delete') return callback(config) def bfd(self, **kwargs): """Configure BFD for Interface. Args: name (str): name of the interface to configure (230/0/1 etc) int_type (str): interface type (gigabitethernet etc) tx (str): BFD transmit interval in milliseconds (300, 500, etc) rx (str): BFD receive interval in milliseconds (300, 500, etc) multiplier (str): BFD multiplier. (3, 7, 5, etc) delete (bool): True if BFD configuration should be deleted. Default value will be False if not specified. get (bool): Get config instead of editing config. (True, False) callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if `tx`, `rx`, or `multiplier` is not passed. Examples: >>> import pynos.device >>> switches = ['10.24.39.230'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... output = dev.interface.bfd(name='230/0/4', rx='300', ... tx='300', multiplier='3', int_type='tengigabitethernet') ... output = dev.interface.bfd(name='230/0/4', rx='300', ... tx='300', multiplier='3', ... int_type='tengigabitethernet', get=True) ... output = dev.interface.bfd(name='230/0/4', rx='300', ... tx='300', multiplier='3', ... int_type='tengigabitethernet', delete=True) """ int_type = str(kwargs.pop('int_type').lower()) kwargs['name'] = str(kwargs.pop('name')) kwargs['min_tx'] = kwargs.pop('tx') kwargs['min_rx'] = kwargs.pop('rx') kwargs['delete'] = kwargs.pop('delete', False) callback = kwargs.pop('callback', self._callback) valid_int_types = ['gigabitethernet', 'tengigabitethernet', 'fortygigabitethernet', 'hundredgigabitethernet'] if int_type not in valid_int_types: raise ValueError('int_type must be one of: %s' % repr(valid_int_types)) kwargs['int_type'] = int_type bfd_tx = self._bfd_tx(**kwargs) bfd_rx = self._bfd_rx(**kwargs) bfd_multiplier = self._bfd_multiplier(**kwargs) if kwargs.pop('get', False): return self._get_bfd(bfd_tx, bfd_rx, bfd_multiplier) config = pynos.utilities.merge_xml(bfd_tx, bfd_rx) config = pynos.utilities.merge_xml(config, bfd_multiplier) return callback(config) def _bfd_tx(self, **kwargs): """Return the BFD minimum transmit interval XML. You should not use this method. You probably want `BGP.bfd`. Args: min_tx (str): BFD transmit interval in milliseconds (300, 500, etc) delete (bool): Remove the configuration if ``True``. Returns: XML to be passed to the switch. Raises: None """ int_type = kwargs['int_type'] method_name = 'interface_%s_bfd_interval_min_tx' % int_type bfd_tx = getattr(self._interface, method_name) config = bfd_tx(**kwargs) if kwargs['delete']: tag = 'min-tx' config.find('.//*%s' % tag).set('operation', 'delete') return config def _bfd_rx(self, **kwargs): """Return the BFD minimum receive interval XML. You should not use this method. You probably want `BGP.bfd`. Args: min_rx (str): BFD receive interval in milliseconds (300, 500, etc) delete (bool): Remove the configuration if ``True``. Returns: XML to be passed to the switch. Raises: None """ int_type = kwargs['int_type'] method_name = 'interface_%s_bfd_interval_min_rx' % int_type bfd_rx = getattr(self._interface, method_name) config = bfd_rx(**kwargs) if kwargs['delete']: tag = 'min-rx' config.find('.//*%s' % tag).set('operation', 'delete') pass return config def _bfd_multiplier(self, **kwargs): """Return the BFD multiplier XML. You should not use this method. You probably want `BGP.bfd`. Args: min_tx (str): BFD transmit interval in milliseconds (300, 500, etc) delete (bool): Remove the configuration if ``True``. Returns: XML to be passed to the switch. Raises: None """ int_type = kwargs['int_type'] method_name = 'interface_%s_bfd_interval_multiplier' % int_type bfd_multiplier = getattr(self._interface, method_name) config = bfd_multiplier(**kwargs) if kwargs['delete']: tag = 'multiplier' config.find('.//*%s' % tag).set('operation', 'delete') return config def _get_bfd(self, tx, rx, multiplier): """Get and merge the `bfd` config from global BGP. You should not use this method. You probably want `BGP.bfd`. Args: tx: XML document with the XML to get the transmit interval. rx: XML document with the XML to get the receive interval. multiplier: XML document with the XML to get the interval multiplier. Returns: Merged XML document. Raises: None """ tx = self._callback(tx, handler='get_config') rx = self._callback(rx, handler='get_config') multiplier = self._callback(multiplier, handler='get_config') tx = pynos.utilities.return_xml(str(tx)) rx = pynos.utilities.return_xml(str(rx)) multiplier = pynos.utilities.return_xml(str(multiplier)) config = pynos.utilities.merge_xml(tx, rx) return pynos.utilities.merge_xml(config, multiplier) def vrf(self, **kwargs): """Create a vrf. Args: vrf_name (str): Name of the vrf (vrf101, vrf-1 etc). get (bool): Get config instead of editing config. (True, False) delete (bool): False, the vrf is created and True if its to be deleted (True, False). Default value will be False if not specified. rbridge_id (str): rbridge-id for device. callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if `rbridge_id`,`vrf_name` is not passed. ValueError: if `rbridge_id`, `vrf_name` is invalid. Examples: >>> import pynos.device >>> switches = ['10.24.39.211', '10.24.39.203'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... output = dev.interface.vrf(vrf_name=vrf1, ... rbridge_id='225') ... output = dev.interface.vrf(rbridge_id='225', ... get=True) ... output = dev.interface.vrf(vrf_name=vrf1, ... rbridge_id='225',delete=True) """ rbridge_id = kwargs['rbridge_id'] get_config = kwargs.pop('get', False) delete = kwargs.pop('delete', False) callback = kwargs.pop('callback', self._callback) result = [] method_class = self._rbridge method_name = 'rbridge_id_vrf_vrf_name' vrf = getattr(method_class, method_name) if not get_config: vrf_name = kwargs['vrf_name'] vrf_args = dict(rbridge_id=rbridge_id, vrf_name=vrf_name) config = vrf(**vrf_args) if delete: config.find('.//*vrf').set('operation', 'delete') result = callback(config) elif get_config: vrf_args = dict(rbridge_id=rbridge_id, vrf_name='') config = vrf(**vrf_args) output = callback(config, handler='get_config') for item in output.data.findall('.//{*}vrf'): vrfname = item.find('.//{*}vrf-name').text tmp = {'rbridge_id': rbridge_id, 'vrf_name': vrfname} result.append(tmp) return result def vrf_route_distiniguisher(self, **kwargs): """Configure Route distiniguisher. Args: rbridge_id (str): rbridge-id for device. vrf_name (str): Name of the vrf (vrf101, vrf-1 etc). rd (str): Route distiniguisher <ASN:nn or IP-address:nn> get (bool): Get config instead of editing config. (True, False) delete (bool): False, the vrf rd is configured and True if its to be deleted (True, False). Default value will be False if not specified. callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if `rbridge_id`,`vrf_name`, 'rd' is not passed. ValueError: if `rbridge_id`, `vrf_name`, 'rd' is invalid. Examples: >>> import pynos.device >>> switches = ['10.24.39.211', '10.24.39.203'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... output = dev.interface.vrf_route_distiniguisher( ... vrf_name=vrf1, rbridge_id='2', rd='10.0.1.1:101') ... output = dev.interface.vrf_route_distiniguisher( ... vrf_name=vrf1, rbridge_id='2', rd='100:101') ... output = dev.interface.vrf_route_distiniguisher( ... rbridge_id='2', get=True) ... output = dev.interface.vrf_route_distiniguisher( ... rbridge_id='2', vrf_name='vrf2', get=True) ... output = dev.interface.vrf_route_distiniguisher( ... vrf_name=vrf1, rbridge_id='2', rd='100:101', ... delete=True) """ rbridge_id = kwargs['rbridge_id'] get_config = kwargs.pop('get', False) delete = kwargs.pop('delete', False) callback = kwargs.pop('callback', self._callback) result = [] method_class = self._rbridge method_name = 'rbridge_id_vrf_route_distiniguisher' vrf_rd = getattr(method_class, method_name) if not get_config: vrf_name = kwargs['vrf_name'] rd = kwargs['rd'] rd_args = dict(rbridge_id=rbridge_id, vrf_name=vrf_name, route_distiniguisher=rd) config = vrf_rd(**rd_args) if delete: config.find('.//*route-distiniguisher').set('operation', 'delete') result = callback(config) elif get_config: vrf_name = kwargs.pop('vrf_name', '') rd_args = dict(rbridge_id=rbridge_id, vrf_name=vrf_name, route_distiniguisher='') config = vrf_rd(**rd_args) output = callback(config, handler='get_config') for item in output.data.findall('.//{*}vrf'): vrfname = item.find('.//{*}vrf-name').text if item.find('.//{*}route-distiniguisher') is not None: vrfrd = item.find('.//{*}route-distiniguisher').text else: vrfrd = '' tmp = {'rbridge_id': rbridge_id, 'vrf_name': vrfname, 'rd': vrfrd} result.append(tmp) return result def vrf_l3vni(self, **kwargs): """Configure Layer3 vni under vrf. Args: rbridge_id (str): rbridge-id for device. vrf_name (str): Name of the vrf (vrf101, vrf-1 etc). l3vni (str): <NUMBER:1-16777215> Layer 3 VNI. get (bool): Get config instead of editing config. (True, False) delete (bool): False the L3 vni is configured and True if its to be deleted (True, False). Default value will be False if not specified. callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if `rbridge_id`,`vrf_name`, 'l3vni' is not passed. ValueError: if `rbridge_id`, `vrf_name`, 'l3vni' is invalid. Examples: >>> import pynos.device >>> switches = ['10.24.39.211', '10.24.39.203'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... output = dev.interface.vrf_vni( ... vrf_name=vrf1, rbridge_id='2', l3vni ='7201') ... output = dev.interface.vrf_vni(rbridge_id='2', ... get=True) ... output = dev.interface.vrf_vni(rbridge_id='2', ... , vrf_name='vrf2' get=True) ... output = dev.interface.vrf_vni(vrf_name=vrf1, ... rbridge_id='2', l3vni ='7201', delete=True) """ rbridge_id = kwargs['rbridge_id'] get_config = kwargs.pop('get', False) delete = kwargs.pop('delete', False) callback = kwargs.pop('callback', self._callback) result = [] method_class = self._rbridge method_name = 'rbridge_id_vrf_vni' vrf_vni = getattr(method_class, method_name) if not get_config: vrf_name = kwargs['vrf_name'] l3vni = kwargs['l3vni'] vni_args = dict(rbridge_id=rbridge_id, vrf_name=vrf_name, vni=l3vni) config = vrf_vni(**vni_args) if delete: config.find('.//*vni').set('operation', 'delete') result = callback(config) elif get_config: vrf_name = kwargs.pop('vrf_name', '') vni_args = dict(rbridge_id=rbridge_id, vrf_name=vrf_name, vni='') config = vrf_vni(**vni_args) output = callback(config, handler='get_config') for item in output.data.findall('.//{*}vrf'): vrfname = item.find('.//{*}vrf-name').text if item.find('.//{*}vni') is not None: vrfvni = item.find('.//{*}vni').text else: vrfvni = '' tmp = {'rbridge_id': rbridge_id, 'vrf_name': vrfname, 'l3vni': vrfvni} result.append(tmp) return result def vrf_afi_rt_evpn(self, **kwargs): """Configure Target VPN Extended Communities Args: rbridge_id (str): rbridge-id for device. vrf_name (str): Name of the vrf (vrf101, vrf-1 etc). rt (str): Route Target(import/export/both). rt_value (str): Route Target Value ASN:nn Target VPN Extended Community. afi (str): Address family (ip/ipv6). get (bool): Get config instead of editing config. List all the details of all afi under all vrf(True, False) delete_rt (bool): True to delete the route-target under address family (True, False). Default value will be False if not specified. delete_afi (bool): True to delet the ip/ipv6 address family Default value will be False if not specified. callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if `rbridge_id`,`vrf_name`, 'afi', 'rt', 'rt_value' is not passed. ValueError: if `rbridge_id`, `vrf_name`, 'afi', 'rt', rt_value is invalid. Examples: >>> import pynos.device >>> switches = ['10.24.39.211', '10.24.39.203'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... output = dev.interface.vrf_vni(rbridge_id="1", ... afi="ip", rt='import', rt_value='101:101', ... vrf_name="vrf1") ... output = dev.interface.vrf_vni(rbridge_id="1", ... afi="ip", rt='import', rt_value='101:101', ... vrf_name="vrf1",delete_rt=True) ... output = dev.interface.vrf_vni(rbridge_id="1", ... afi="ip", rt='import', rt_value='101:101', ... vrf_name="vrf1",delete_afi=True) ... output = dev.interface.vrf_vni(rbridge_id="1", ... afi="ip", get=True) ... output = dev.interface.vrf_vni(rbridge_id="1", ... afi="ip", vrf_name="vrf2", get=True) """ rbridge_id = kwargs['rbridge_id'] afi = kwargs['afi'] get_config = kwargs.pop('get', False) delete_rt = kwargs.pop('delete_rt', False) delete_afi = kwargs.pop('delete_afi', False) callback = kwargs.pop('callback', self._callback) result = [] method_class = self._rbridge method_name = 'rbridge_id_vrf_address_family_%s_unicast_' \ 'route_target_evpn' % afi vrf_rt = getattr(method_class, method_name) if not get_config: vrf_name = kwargs['vrf_name'] rt = kwargs['rt'] rt_value = kwargs['rt_value'] rt_args = dict(rbridge_id=rbridge_id, vrf_name=vrf_name, action=rt, target_community=rt_value) config = vrf_rt(**rt_args) if delete_afi is True: if config.find('.//*ipv6') is not None: config.find('.//*ipv6').set('operation', 'delete') if config.find('.//*ip') is not None: config.find('.//*ip').set('operation', 'delete') if delete_rt is True: config.find('.//*route-target').set('operation', 'delete') result = callback(config) elif get_config: vrf_name = kwargs.pop('vrf_name', '') rt_args = dict(rbridge_id=rbridge_id, vrf_name=vrf_name, action='', target_community='') config = vrf_rt(**rt_args) output = callback(config, handler='get_config') for vrf_node in output.data.findall('.//{*}vrf'): afi = '' vrfrt = [] vrfrtval = [] vrfname = vrf_node.find('.//{*}vrf-name').text if vrf_node.find('.//{*}ip') is not None: afi = "ip" if vrf_node.find('.//{*}route-target') is not None: for ipv4_action in vrf_node.findall('.//{*}action'): rttemp = ipv4_action.text vrfrt.append(rttemp) for ipv4_rt in vrf_node.findall('.//{' '*}target-community'): valtemp = ipv4_rt.text vrfrtval.append(valtemp) if vrf_node.find('.//{*}ipv6') is not None: afi = "ipv6" if vrf_node.find('.//{*}route-target') is not None: for ipv6_action in vrf_node.findall('.//{*}action'): rttemp = ipv6_action.text vrfrt.append(rttemp) for ipv6_rt in vrf_node.findall('.//{' '*}target-community'): valtemp = ipv6_rt.text vrfrtval.append(valtemp) tmp = {'rbridge_id': rbridge_id, 'vrf_name': vrfname, 'afi': afi, 'rt': vrfrt, 'rtvalue': vrfrtval} result.append(tmp) return result def conversational_arp(self, **kwargs): """Enable conversational arp learning on VDX switches Args: rbridge_id (str): rbridge-id for device. get (bool): Get config instead of editing config. (True, False) delete (bool): True, delete the conversation arp learning. (True, False) callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if `rbridge_id` is not passed. ValueError: if `rbridge_id` is invalid. Examples: >>> import pynos.device >>> conn = ('10.24.39.211', '22') >>> auth = ('admin', 'password') >>> with pynos.device.Device(conn=conn, auth=auth) as dev: ... output = dev.interface.conversational_arp(rbridge_id="1") ... output = dev.interface.conversational_arp(rbridge_id="1", get=True) ... output = dev.interface.conversational_arp(rbridge_id="1", delete=True) """ rbridge_id = kwargs.pop('rbridge_id', '1') callback = kwargs.pop('callback', self._callback) arp_config = getattr(self._rbridge, 'rbridge_id_host_table_aging_mode_conversational') arp_args = dict(rbridge_id=rbridge_id) config = arp_config(**arp_args) if kwargs.pop('get', False): output = callback(config, handler='get_config') item = output.data.find('.//{*}aging-mode') if item is not None: return True else: return None if kwargs.pop('delete', False): config.find('.//*aging-mode').set('operation', 'delete') return callback(config) def ip_anycast_gateway(self, **kwargs): """ Add anycast gateway under interface ve. Args: int_type: L3 interface type on which the anycast ip needs to be configured. name:L3 interface name on which the anycast ip needs to be configured. anycast_ip: Anycast ip which the L3 interface needs to be associated. enable (bool): If ip anycast gateway should be enabled or disabled.Default:``True``. get (bool) : Get config instead of editing config. (True, False) rbridge_id (str): rbridge-id for device. Only required when type is `ve`. callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if `int_type`, `name`, `anycast_ip` is not passed. ValueError: if `int_type`, `name`, `anycast_ip` is invalid. Examples: >>> import pynos.device >>> switches = ['10.24.39.211', '10.24.39.203'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... output = dev.interface.ip_anycast_gateway( ... int_type='ve', ... name='89', ... anycast_ip='10.20.1.1/24', ... rbridge_id='1') ... output = dev.interface.ip_anycast_gateway( ... get=True,int_type='ve', ... name='89', ... anycast_ip='10.20.1.1/24', ... rbridge_id='1') ... output = dev.interface.ip_anycast_gateway( ... enable=False,int_type='ve', ... name='89', ... anycast_ip='10.20.1.1/24', ... rbridge_id='1') ... # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): KeyError """ int_type = kwargs.pop('int_type').lower() name = kwargs.pop('name') anycast_ip = kwargs.pop('anycast_ip', '') enable = kwargs.pop('enable', True) get = kwargs.pop('get', False) rbridge_id = kwargs.pop('rbridge_id', '1') callback = kwargs.pop('callback', self._callback) valid_int_types = ['ve'] method_class = self._rbridge if get and anycast_ip == '': enable = None if int_type not in valid_int_types: raise ValueError('`int_type` must be one of: %s' % repr(valid_int_types)) anycast_args = dict(name=name, ip_address=anycast_ip, ipv6_address=anycast_ip) method_name1 = 'interface_%s_ip_ip_anycast_'\ 'address_ip_address' % int_type method_name2 = 'interface_%s_ipv6_ipv6_'\ 'anycast_address_ipv6_address' % int_type method_name1 = 'rbridge_id_%s' % method_name1 method_name2 = 'rbridge_id_%s' % method_name2 anycast_args['rbridge_id'] = rbridge_id if not pynos.utilities.valid_vlan_id(name): raise InvalidVlanId("`name` must be between `1` and `8191`") ip_anycast_gateway1 = getattr(method_class, method_name1) ip_anycast_gateway2 = getattr(method_class, method_name2) config1 = ip_anycast_gateway1(**anycast_args) config2 = ip_anycast_gateway2(**anycast_args) result = [] result.append(callback(config1, handler='get_config')) result.append(callback(config2, handler='get_config')) return result elif get: enable = None ipaddress = ip_interface(unicode(anycast_ip)) if int_type not in valid_int_types: raise ValueError('`int_type` must be one of: %s' % repr(valid_int_types)) if anycast_ip != '': ipaddress = ip_interface(unicode(anycast_ip)) if ipaddress.version == 4: anycast_args = dict(name=name, ip_address=anycast_ip) method_name = 'interface_%s_ip_ip_anycast_'\ 'address_ip_address' % int_type elif ipaddress.version == 6: anycast_args = dict(name=name, ipv6_address=anycast_ip) method_name = 'interface_%s_ipv6_ipv6_'\ 'anycast_address_ipv6_address' % int_type method_name = 'rbridge_id_%s' % method_name anycast_args['rbridge_id'] = rbridge_id if not pynos.utilities.valid_vlan_id(name): raise InvalidVlanId("`name` must be between `1` and `8191`") ip_anycast_gateway = getattr(method_class, method_name) config = ip_anycast_gateway(**anycast_args) if get: return callback(config, handler='get_config') if not enable: if ipaddress.version == 4: config.find('.//*ip-anycast-address').\ set('operation', 'delete') elif ipaddress.version == 6: config.find('.//*ipv6-anycast-address').\ set('operation', 'delete') return callback(config) def arp_suppression(self, **kwargs): """ Enable Arp Suppression on a Vlan. Args: name:Vlan name on which the Arp suppression needs to be enabled. enable (bool): If arp suppression should be enabled or disabled.Default:``True``. get (bool) : Get config instead of editing config. (True, False) callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if `name` is not passed. ValueError: if `name` is invalid. output2 = dev.interface.arp_suppression(name='89') Examples: >>> import pynos.device >>> switches = ['10.24.39.211', '10.24.39.203'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... output = dev.interface.arp_suppression( ... name='89') ... output = dev.interface.arp_suppression( ... get=True,name='89') ... output = dev.interface.arp_suppression( ... enable=False,name='89') ... # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): KeyError """ name = kwargs.pop('name') enable = kwargs.pop('enable', True) get = kwargs.pop('get', False) callback = kwargs.pop('callback', self._callback) method_class = self._interface arp_args = dict(name=name) if name: if not pynos.utilities.valid_vlan_id(name): raise InvalidVlanId("`name` must be between `1` and `8191`") arp_suppression = getattr(method_class, 'interface_vlan_interface_vlan_suppress_' 'arp_suppress_arp_enable') config = arp_suppression(**arp_args) if get: return callback(config, handler='get_config') if not enable: config.find('.//*suppress-arp').set('operation', 'delete') return callback(config) def create_evpn_instance(self, **kwargs): """ Add evpn instance. Args: evpn_instance_name: Instance name for evpn enable (bool): If evpn instance needs to be configured or disabled.Default:``True``. get (bool) : Get config instead of editing config. (True, False) rbridge_id (str): rbridge-id for device. Only required when type is `ve`. callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if 'evpn_instance_name' is not passed. ValueError: if 'evpn_instance_name' is invalid. Examples: >>> import pynos.device >>> switches = ['10.24.39.211', '10.24.39.203'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... output = dev.interface.create_evpn_instance( ... evpn_instance_name='100', ... rbridge_id='1') ... output = dev.interface.create_evpn_instance( ... get=True, ... evpn_instance_name='100', ... rbridge_id='1') ... output = dev.interface.create_evpn_instance( ... enable=False, ... evpn_instance_name='101', ... rbridge_id='1') ... output = dev.interface.create_evpn_instance( ... get=True, ... rbridge_id='1') ... # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): KeyError """ evpn_instance_name = kwargs.pop('evpn_instance_name', '') enable = kwargs.pop('enable', True) get = kwargs.pop('get', False) rbridge_id = kwargs.pop('rbridge_id', '1') callback = kwargs.pop('callback', self._callback) evpn_args = dict(instance_name=evpn_instance_name) if get: enable = None method_name = 'rbridge_id_evpn_instance_instance_name' method_class = self._rbridge evpn_args['rbridge_id'] = rbridge_id create_evpn_instance = getattr(method_class, method_name) config = create_evpn_instance(**evpn_args) if get: return callback(config, handler='get_config') if not enable: config.find('.//*/evpn-instance').set('operation', 'delete') pynos.utilities.print_xml_string(config) return callback(config) def evpn_instance_rt_both_ignore_as(self, **kwargs): """ Add evpn instance route target ignore AS. Args: evpn_instance_name: Instance name for evpn enable (bool): If target community needs to be enabled or disabled.Default:``True``. get (bool) : Get config instead of editing config. (True, False) rbridge_id (str): rbridge-id for device. Only required when type is `ve`. callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if 'evpn_instance_name' is not passed. ValueError: if 'evpn_instance_name' is invalid. Examples: >>> import pynos.device >>> switches = ['10.24.39.211', '10.24.39.203'] >>> auth = ('admin', 'password') >>> for switch in switches: ...conn = (switch, '22') ...with pynos.device.Device(conn=conn, auth=auth) as dev: ... output=dev.interface.evpn_instance_rt_both_ignore_as( ... evpn_instance_name='100', ... rbridge_id='1') ... output=dev.interface.evpn_instance_rt_both_ignore_as( ... get=True, ... evpn_instance_name='100', ... rbridge_id='1') ... output=dev.interface.evpn_instance_rt_both_ignore_as( ... enable=False, ... evpn_instance_name='101', ... rbridge_id='1') ... output=dev.interface.evpn_instance_rt_both_ignore_as( ... get=True, ... rbridge_id='1') ... # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): KeyError """ evpn_instance_name = kwargs.pop('evpn_instance_name', '') enable = kwargs.pop('enable', True) get = kwargs.pop('get', False) rbridge_id = kwargs.pop('rbridge_id', '1') callback = kwargs.pop('callback', self._callback) evpn_args = dict(instance_name=evpn_instance_name, target_community='auto') if get: enable = None method_name = 'rbridge_id_evpn_instance_route_target_both_ignore_as' method_class = self._rbridge evpn_args['rbridge_id'] = rbridge_id evpn_instance_rt_both_ignore_as = getattr(method_class, method_name) config = evpn_instance_rt_both_ignore_as(**evpn_args) if get: return callback(config, handler='get_config') if not enable: config.find('.//*target-community').set('operation', 'delete') return callback(config) def evpn_instance_duplicate_mac_timer(self, **kwargs): """ Add "Duplicate MAC timer value" under evpn instance. Args: evpn_instance_name: Instance name for evpn duplicate_mac_timer_value: Duplicate MAC timer value. enable (bool): If target community needs to be enabled or disabled.Default:``True``. get (bool) : Get config instead of editing config. (True, False) rbridge_id (str): rbridge-id for device. Only required when type is `ve`. callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if 'evpn_instance_name' is not passed. ValueError: if 'evpn_instance_name' is invalid. Examples: >>> import pynos.device >>> switches = ['10.24.39.211', '10.24.39.203'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... output=dev.interface.evpn_instance_duplicate_mac_timer( ... evpn_instance_name='100', ... duplicate_mac_timer_value='10' ... rbridge_id='1') ... output=dev.interface.evpn_instance_duplicate_mac_timer( ... get=True, ... evpn_instance_name='100', ... duplicate_mac_timer_value='10' ... rbridge_id='1') ... output=dev.interface.evpn_instance_duplicate_mac_timer( ... enable=False, ... evpn_instance_name='101', ... duplicate_mac_timer_value='10' ... rbridge_id='1') ... output=dev.interface.evpn_instance_duplicate_mac_timer( ... get=True, ... evpn_instance_name='101', ... rbridge_id='1') ... # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): KeyError """ evpn_instance_name = kwargs.pop('evpn_instance_name', '') duplicate_mac_timer_value = kwargs.pop('duplicate_mac_timer_value', '180') enable = kwargs.pop('enable', True) get = kwargs.pop('get', False) rbridge_id = kwargs.pop('rbridge_id', '1') callback = kwargs.pop('callback', self._callback) evpn_args = dict(instance_name=evpn_instance_name, duplicate_mac_timer_value=duplicate_mac_timer_value) if get: enable = None method_name = 'rbridge_id_evpn_instance_duplicate'\ '_mac_timer_duplicate_mac_timer_value' method_class = self._rbridge evpn_args['rbridge_id'] = rbridge_id evpn_instance_duplicate_mac_timer = getattr(method_class, method_name) config = evpn_instance_duplicate_mac_timer(**evpn_args) if get: return callback(config, handler='get_config') if not enable: config.find('.//*duplicate-mac-timer').set('operation', 'delete') return callback(config) def evpn_instance_mac_timer_max_count(self, **kwargs): """ Add "Duplicate MAC max count" under evpn instance. Args: evpn_instance_name: Instance name for evpn max_count: Duplicate MAC max count. enable (bool): If target community needs to be enabled or disabled.Default:``True``. get (bool) : Get config instead of editing config. (True, False) rbridge_id (str): rbridge-id for device. Only required when type is `ve`. callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if 'evpn_instance_name' is not passed. ValueError: if 'evpn_instance_name' is invalid. Examples: >>> import pynos.device >>> switches = ['10.24.39.211', '10.24.39.203'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... output=dev.interface.evpn_instance_mac_timer_max_count( ... evpn_instance_name='100', ... max_count='10' ... rbridge_id='1') ... output=dev.interface.evpn_instance_mac_timer_max_count( ... get=True, ... evpn_instance_name='100', ... max_count='10' ... rbridge_id='1') ... output=dev.interface.evpn_instance_mac_timer_max_count( ... enable=False, ... evpn_instance_name='101', ... max_count='10' ... rbridge_id='1') ... output=dev.interface.evpn_instance_mac_timer_max_count( ... get=True, ... evpn_instance_name='101', ... rbridge_id='1') ... # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): KeyError """ evpn_instance_name = kwargs.pop('evpn_instance_name', '') max_count = kwargs.pop('max_count', '5') enable = kwargs.pop('enable', True) get = kwargs.pop('get', False) rbridge_id = kwargs.pop('rbridge_id', '1') callback = kwargs.pop('callback', self._callback) evpn_args = dict(instance_name=evpn_instance_name, max_count=max_count) if get: enable = None method_name = 'rbridge_id_evpn_instance_duplicate_'\ 'mac_timer_max_count' method_class = self._rbridge evpn_args['rbridge_id'] = rbridge_id evpn_instance_mac_timer_max_count = getattr(method_class, method_name) config = evpn_instance_mac_timer_max_count(**evpn_args) if get: return callback(config, handler='get_config') if not enable: config.find('.//*duplicate-mac-timer').set('operation', 'delete') return callback(config) def evpn_instance_rd_auto(self, **kwargs): """ Add RD auto under EVPN instance. Args: rbridge_id: Rbrdige id . instance_name: EVPN instance name. Returns: True if command completes successfully or False if not. Raises: None Examples: >>> import pynos.device >>> switches = ['10.24.39.211', '10.24.39.203'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... output=dev.interface.evpn_instance_rd_auto( ... evpn_instance_name='100', ... rbridge_id='1') """ config = ET.Element("config") rbridge_id = ET.SubElement(config, "rbridge-id", xmlns="urn:brocade.com" ":mgmt:brocade-rbridge") rbridge_id_key = ET.SubElement(rbridge_id, "rbridge-id") rbridge_id_key.text = kwargs.pop('rbridge_id') evpn_instance = ET.SubElement(rbridge_id, "evpn-instance", xmlns="urn:brocade.com:mgmt:brocade-bgp") instance_name_key = ET.SubElement(evpn_instance, "instance-name") instance_name_key.text = kwargs.pop('instance_name') route_distinguisher = ET.SubElement(evpn_instance, "route-distinguisher") ET.SubElement(route_distinguisher, "auto") callback = kwargs.pop('callback', self._callback) return callback(config) def mac_move_detect_enable(self, **kwargs): """Enable mac move detect enable on vdx switches Args: get (bool): Get config instead of editing config. (True, False) delete (bool): True, delete the mac-move-detect-enable. (True, False) callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: None Examples: >>> import pynos.device >>> conn = ('10.24.39.211', '22') >>> auth = ('admin', 'password') >>> with pynos.device.Device(conn=conn, auth=auth) as dev: ... output = dev.interface.mac_move_detect_enable() ... output = dev.interface.mac_move_detect_enable(get=True) ... output = dev.interface.mac_move_detect_enable(delete=True) """ callback = kwargs.pop('callback', self._callback) mac_move = getattr(self._mac_address_table, 'mac_address_table_mac_move_mac_move_' 'detect_enable') config = mac_move() if kwargs.pop('get', False): output = callback(config, handler='get_config') item = output.data.find('.//{*}mac-move-detect-enable') if item is not None: return True else: return None if kwargs.pop('delete', False): config.find('.//*mac-move-detect-enable').set('operation', 'delete') return callback(config) def mac_move_limit(self, **kwargs): """Configure mac move limit on vdx switches Args: mac_move_limit: set the limit of mac move limit get (bool): Get config instead of editing config. (True, False) delete (bool): True, delete the mac move limit.(True, False) callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: None Examples: >>> import pynos.device >>> conn = ('10.24.39.211', '22') >>> auth = ('admin', 'password') >>> with pynos.device.Device(conn=conn, auth=auth) as dev: ... output = dev.interface.mac_move_limit() ... output = dev.interface.mac_move_limit(get=True) ... output = dev.interface.mac_move_limit(delete=True) """ callback = kwargs.pop('callback', self._callback) get_config = kwargs.pop('get', False) delete = kwargs.pop('delete', False) if not get_config: if not delete: mac_move_limit = kwargs.pop('mac_move_limit') mac_move = getattr(self._mac_address_table, 'mac_address_table_mac_move_' 'mac_move_limit') config = mac_move(mac_move_limit=mac_move_limit) else: mac_move = getattr(self._mac_address_table, 'mac_address_table_mac_move_' 'mac_move_limit') config = mac_move(mac_move_limit='') config.find('.//*mac-move-limit').set('operation', 'delete') return callback(config) if get_config: mac_move = getattr(self._mac_address_table, 'mac_address_table_mac_move_mac' '_move_limit') config = mac_move(mac_move_limit='') output = callback(config, handler='get_config') if output.data.find('.//{*}mac-move-limit') is not None: limit = output.data.find('.//{*}mac-move-limit').text if limit is not None: return limit else: return None else: limit_default = "20" return limit_default
BRCDcomm/pynos
pynos/versions/ver_7/ver_7_0_0/interface.py
Python
apache-2.0
61,234
""" The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ from utils import PrimeGen def sum_primes_below(limit): gen = PrimeGen(limit) return sum(gen) if __name__ == "__main__": print(sum_primes_below(2000000))
nymoral/euler
p10.py
Python
mit
281
def main(): num=input("Enter a # and I'll tell you all perfect numbers up to that #: ") for i in range(1,num+1): sum=0 for j in range(1,(i/2)+1): # why +1? if i%j==0: # check if remainder is 0 sum=sum+j # print "factor: ",i if sum==i: print sum,"is Perfect!" print "That's all there are!" main()
ianfelzer1/ifelzer-advprog
Last Year/python files /new1.py
Python
gpl-3.0
400
# -*- coding: utf-8 -*- import time from .finder import TIME_LIMIT, MAX_RUNS, BY_START, BY_END from .a_star import AStarFinder from pathfinding.core.diagonal_movement import DiagonalMovement class BiAStarFinder(AStarFinder): """ Similar to the default A* algorithm from a_star. """ def __init__(self, heuristic=None, weight=1, diagonal_movement=DiagonalMovement.never, time_limit=TIME_LIMIT, max_runs=MAX_RUNS): """ find shortest path using Bi-A* algorithm :param heuristic: heuristic used to calculate distance of 2 points (defaults to manhattan) :param weight: weight for the edges :param diagonal_movement: if diagonal movement is allowed (see enum in diagonal_movement) :param time_limit: max. runtime in seconds :param max_runs: max. amount of tries until we abort the search (optional, only if we enter huge grids and have time constrains) <=0 means there are no constrains and the code might run on any large map. """ super(BiAStarFinder, self).__init__( heuristic=heuristic, weight=weight, diagonal_movement=diagonal_movement, time_limit=time_limit, max_runs=max_runs) self.weighted = False def find_path(self, start, end, grid): """ find a path from start to end node on grid using the A* algorithm :param start: start node :param end: end node :param grid: grid that stores all possible steps/tiles as 2D-list :return: """ self.start_time = time.time() # execution time limitation self.runs = 0 # count number of iterations start_open_list = [start] start.g = 0 start.f = 0 start.opened = BY_START end_open_list = [end] end.g = 0 end.f = 0 end.opened = BY_END while len(start_open_list) > 0 and len(end_open_list) > 0: self.runs += 1 self.keep_running() path = self.check_neighbors(start, end, grid, start_open_list, open_value=BY_START, backtrace_by=BY_END) if path: return path, self.runs self.runs += 1 self.keep_running() path = self.check_neighbors(end, start, grid, end_open_list, open_value=BY_END, backtrace_by=BY_START) if path: return path, self.runs # failed to find path return [], self.runs
brean/python-pathfinding
pathfinding/finder/bi_a_star.py
Python
mit
2,744
#!/usr/bin/env python # coding=utf-8 from flask import render_template from . import main # @main.app_errorhandler(404) # def page_not_found(e): # return render_template('404.html'), 404 # # @main.app_errorhandler(500) # def internal_server_error(e): # return render_template('500.html'), 500
youqingkui/yinxiang_blog_py
app/main/errors.py
Python
mit
302
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from datospersonalesapp.models import Paciente from empleadosapp.models import Doctor from smart_selects.db_fields import ChainedForeignKey # Create your models here. ## opciones para indicar el tipo de consulta # TCONSULTA_CHOICES = ( ('PRV', 'Primera vez'), ('SUB', 'Subsecuente'), ) ## modelo de consulta, tabla generalapp_consulta # class Consulta(models.Model): # PK id = models.AutoField(primary_key=True) # FK hacia el expediente del pacientes cod_expediente = models.ForeignKey(Paciente, on_delete=models.CASCADE) # FK que permite identificar al doctor cod_doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) nit_paciente = models.CharField(max_length=17) fecha = models.DateTimeField(auto_now=True) # primera vez o subsecuente tipo_consulta = models.CharField(max_length=50, choices=TCONSULTA_CHOICES) consulta_por = models.TextField() visto_bueno = models.CharField(max_length=2, null=True, blank=True) presenta_enfermedad = models.TextField(blank=True) antecedentes_personales = models.TextField(blank=True) antecedentes_familiares = models.TextField(blank=True) exploracion_clinica = models.TextField() diagnostico_principal = models.CharField(max_length=500, blank=True) otros_diagnosticos = models.TextField(blank=True) tratamiento = models.TextField(blank=True) observaciones = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # ## modelo de medicamento, tabla generalapp_medicamento # # # class Medicamento(models.Model): # # PK id = models.AutoField(primary_key=True) # nombre_medicamento = models.CharField(max_length=500) # class Unidad(models.Model): # # PK id = models.AutoField(primary_key=True) # simbolo_unidad = models.CharField(max_length=50) # nombre_unidad = models.CharField(max_length=500) ## modelo de forma farmaceutica de los medicamentos, tabla generalapp_forma # class Forma(models.Model): # PK id = models.AutoField(primary_key=True) nombre_forma = models.CharField(max_length=200) ## modelo de via de administracion, tabla generalapp_via # class Via(models.Model): # PK id = models.AutoField(primary_key=True) nombre_via = models.CharField(max_length=200) ## # # class Via(models.Model): # # PK id = models.AutoField(primary_key=True) # nombre_via = models.CharField(max_length=500) ## modelo de receta, tabla generalapp_receta # class Receta(models.Model): # PK id = models.AutoField(primary_key=True) # FK hacia el expediente del paciente cod_expediente = models.ForeignKey(Paciente, on_delete=models.CASCADE) # FK que permite identificar al doctor cod_doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) # FK hacia la consulta cod_consulta = models.ForeignKey(Consulta, on_delete=models.CASCADE) fecha = models.DateTimeField(auto_now=True) medicamento = models.TextField() observaciones = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # class Compuesto(models.Model): # # PK id = models.AutoField(primary_key=True) # # FK hacia el expediente del paciente # cod_expediente = models.ForeignKey(Paciente, on_delete=models.CASCADE) # # FK que permite identificar al doctor # cod_doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) # # FK hacia la consulta # cod_consulta = models.ForeignKey(Consulta, on_delete=models.CASCADE) # fecha = models.DateTimeField(auto_now=True) # compuesto = models.TextField() # observaciones = models.TextField(blank=True) # created_at = models.DateTimeField(auto_now_add=True) # updated_at = models.DateTimeField(auto_now=True) class AreaLab(models.Model): codigoArea = models.AutoField(primary_key=True) nombreArea = models.CharField(max_length=200) def __str__(self): return '%s' % (self.nombreArea.encode('utf8')) class ExamenLab(models.Model): codigoExamen = models.AutoField(primary_key=True) codArea = models.ForeignKey(AreaLab, on_delete=models.CASCADE) nombreExamen = models.CharField(max_length=400) def __str__(self): return '%s' % (self.nombreExamen.encode('utf8')) # ## modelo de orden de laboratorio # class OrdenLab(models.Model): # PK id = models.AutoField(primary_key=True) # FK hacia el expediente del paciente cod_expediente = models.ForeignKey(Paciente, on_delete=models.CASCADE) # FK que permite identificar al doctor cod_doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) # FK hacia la consulta cod_consulta = models.ForeignKey(Consulta, on_delete=models.CASCADE) fecha = models.DateTimeField(auto_now=True) codArea = models.ForeignKey(AreaLab, on_delete=models.CASCADE) codExamen = ChainedForeignKey(ExamenLab, chained_field='codArea', chained_model_field='codArea', show_all=False, auto_choose=True) observaciones = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # ## modelo de referencia interna, tabla generalapp_referenciainterna # class ReferenciaInterna(models.Model): # PK id = models.AutoField(primary_key=True) # FK hacia el expediente del paciente cod_expediente = models.ForeignKey(Paciente, on_delete=models.CASCADE) # FK que permite identificar al doctor cod_doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) # FK hacia la consulta cod_consulta = models.ForeignKey(Consulta, on_delete=models.CASCADE) fecha = models.DateTimeField(auto_now=True) referido_a = models.CharField(max_length=500) nombre_paciente = models.CharField(max_length=200) tipo_paciente = models.CharField(max_length=200) procedencia_paciente = models.CharField(max_length=200) motivo_referencia = models.TextField() observaciones = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # ## modelo de referencia externa, tabla generalapp_referenciaexterna # class ReferenciaExterna(models.Model): # PK id = models.AutoField(primary_key=True) # FK hacia el expediente del paciente cod_expediente = models.ForeignKey(Paciente, on_delete=models.CASCADE) # FK que permite identificar al doctor cod_doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) # FK hacia la consulta cod_consulta = models.ForeignKey(Consulta, on_delete=models.CASCADE) fecha = models.DateTimeField(auto_now=True) referido_a = models.CharField(max_length=500) nombre_paciente = models.CharField(max_length=200) edad_paciente = models.PositiveSmallIntegerField() sexo_paciente = models.CharField(max_length=1) domicilio_paciente = models.CharField(max_length=500) telefono_paciente = models.CharField(max_length=9) presion_arterial = models.CharField(max_length=20) frecuencia_cardiaca = models.PositiveSmallIntegerField() frecuencia_respiratoria = models.PositiveSmallIntegerField() temperatura = models.DecimalField(max_digits=4, decimal_places=2) peso = models.PositiveSmallIntegerField() talla = models.DecimalField(max_digits=3, decimal_places=2) consulta_por = models.TextField() presenta_enfermedad = models.TextField(blank=True) antecedentes_personales = models.TextField(blank=True) examen_fisico = models.TextField() examenes_laboratorio = models.TextField(blank=True) impresion_diagnostica = models.TextField() observaciones = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # ## modelo de centro asistencial para referencia externa # class CentroAsistencial(models.Model): # PK id = models.AutoField(primary_key=True) nombre = models.CharField(max_length=200) def __str__(self): return '%s' % (self.nombre) # ## class db29179_cie10(models.Model): id10 = models.CharField(max_length=10, primary_key=True) dec10 = models.CharField(max_length=400) grp10 = models.CharField(max_length=200, null=True) def __str__(self): return '%s' % (self.dec10.encode('utf8'))
anderson7ru/bienestarues
generalapp/models.py
Python
mit
8,775
# Copyright 2012 by Wibowo Arindrarto. All rights reserved. # All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Custom indexing for Bio.SearchIO objects.""" import sys # Add path to Bio sys.path.append('../..') from Bio._py3k import StringIO from Bio._py3k import _bytes_to_string from Bio import bgzf from Bio.File import _IndexedSeqFileProxy, _open_for_random_access __docformat__ = "restructuredtext en" class SearchIndexer(_IndexedSeqFileProxy): """Base class for file format specific random access. Subclasses for each file format should define '_parser' and optionally 'get_raw' methods. """ def __init__(self, filename, **kwargs): self._handle = _open_for_random_access(filename) self._kwargs = kwargs def _parse(self, handle): return next(iter(self._parser(handle, **self._kwargs))) def get(self, offset): return self._parse(StringIO(_bytes_to_string(self.get_raw(offset))))
Ambuj-UF/ConCat-1.0
src/Utils/Bio/SearchIO/_index.py
Python
gpl-2.0
1,097
import sys import os import codecs from setuptools import setup, find_packages if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() VERSION = "0.1.1" with codecs.open('README.rst', encoding='utf-8') as f: README = f.read() with codecs.open('CHANGELOG.rst', encoding='utf-8') as f: CHANGELOG = f.read() setup( name='puppetboard', version=VERSION, author='Daniele Sluijters', author_email='[email protected]', packages=find_packages(), url='https://github.com/puppet-community/puppetboard', license='Apache License 2.0', description='Web frontend for PuppetDB', include_package_data=True, long_description='\n'.join((README, CHANGELOG)), install_requires=[ "Flask >= 0.10.1", "Flask-WTF >= 0.9.4, <= 0.9.5", "WTForms < 2.0", "pypuppetdb >= 0.2.1, < 0.3.0", ], keywords="puppet puppetdb puppetboard", classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Framework :: Flask', 'Intended Audience :: System Administrators', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], )
holstvoogd/puppetboard
setup.py
Python
apache-2.0
1,582
import os from django.conf import settings from django.core.files import File from django.core.files.images import ImageFile from django.test import override_settings from unittest import mock from nose.tools import eq_ import kitsune.upload.tasks from kitsune.questions.tests import QuestionFactory from kitsune.sumo.tests import TestCase from kitsune.upload.models import ImageAttachment from kitsune.upload.tasks import ( _scale_dimensions, _create_image_thumbnail, compress_image, generate_thumbnail, ) from kitsune.users.tests import UserFactory class ScaleDimensionsTestCase(TestCase): def test_scale_dimensions_default(self): """A square image of exact size is not scaled.""" ts = settings.THUMBNAIL_SIZE (width, height) = _scale_dimensions(ts, ts, ts) eq_(ts, width) eq_(ts, height) def test_small(self): """A small image is not scaled.""" ts = settings.THUMBNAIL_SIZE // 2 (width, height) = _scale_dimensions(ts, ts) eq_(ts, width) eq_(ts, height) def test_width_large(self): """An image with large width is scaled to width=MAX.""" ts = 120 (width, height) = _scale_dimensions(ts * 3 + 10, ts - 1, ts) eq_(ts, width) eq_(38, height) def test_large_height(self): """An image with large height is scaled to height=MAX.""" ts = 150 (width, height) = _scale_dimensions(ts - 2, ts * 2 + 9, ts) eq_(71, width) eq_(ts, height) def test_large_both_height(self): """An image with both large is scaled to the largest - height.""" ts = 150 (width, height) = _scale_dimensions(ts * 2 + 13, ts * 5 + 30, ts) eq_(60, width) eq_(ts, height) def test_large_both_width(self): """An image with both large is scaled to the largest - width.""" ts = 150 (width, height) = _scale_dimensions(ts * 20 + 8, ts * 4 + 36, ts) eq_(ts, width) eq_(31, height) class CreateThumbnailTestCase(TestCase): def test_create_image_thumbnail_default(self): """A thumbnail is created from an image file.""" thumb_content = _create_image_thumbnail("kitsune/upload/tests/media/test.jpg") actual_thumb = ImageFile(thumb_content) with open("kitsune/upload/tests/media/test_thumb.jpg", "rb") as f: expected_thumb = ImageFile(f) eq_(expected_thumb.width, actual_thumb.width) eq_(expected_thumb.height, actual_thumb.height) def test_create_image_thumbnail_avatar(self): """An avatar is created from an image file.""" thumb_content = _create_image_thumbnail( "kitsune/upload/tests/media/test.jpg", settings.AVATAR_SIZE, pad=True ) actual_thumb = ImageFile(thumb_content) eq_(settings.AVATAR_SIZE, actual_thumb.width) eq_(settings.AVATAR_SIZE, actual_thumb.height) class GenerateThumbnail(TestCase): def setUp(self): super(GenerateThumbnail, self).setUp() self.user = UserFactory() self.obj = QuestionFactory() def tearDown(self): ImageAttachment.objects.all().delete() def _image_with_thumbnail(self): image = ImageAttachment(content_object=self.obj, creator=self.user) with open("kitsune/upload/tests/media/test.jpg", "rb") as f: up_file = File(f) image.file.save(up_file.name, up_file, save=True) generate_thumbnail(image, "file", "thumbnail") return image def test_generate_thumbnail_default(self): """generate_thumbnail creates a thumbnail.""" image = self._image_with_thumbnail() eq_(90, image.thumbnail.width) eq_(120, image.thumbnail.height) def test_generate_no_file(self): """generate_thumbnail does not fail when no file is provided.""" image = ImageAttachment(content_object=self.obj, creator=self.user) generate_thumbnail(image, "file", "thumbnail") def test_generate_deleted_file(self): """generate_thumbnail does not fail if file doesn't actually exist.""" image = ImageAttachment(content_object=self.obj, creator=self.user) with open("kitsune/upload/tests/media/test.jpg", "rb") as f: up_file = File(f) image.file.save(up_file.name, up_file, save=True) # The field will be set but the file isn't there. os.remove(image.file.path) generate_thumbnail(image, "file", "thumbnail") def test_generate_thumbnail_twice(self): """generate_thumbnail replaces old thumbnail.""" image = self._image_with_thumbnail() old_path = image.thumbnail.path # The thumbnail exists. assert os.path.isfile(old_path) generate_thumbnail(image, "file", "thumbnail") new_path = image.thumbnail.path # The thumbnail was replaced. # Avoid potential failure when old thumbnail was saved 1 second ago. assert os.path.isfile(new_path) # Old file is either replaced or deleted. if old_path != new_path: assert not os.path.exists(old_path) class CompressImageTestCase(TestCase): def setUp(self): super(CompressImageTestCase, self).setUp() self.user = UserFactory() self.obj = QuestionFactory() def tearDown(self): ImageAttachment.objects.all().delete() def _uploaded_image(self, testfile="test.png"): image = ImageAttachment(content_object=self.obj, creator=self.user) with open("kitsune/upload/tests/media/" + testfile, "rb") as f: up_file = File(f) image.file.save(up_file.name, up_file, save=True) return image @override_settings(OPTIPNG_PATH="/dude") @mock.patch.object(kitsune.upload.tasks.subprocess, "call") def test_compressed_image_default(self, call): """uploaded image is compressed.""" image = self._uploaded_image() compress_image(image, "file") assert call.called @override_settings(OPTIPNG_PATH="/dude") @mock.patch.object(kitsune.upload.tasks.subprocess, "call") def test_compress_no_file(self, call): """compress_image does not fail when no file is provided.""" image = ImageAttachment(content_object=self.obj, creator=self.user) compress_image(image, "file") assert not call.called @override_settings(OPTIPNG_PATH="") @mock.patch.object(kitsune.upload.tasks.subprocess, "call") def test_compress_no_compression_software(self, call): """compress_image does not fail when no compression software.""" image = self._uploaded_image() compress_image(image, "file") assert not call.called @override_settings(OPTIPNG_PATH="/dude") @mock.patch.object(kitsune.upload.tasks.subprocess, "call") def test_compressed_image_animated(self, call): """uploaded animated gif image is not compressed.""" image = self._uploaded_image(testfile="animated.gif") compress_image(image, "file") assert not call.called
mozilla/kitsune
kitsune/upload/tests/test_tasks.py
Python
bsd-3-clause
7,113
import numpy as np import matplotlib.pyplot as plt def draw_matches(img1, kp1, img2, kp2, matches, color=None): """Draws lines between matching keypoints of two images. Keypoints not in a matching pair are not drawn. Places the images side by side in a new image and draws circles around each keypoint, with line segments connecting matching pairs. You can tweak the r, thickness, and figsize values as needed. Args: img1: An openCV image ndarray in a grayscale or color format. kp1: A list of cv2.KeyPoint objects for img1. img2: An openCV image ndarray of the same format and with the same element type as img1. kp2: A list of cv2.KeyPoint objects for img2. matches: A list of DMatch objects whose trainIdx attribute refers to img1 keypoints and whose queryIdx attribute refers to img2 keypoints. color: The color of the circles and connecting lines drawn on the images. A 3-tuple for color images, a scalar for grayscale images. If None, these values are randomly generated. """ # We're drawing them side by side. Get dimensions accordingly. # Handle both color and grayscale images. if len(img1.shape) == 3: new_shape = (max(img1.shape[0], img2.shape[0]), img1.shape[1]+img2.shape[1], img1.shape[2]) elif len(img1.shape) == 2: new_shape = (max(img1.shape[0], img2.shape[0]), img1.shape[1]+img2.shape[1]) new_img = np.zeros(new_shape, type(img1.flat[0])) # Place images onto the new image. new_img[0:img1.shape[0],0:img1.shape[1]] = img1 new_img[0:img2.shape[0],img1.shape[1]:img1.shape[1]+img2.shape[1]] = img2 # Draw lines between matches. Make sure to offset kp coords in second image appropriately. r = 15 thickness = 2 if color: c = color for m in matches: # Generate random color for RGB/BGR and grayscale images as needed. if not color: c = np.random.randint(0,256,3) if len(img1.shape) == 3 else np.random.randint(0,256) # So the keypoint locs are stored as a tuple of floats. cv2.line(), like most other things, # wants locs as a tuple of ints. end1 = tuple(np.round(kp1[m.trainIdx].pt).astype(int)) end2 = tuple(np.round(kp2[m.queryIdx].pt).astype(int) + np.array([img1.shape[1], 0])) cv2.line(new_img, end1, end2, c, thickness) cv2.circle(new_img, end1, r, c, thickness) cv2.circle(new_img, end2, r, c, thickness) plt.figure(figsize=(15,15)) plt.imshow(new_img) plt.show()
haiweiosu/Optical-Character-Recognition-using-Template-Matching-Object-Detection-in-Images
drawMatches.py
Python
apache-2.0
2,594
a = [] a.append('1')
amiraliakbari/sharif-mabani-python
by-session/ta-921/j9/ex1.py
Python
mit
21
""" Module that provides access to the underlying beamline control layer, HardwareRepository. The HardwareRepository consists of several HardwareObjects that can be directly accessed through this module. See the list of HardwareObjects that are "exported" below. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import logging import traceback import pickle from os import path import QueueManager # The HardwareRepository object HWR = None # Below, all the HardwareObjects made available through this module, # Initialized by the init function # BeamlineSetup beamline = None # XMLRPCServer actions = None # Plotting plotting = None def get_hwo(obj, name): """ Convenience method for getting HardwareObjects from the HardwareRepository. Retrieves the HardwareObject with the name <name> from either the HardwareRepository or from a parent HardwareObject passed as <obj> Handles exceptions with exit_with_error, which means that the application will exit on exception :param obj: HardwreObject or HardwareRepository :param str name: The name of the HardwreObject :rtype: HardwareObject :return: The HardwareObject """ ho = None try: if hasattr(obj, "getHardwareObject"): ho = obj.getHardwareObject(name) else: ho = obj.getObjectByRole(name) except Exception: msg = "Could not initialize hardware object corresponding to %s \n" msg = msg % name.upper() msg += "Make sure that all related device servers are running \n" msg += "Make sure that the detector software is running \n" exit_with_error(msg) return ho def exit_with_error(msg): """ Writes the traceback and msg to the log and exits the application :param str msg: Additional message to write to log """ logging.getLogger("HWR").error(traceback.format_exc()) if msg: logging.getLogger("HWR").error(msg) msg = "Could not initialize one or several hardware objects, stopped " msg += "at first error !" logging.getLogger("HWR").error(msg) logging.getLogger("HWR").error("Quitting server !") sys.exit(-1) def init(hwr, hwdir): """ Initializes the HardwareRepository with XML files read from hwdir. The hwr module must be imported at the very beginning of the application start-up to function correctly. This method can however be called later, so that initialization can be done when one wishes. :param hwr: HardwareRepository module :param str hwdir: Path to hardware objects :return: None """ global HWR try: hwr.init_hardware_repository(path.abspath(path.expanduser(hwdir))) _hwr = hwr.getHardwareRepository() _hwr.connect() HWR = _hwr except Exception: logging.getLogger("HWR").exception("") try: global beamline, actions, plotting beamline = hwr.beamline qm = QueueManager.QueueManager('MXCuBE3') from mxcube3.core import qutils qutils.init_signals(hwr.beamline.queue_model) except Exception: msg = "Could not initialize one or several hardware objects, " msg += "stopped at first error ! \n" msg += "Make sure That all devices servers are running \n" msg += "Make sure that the detector software is running \n" exit_with_error(msg)
marcus-oscarsson/mxcube3
mxcube3/blcontrol.py
Python
gpl-2.0
3,470