repo_name
stringlengths
5
100
path
stringlengths
4
375
copies
stringclasses
991 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
KhalidGit/flask
Work/TriviaMVA/TriviaMVA/env/Lib/site-packages/pip/_vendor/distlib/version.py
198
22996
# -*- coding: utf-8 -*- # # Copyright (C) 2012-2013 The Python Software Foundation. # See LICENSE.txt and CONTRIBUTORS.txt. # """ Implementation of a flexible versioning scheme providing support for PEP-386, distribute-compatible and semantic versioning. """ import logging import re from .compat import string_types __all__ = ['NormalizedVersion', 'NormalizedMatcher', 'LegacyVersion', 'LegacyMatcher', 'SemanticVersion', 'SemanticMatcher', 'UnsupportedVersionError', 'get_scheme'] logger = logging.getLogger(__name__) class UnsupportedVersionError(ValueError): """This is an unsupported version.""" pass class Version(object): def __init__(self, s): self._string = s = s.strip() self._parts = parts = self.parse(s) assert isinstance(parts, tuple) assert len(parts) > 0 def parse(self, s): raise NotImplementedError('please implement in a subclass') def _check_compatible(self, other): if type(self) != type(other): raise TypeError('cannot compare %r and %r' % (self, other)) def __eq__(self, other): self._check_compatible(other) return self._parts == other._parts def __ne__(self, other): return not self.__eq__(other) def __lt__(self, other): self._check_compatible(other) return self._parts < other._parts def __gt__(self, other): return not (self.__lt__(other) or self.__eq__(other)) def __le__(self, other): return self.__lt__(other) or self.__eq__(other) def __ge__(self, other): return self.__gt__(other) or self.__eq__(other) # See http://docs.python.org/reference/datamodel#object.__hash__ def __hash__(self): return hash(self._parts) def __repr__(self): return "%s('%s')" % (self.__class__.__name__, self._string) def __str__(self): return self._string @property def is_prerelease(self): raise NotImplementedError('Please implement in subclasses.') class Matcher(object): version_class = None dist_re = re.compile(r"^(\w[\s\w'.-]*)(\((.*)\))?") comp_re = re.compile(r'^(<=|>=|<|>|!=|==|~=)?\s*([^\s,]+)$') num_re = re.compile(r'^\d+(\.\d+)*$') # value is either a callable or the name of a method _operators = { '<': lambda v, c, p: v < c, '>': lambda v, c, p: v > c, '<=': lambda v, c, p: v == c or v < c, '>=': lambda v, c, p: v == c or v > c, '==': lambda v, c, p: v == c, # by default, compatible => >=. '~=': lambda v, c, p: v == c or v > c, '!=': lambda v, c, p: v != c, } def __init__(self, s): if self.version_class is None: raise ValueError('Please specify a version class') self._string = s = s.strip() m = self.dist_re.match(s) if not m: raise ValueError('Not valid: %r' % s) groups = m.groups('') self.name = groups[0].strip() self.key = self.name.lower() # for case-insensitive comparisons clist = [] if groups[2]: constraints = [c.strip() for c in groups[2].split(',')] for c in constraints: m = self.comp_re.match(c) if not m: raise ValueError('Invalid %r in %r' % (c, s)) groups = m.groups() op = groups[0] or '~=' s = groups[1] if s.endswith('.*'): if op not in ('==', '!='): raise ValueError('\'.*\' not allowed for ' '%r constraints' % op) # Could be a partial version (e.g. for '2.*') which # won't parse as a version, so keep it as a string vn, prefix = s[:-2], True if not self.num_re.match(vn): # Just to check that vn is a valid version self.version_class(vn) else: # Should parse as a version, so we can create an # instance for the comparison vn, prefix = self.version_class(s), False clist.append((op, vn, prefix)) self._parts = tuple(clist) def match(self, version): """ Check if the provided version matches the constraints. :param version: The version to match against this instance. :type version: Strring or :class:`Version` instance. """ if isinstance(version, string_types): version = self.version_class(version) for operator, constraint, prefix in self._parts: f = self._operators.get(operator) if isinstance(f, string_types): f = getattr(self, f) if not f: msg = ('%r not implemented ' 'for %s' % (operator, self.__class__.__name__)) raise NotImplementedError(msg) if not f(version, constraint, prefix): return False return True @property def exact_version(self): result = None if len(self._parts) == 1 and self._parts[0][0] == '==': result = self._parts[0][1] return result def _check_compatible(self, other): if type(self) != type(other) or self.name != other.name: raise TypeError('cannot compare %s and %s' % (self, other)) def __eq__(self, other): self._check_compatible(other) return self.key == other.key and self._parts == other._parts def __ne__(self, other): return not self.__eq__(other) # See http://docs.python.org/reference/datamodel#object.__hash__ def __hash__(self): return hash(self.key) + hash(self._parts) def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self._string) def __str__(self): return self._string PEP426_VERSION_RE = re.compile(r'^(\d+(\.\d+)*)((a|b|c|rc)(\d+))?' r'(\.(post)(\d+))?(\.(dev)(\d+))?' r'(-(\d+(\.\d+)?))?$') def _pep426_key(s): s = s.strip() m = PEP426_VERSION_RE.match(s) if not m: raise UnsupportedVersionError('Not a valid version: %s' % s) groups = m.groups() nums = tuple(int(v) for v in groups[0].split('.')) while len(nums) > 1 and nums[-1] == 0: nums = nums[:-1] pre = groups[3:5] post = groups[6:8] dev = groups[9:11] local = groups[12] if pre == (None, None): pre = () else: pre = pre[0], int(pre[1]) if post == (None, None): post = () else: post = post[0], int(post[1]) if dev == (None, None): dev = () else: dev = dev[0], int(dev[1]) if local is None: local = () else: local = tuple([int(s) for s in local.split('.')]) if not pre: # either before pre-release, or final release and after if not post and dev: # before pre-release pre = ('a', -1) # to sort before a0 else: pre = ('z',) # to sort after all pre-releases # now look at the state of post and dev. if not post: post = ('_',) # sort before 'a' if not dev: dev = ('final',) #print('%s -> %s' % (s, m.groups())) return nums, pre, post, dev, local _normalized_key = _pep426_key class NormalizedVersion(Version): """A rational version. Good: 1.2 # equivalent to "1.2.0" 1.2.0 1.2a1 1.2.3a2 1.2.3b1 1.2.3c1 1.2.3.4 TODO: fill this out Bad: 1 # mininum two numbers 1.2a # release level must have a release serial 1.2.3b """ def parse(self, s): result = _normalized_key(s) # _normalized_key loses trailing zeroes in the release # clause, since that's needed to ensure that X.Y == X.Y.0 == X.Y.0.0 # However, PEP 440 prefix matching needs it: for example, # (~= 1.4.5.0) matches differently to (~= 1.4.5.0.0). m = PEP426_VERSION_RE.match(s) # must succeed groups = m.groups() self._release_clause = tuple(int(v) for v in groups[0].split('.')) return result PREREL_TAGS = set(['a', 'b', 'c', 'rc', 'dev']) @property def is_prerelease(self): return any(t[0] in self.PREREL_TAGS for t in self._parts if t) def _match_prefix(x, y): x = str(x) y = str(y) if x == y: return True if not x.startswith(y): return False n = len(y) return x[n] == '.' class NormalizedMatcher(Matcher): version_class = NormalizedVersion # value is either a callable or the name of a method _operators = { '~=': '_match_compatible', '<': '_match_lt', '>': '_match_gt', '<=': '_match_le', '>=': '_match_ge', '==': '_match_eq', '!=': '_match_ne', } def _adjust_local(self, version, constraint, prefix): if prefix: strip_local = '-' not in constraint and version._parts[-1] else: # both constraint and version are # NormalizedVersion instances. # If constraint does not have a local component, # ensure the version doesn't, either. strip_local = not constraint._parts[-1] and version._parts[-1] if strip_local: s = version._string.split('-', 1)[0] version = self.version_class(s) return version, constraint def _match_lt(self, version, constraint, prefix): version, constraint = self._adjust_local(version, constraint, prefix) if version >= constraint: return False release_clause = constraint._release_clause pfx = '.'.join([str(i) for i in release_clause]) return not _match_prefix(version, pfx) def _match_gt(self, version, constraint, prefix): version, constraint = self._adjust_local(version, constraint, prefix) if version <= constraint: return False release_clause = constraint._release_clause pfx = '.'.join([str(i) for i in release_clause]) return not _match_prefix(version, pfx) def _match_le(self, version, constraint, prefix): version, constraint = self._adjust_local(version, constraint, prefix) return version <= constraint def _match_ge(self, version, constraint, prefix): version, constraint = self._adjust_local(version, constraint, prefix) return version >= constraint def _match_eq(self, version, constraint, prefix): version, constraint = self._adjust_local(version, constraint, prefix) if not prefix: result = (version == constraint) else: result = _match_prefix(version, constraint) return result def _match_ne(self, version, constraint, prefix): version, constraint = self._adjust_local(version, constraint, prefix) if not prefix: result = (version != constraint) else: result = not _match_prefix(version, constraint) return result def _match_compatible(self, version, constraint, prefix): version, constraint = self._adjust_local(version, constraint, prefix) if version == constraint: return True if version < constraint: return False release_clause = constraint._release_clause if len(release_clause) > 1: release_clause = release_clause[:-1] pfx = '.'.join([str(i) for i in release_clause]) return _match_prefix(version, pfx) _REPLACEMENTS = ( (re.compile('[.+-]$'), ''), # remove trailing puncts (re.compile(r'^[.](\d)'), r'0.\1'), # .N -> 0.N at start (re.compile('^[.-]'), ''), # remove leading puncts (re.compile(r'^\((.*)\)$'), r'\1'), # remove parentheses (re.compile(r'^v(ersion)?\s*(\d+)'), r'\2'), # remove leading v(ersion) (re.compile(r'^r(ev)?\s*(\d+)'), r'\2'), # remove leading v(ersion) (re.compile('[.]{2,}'), '.'), # multiple runs of '.' (re.compile(r'\b(alfa|apha)\b'), 'alpha'), # misspelt alpha (re.compile(r'\b(pre-alpha|prealpha)\b'), 'pre.alpha'), # standardise (re.compile(r'\(beta\)$'), 'beta'), # remove parentheses ) _SUFFIX_REPLACEMENTS = ( (re.compile('^[:~._+-]+'), ''), # remove leading puncts (re.compile('[,*")([\]]'), ''), # remove unwanted chars (re.compile('[~:+_ -]'), '.'), # replace illegal chars (re.compile('[.]{2,}'), '.'), # multiple runs of '.' (re.compile(r'\.$'), ''), # trailing '.' ) _NUMERIC_PREFIX = re.compile(r'(\d+(\.\d+)*)') def _suggest_semantic_version(s): """ Try to suggest a semantic form for a version for which _suggest_normalized_version couldn't come up with anything. """ result = s.strip().lower() for pat, repl in _REPLACEMENTS: result = pat.sub(repl, result) if not result: result = '0.0.0' # Now look for numeric prefix, and separate it out from # the rest. #import pdb; pdb.set_trace() m = _NUMERIC_PREFIX.match(result) if not m: prefix = '0.0.0' suffix = result else: prefix = m.groups()[0].split('.') prefix = [int(i) for i in prefix] while len(prefix) < 3: prefix.append(0) if len(prefix) == 3: suffix = result[m.end():] else: suffix = '.'.join([str(i) for i in prefix[3:]]) + result[m.end():] prefix = prefix[:3] prefix = '.'.join([str(i) for i in prefix]) suffix = suffix.strip() if suffix: #import pdb; pdb.set_trace() # massage the suffix. for pat, repl in _SUFFIX_REPLACEMENTS: suffix = pat.sub(repl, suffix) if not suffix: result = prefix else: sep = '-' if 'dev' in suffix else '+' result = prefix + sep + suffix if not is_semver(result): result = None return result def _suggest_normalized_version(s): """Suggest a normalized version close to the given version string. If you have a version string that isn't rational (i.e. NormalizedVersion doesn't like it) then you might be able to get an equivalent (or close) rational version from this function. This does a number of simple normalizations to the given string, based on observation of versions currently in use on PyPI. Given a dump of those version during PyCon 2009, 4287 of them: - 2312 (53.93%) match NormalizedVersion without change with the automatic suggestion - 3474 (81.04%) match when using this suggestion method @param s {str} An irrational version string. @returns A rational version string, or None, if couldn't determine one. """ try: _normalized_key(s) return s # already rational except UnsupportedVersionError: pass rs = s.lower() # part of this could use maketrans for orig, repl in (('-alpha', 'a'), ('-beta', 'b'), ('alpha', 'a'), ('beta', 'b'), ('rc', 'c'), ('-final', ''), ('-pre', 'c'), ('-release', ''), ('.release', ''), ('-stable', ''), ('+', '.'), ('_', '.'), (' ', ''), ('.final', ''), ('final', '')): rs = rs.replace(orig, repl) # if something ends with dev or pre, we add a 0 rs = re.sub(r"pre$", r"pre0", rs) rs = re.sub(r"dev$", r"dev0", rs) # if we have something like "b-2" or "a.2" at the end of the # version, that is pobably beta, alpha, etc # let's remove the dash or dot rs = re.sub(r"([abc]|rc)[\-\.](\d+)$", r"\1\2", rs) # 1.0-dev-r371 -> 1.0.dev371 # 0.1-dev-r79 -> 0.1.dev79 rs = re.sub(r"[\-\.](dev)[\-\.]?r?(\d+)$", r".\1\2", rs) # Clean: 2.0.a.3, 2.0.b1, 0.9.0~c1 rs = re.sub(r"[.~]?([abc])\.?", r"\1", rs) # Clean: v0.3, v1.0 if rs.startswith('v'): rs = rs[1:] # Clean leading '0's on numbers. #TODO: unintended side-effect on, e.g., "2003.05.09" # PyPI stats: 77 (~2%) better rs = re.sub(r"\b0+(\d+)(?!\d)", r"\1", rs) # Clean a/b/c with no version. E.g. "1.0a" -> "1.0a0". Setuptools infers # zero. # PyPI stats: 245 (7.56%) better rs = re.sub(r"(\d+[abc])$", r"\g<1>0", rs) # the 'dev-rNNN' tag is a dev tag rs = re.sub(r"\.?(dev-r|dev\.r)\.?(\d+)$", r".dev\2", rs) # clean the - when used as a pre delimiter rs = re.sub(r"-(a|b|c)(\d+)$", r"\1\2", rs) # a terminal "dev" or "devel" can be changed into ".dev0" rs = re.sub(r"[\.\-](dev|devel)$", r".dev0", rs) # a terminal "dev" can be changed into ".dev0" rs = re.sub(r"(?![\.\-])dev$", r".dev0", rs) # a terminal "final" or "stable" can be removed rs = re.sub(r"(final|stable)$", "", rs) # The 'r' and the '-' tags are post release tags # 0.4a1.r10 -> 0.4a1.post10 # 0.9.33-17222 -> 0.9.33.post17222 # 0.9.33-r17222 -> 0.9.33.post17222 rs = re.sub(r"\.?(r|-|-r)\.?(\d+)$", r".post\2", rs) # Clean 'r' instead of 'dev' usage: # 0.9.33+r17222 -> 0.9.33.dev17222 # 1.0dev123 -> 1.0.dev123 # 1.0.git123 -> 1.0.dev123 # 1.0.bzr123 -> 1.0.dev123 # 0.1a0dev.123 -> 0.1a0.dev123 # PyPI stats: ~150 (~4%) better rs = re.sub(r"\.?(dev|git|bzr)\.?(\d+)$", r".dev\2", rs) # Clean '.pre' (normalized from '-pre' above) instead of 'c' usage: # 0.2.pre1 -> 0.2c1 # 0.2-c1 -> 0.2c1 # 1.0preview123 -> 1.0c123 # PyPI stats: ~21 (0.62%) better rs = re.sub(r"\.?(pre|preview|-c)(\d+)$", r"c\g<2>", rs) # Tcl/Tk uses "px" for their post release markers rs = re.sub(r"p(\d+)$", r".post\1", rs) try: _normalized_key(rs) except UnsupportedVersionError: rs = None return rs # # Legacy version processing (distribute-compatible) # _VERSION_PART = re.compile(r'([a-z]+|\d+|[\.-])', re.I) _VERSION_REPLACE = { 'pre': 'c', 'preview': 'c', '-': 'final-', 'rc': 'c', 'dev': '@', '': None, '.': None, } def _legacy_key(s): def get_parts(s): result = [] for p in _VERSION_PART.split(s.lower()): p = _VERSION_REPLACE.get(p, p) if p: if '0' <= p[:1] <= '9': p = p.zfill(8) else: p = '*' + p result.append(p) result.append('*final') return result result = [] for p in get_parts(s): if p.startswith('*'): if p < '*final': while result and result[-1] == '*final-': result.pop() while result and result[-1] == '00000000': result.pop() result.append(p) return tuple(result) class LegacyVersion(Version): def parse(self, s): return _legacy_key(s) @property def is_prerelease(self): result = False for x in self._parts: if (isinstance(x, string_types) and x.startswith('*') and x < '*final'): result = True break return result class LegacyMatcher(Matcher): version_class = LegacyVersion _operators = dict(Matcher._operators) _operators['~='] = '_match_compatible' numeric_re = re.compile('^(\d+(\.\d+)*)') def _match_compatible(self, version, constraint, prefix): if version < constraint: return False m = self.numeric_re.match(str(constraint)) if not m: logger.warning('Cannot compute compatible match for version %s ' ' and constraint %s', version, constraint) return True s = m.groups()[0] if '.' in s: s = s.rsplit('.', 1)[0] return _match_prefix(version, s) # # Semantic versioning # _SEMVER_RE = re.compile(r'^(\d+)\.(\d+)\.(\d+)' r'(-[a-z0-9]+(\.[a-z0-9-]+)*)?' r'(\+[a-z0-9]+(\.[a-z0-9-]+)*)?$', re.I) def is_semver(s): return _SEMVER_RE.match(s) def _semantic_key(s): def make_tuple(s, absent): if s is None: result = (absent,) else: parts = s[1:].split('.') # We can't compare ints and strings on Python 3, so fudge it # by zero-filling numeric values so simulate a numeric comparison result = tuple([p.zfill(8) if p.isdigit() else p for p in parts]) return result m = is_semver(s) if not m: raise UnsupportedVersionError(s) groups = m.groups() major, minor, patch = [int(i) for i in groups[:3]] # choose the '|' and '*' so that versions sort correctly pre, build = make_tuple(groups[3], '|'), make_tuple(groups[5], '*') return (major, minor, patch), pre, build class SemanticVersion(Version): def parse(self, s): return _semantic_key(s) @property def is_prerelease(self): return self._parts[1][0] != '|' class SemanticMatcher(Matcher): version_class = SemanticVersion class VersionScheme(object): def __init__(self, key, matcher, suggester=None): self.key = key self.matcher = matcher self.suggester = suggester def is_valid_version(self, s): try: self.matcher.version_class(s) result = True except UnsupportedVersionError: result = False return result def is_valid_matcher(self, s): try: self.matcher(s) result = True except UnsupportedVersionError: result = False return result def is_valid_constraint_list(self, s): """ Used for processing some metadata fields """ return self.is_valid_matcher('dummy_name (%s)' % s) def suggest(self, s): if self.suggester is None: result = None else: result = self.suggester(s) return result _SCHEMES = { 'normalized': VersionScheme(_normalized_key, NormalizedMatcher, _suggest_normalized_version), 'legacy': VersionScheme(_legacy_key, LegacyMatcher, lambda self, s: s), 'semantic': VersionScheme(_semantic_key, SemanticMatcher, _suggest_semantic_version), } _SCHEMES['default'] = _SCHEMES['normalized'] def get_scheme(name): if name not in _SCHEMES: raise ValueError('unknown scheme name: %r' % name) return _SCHEMES[name]
apache-2.0
buqing2009/MissionPlanner
Lib/site-packages/scipy/special/tests/test_specfun.py
53
3683
# Corresponds to a small subset of scipy.special.specfun # that has features that were ported manually from fwrap # to f2py. # It was assumed that SciPy 0.7.0 shipped with Ubuntu Lucid # (using f2py) returned the correct values. # import numpy as np from numpy import array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp, log, zeros, \ sqrt, asarray, inf, nan_to_num, real, arctan, float_ from numpy.testing import assert_equal, assert_almost_equal, assert_array_equal, \ assert_array_almost_equal, assert_approx_equal, assert_, \ rand, dec, TestCase, run_module_suite, assert_raises from scipy.special import specfun from testutils import assert_tol_equal, with_special_errors def assert_not_raises(func, *args, **kw): # since test failure and test error is not the same try: func(*args, **kw) except: assert_(False) class TestSpecfun(TestCase): def test_clqmn(self): a, b = specfun.clqmn(2, 2, 1.0+1.0j) assert_tol_equal(a, [[(0.40235947810852513-0.5535743588970452j), (-0.044066162994429635-0.15121488078852013j), (-0.040456662363126783-0.016134386225902096j)], [(-0.35157758425414298+0.56886448100578324j), (0.10003085479304373+0.29390281413581559j), (0.12153929047997031+0.044072044775011442j)], [(0.40000000000000002-1.2000000000000004j), (-0.40000000000000008-0.80000000000000004j), (-0.48563228094330374-0.12512005465771367j)]]) assert_tol_equal(b, [[(0.20000000000000001+0.40000000000000002j), (0.20235947810852509+0.046425641102954752j), (0.067801511016711016-0.053644642365560456j)], [(-0.27100317175264133-0.32471944675364245j), (-0.39937475906618558-0.054954225049664206j), (-0.19116269416515053+0.16816038356718191j)], [(0.88000000000000012+0.16000000000000003j), (1.1200000000000001-0.16000000000000003j), (0.61560302203342199-0.747289284731121j)]]) # Integer (and real) argument assert_tol_equal(specfun.clqmn(1, 1, 3)[0], [[(0.34657359027997264+0j), (0.039720770839917957+0j)], [(-0.35355339059327373+0j), (-0.080402028311274076+0j)]]) def test_clqn(self): a, b = specfun.clqn(2, 1.0+2.0j) assert_tol_equal(a, [(0.17328679513998635-0.3926990816987242j), (-0.041315041462565365-0.046125491418751496j), (-0.010239485507586708+0.0032161793335387366j)]) assert_tol_equal(b, [(0.125+0.125j), (0.048286795139986335-0.017699081698724153j), (0.0010548756123039084-0.0133764742562545j)]) def test_clpn(self): a, b = specfun.clpn(2, 1+2j) assert_tol_equal(a, [(1+0j), (1+2j), (-5+6j)]) assert_tol_equal(b, [0j, (1+0j), (3+6j)]) def test_check(self): assert_raises(Exception, specfun.lamn, -1, 1.2) assert_raises(Exception, specfun.lamn, 0, 1.2) assert_not_raises(specfun.lamn, 1, 1.2) assert_raises(Exception, specfun.fcszo, 0, 3) assert_raises(Exception, specfun.fcszo, 1, 0) assert_not_raises(specfun.fcszo, 1, 1) if __name__ == "__main__": run_module_suite()
gpl-3.0
smalls257/VRvisu
Library/External.LCA_RESTRICTED/Languages/CPython/27/Lib/distutils/command/install_headers.py
251
1346
"""distutils.command.install_headers Implements the Distutils 'install_headers' command, to install C/C++ header files to the Python include directory.""" __revision__ = "$Id$" from distutils.core import Command # XXX force is never used class install_headers(Command): description = "install C/C++ header files" user_options = [('install-dir=', 'd', "directory to install header files to"), ('force', 'f', "force installation (overwrite existing files)"), ] boolean_options = ['force'] def initialize_options(self): self.install_dir = None self.force = 0 self.outfiles = [] def finalize_options(self): self.set_undefined_options('install', ('install_headers', 'install_dir'), ('force', 'force')) def run(self): headers = self.distribution.headers if not headers: return self.mkpath(self.install_dir) for header in headers: (out, _) = self.copy_file(header, self.install_dir) self.outfiles.append(out) def get_inputs(self): return self.distribution.headers or [] def get_outputs(self): return self.outfiles # class install_headers
gpl-3.0
tmerrick1/spack
lib/spack/external/_pytest/doctest.py
23
13170
""" discover and run doctests in modules and test files.""" from __future__ import absolute_import, division, print_function import traceback import pytest from _pytest._code.code import ExceptionInfo, ReprFileLocation, TerminalRepr from _pytest.fixtures import FixtureRequest DOCTEST_REPORT_CHOICE_NONE = 'none' DOCTEST_REPORT_CHOICE_CDIFF = 'cdiff' DOCTEST_REPORT_CHOICE_NDIFF = 'ndiff' DOCTEST_REPORT_CHOICE_UDIFF = 'udiff' DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = 'only_first_failure' DOCTEST_REPORT_CHOICES = ( DOCTEST_REPORT_CHOICE_NONE, DOCTEST_REPORT_CHOICE_CDIFF, DOCTEST_REPORT_CHOICE_NDIFF, DOCTEST_REPORT_CHOICE_UDIFF, DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE, ) def pytest_addoption(parser): parser.addini('doctest_optionflags', 'option flags for doctests', type="args", default=["ELLIPSIS"]) parser.addini("doctest_encoding", 'encoding used for doctest files', default="utf-8") group = parser.getgroup("collect") group.addoption("--doctest-modules", action="store_true", default=False, help="run doctests in all .py modules", dest="doctestmodules") group.addoption("--doctest-report", type=str.lower, default="udiff", help="choose another output format for diffs on doctest failure", choices=DOCTEST_REPORT_CHOICES, dest="doctestreport") group.addoption("--doctest-glob", action="append", default=[], metavar="pat", help="doctests file matching pattern, default: test*.txt", dest="doctestglob") group.addoption("--doctest-ignore-import-errors", action="store_true", default=False, help="ignore doctest ImportErrors", dest="doctest_ignore_import_errors") def pytest_collect_file(path, parent): config = parent.config if path.ext == ".py": if config.option.doctestmodules: return DoctestModule(path, parent) elif _is_doctest(config, path, parent): return DoctestTextfile(path, parent) def _is_doctest(config, path, parent): if path.ext in ('.txt', '.rst') and parent.session.isinitpath(path): return True globs = config.getoption("doctestglob") or ['test*.txt'] for glob in globs: if path.check(fnmatch=glob): return True return False class ReprFailDoctest(TerminalRepr): def __init__(self, reprlocation, lines): self.reprlocation = reprlocation self.lines = lines def toterminal(self, tw): for line in self.lines: tw.line(line) self.reprlocation.toterminal(tw) class DoctestItem(pytest.Item): def __init__(self, name, parent, runner=None, dtest=None): super(DoctestItem, self).__init__(name, parent) self.runner = runner self.dtest = dtest self.obj = None self.fixture_request = None def setup(self): if self.dtest is not None: self.fixture_request = _setup_fixtures(self) globs = dict(getfixture=self.fixture_request.getfixturevalue) for name, value in self.fixture_request.getfixturevalue('doctest_namespace').items(): globs[name] = value self.dtest.globs.update(globs) def runtest(self): _check_all_skipped(self.dtest) self.runner.run(self.dtest) def repr_failure(self, excinfo): import doctest if excinfo.errisinstance((doctest.DocTestFailure, doctest.UnexpectedException)): doctestfailure = excinfo.value example = doctestfailure.example test = doctestfailure.test filename = test.filename if test.lineno is None: lineno = None else: lineno = test.lineno + example.lineno + 1 message = excinfo.type.__name__ reprlocation = ReprFileLocation(filename, lineno, message) checker = _get_checker() report_choice = _get_report_choice(self.config.getoption("doctestreport")) if lineno is not None: lines = doctestfailure.test.docstring.splitlines(False) # add line numbers to the left of the error message lines = ["%03d %s" % (i + test.lineno + 1, x) for (i, x) in enumerate(lines)] # trim docstring error lines to 10 lines = lines[max(example.lineno - 9, 0):example.lineno + 1] else: lines = ['EXAMPLE LOCATION UNKNOWN, not showing all tests of that example'] indent = '>>>' for line in example.source.splitlines(): lines.append('??? %s %s' % (indent, line)) indent = '...' if excinfo.errisinstance(doctest.DocTestFailure): lines += checker.output_difference(example, doctestfailure.got, report_choice).split("\n") else: inner_excinfo = ExceptionInfo(excinfo.value.exc_info) lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)] lines += traceback.format_exception(*excinfo.value.exc_info) return ReprFailDoctest(reprlocation, lines) else: return super(DoctestItem, self).repr_failure(excinfo) def reportinfo(self): return self.fspath, self.dtest.lineno, "[doctest] %s" % self.name def _get_flag_lookup(): import doctest return dict(DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1, DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE, NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE, ELLIPSIS=doctest.ELLIPSIS, IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL, COMPARISON_FLAGS=doctest.COMPARISON_FLAGS, ALLOW_UNICODE=_get_allow_unicode_flag(), ALLOW_BYTES=_get_allow_bytes_flag(), ) def get_optionflags(parent): optionflags_str = parent.config.getini("doctest_optionflags") flag_lookup_table = _get_flag_lookup() flag_acc = 0 for flag in optionflags_str: flag_acc |= flag_lookup_table[flag] return flag_acc class DoctestTextfile(pytest.Module): obj = None def collect(self): import doctest # inspired by doctest.testfile; ideally we would use it directly, # but it doesn't support passing a custom checker encoding = self.config.getini("doctest_encoding") text = self.fspath.read_text(encoding) filename = str(self.fspath) name = self.fspath.basename globs = {'__name__': '__main__'} optionflags = get_optionflags(self) runner = doctest.DebugRunner(verbose=0, optionflags=optionflags, checker=_get_checker()) _fix_spoof_python2(runner, encoding) parser = doctest.DocTestParser() test = parser.get_doctest(text, globs, name, filename, 0) if test.examples: yield DoctestItem(test.name, self, runner, test) def _check_all_skipped(test): """raises pytest.skip() if all examples in the given DocTest have the SKIP option set. """ import doctest all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples) if all_skipped: pytest.skip('all tests skipped by +SKIP option') class DoctestModule(pytest.Module): def collect(self): import doctest if self.fspath.basename == "conftest.py": module = self.config.pluginmanager._importconftest(self.fspath) else: try: module = self.fspath.pyimport() except ImportError: if self.config.getvalue('doctest_ignore_import_errors'): pytest.skip('unable to import module %r' % self.fspath) else: raise # uses internal doctest module parsing mechanism finder = doctest.DocTestFinder() optionflags = get_optionflags(self) runner = doctest.DebugRunner(verbose=0, optionflags=optionflags, checker=_get_checker()) for test in finder.find(module, module.__name__): if test.examples: # skip empty doctests yield DoctestItem(test.name, self, runner, test) def _setup_fixtures(doctest_item): """ Used by DoctestTextfile and DoctestItem to setup fixture information. """ def func(): pass doctest_item.funcargs = {} fm = doctest_item.session._fixturemanager doctest_item._fixtureinfo = fm.getfixtureinfo(node=doctest_item, func=func, cls=None, funcargs=False) fixture_request = FixtureRequest(doctest_item) fixture_request._fillfixtures() return fixture_request def _get_checker(): """ Returns a doctest.OutputChecker subclass that takes in account the ALLOW_UNICODE option to ignore u'' prefixes in strings and ALLOW_BYTES to strip b'' prefixes. Useful when the same doctest should run in Python 2 and Python 3. An inner class is used to avoid importing "doctest" at the module level. """ if hasattr(_get_checker, 'LiteralsOutputChecker'): return _get_checker.LiteralsOutputChecker() import doctest import re class LiteralsOutputChecker(doctest.OutputChecker): """ Copied from doctest_nose_plugin.py from the nltk project: https://github.com/nltk/nltk Further extended to also support byte literals. """ _unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE) _bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE) def check_output(self, want, got, optionflags): res = doctest.OutputChecker.check_output(self, want, got, optionflags) if res: return True allow_unicode = optionflags & _get_allow_unicode_flag() allow_bytes = optionflags & _get_allow_bytes_flag() if not allow_unicode and not allow_bytes: return False else: # pragma: no cover def remove_prefixes(regex, txt): return re.sub(regex, r'\1\2', txt) if allow_unicode: want = remove_prefixes(self._unicode_literal_re, want) got = remove_prefixes(self._unicode_literal_re, got) if allow_bytes: want = remove_prefixes(self._bytes_literal_re, want) got = remove_prefixes(self._bytes_literal_re, got) res = doctest.OutputChecker.check_output(self, want, got, optionflags) return res _get_checker.LiteralsOutputChecker = LiteralsOutputChecker return _get_checker.LiteralsOutputChecker() def _get_allow_unicode_flag(): """ Registers and returns the ALLOW_UNICODE flag. """ import doctest return doctest.register_optionflag('ALLOW_UNICODE') def _get_allow_bytes_flag(): """ Registers and returns the ALLOW_BYTES flag. """ import doctest return doctest.register_optionflag('ALLOW_BYTES') def _get_report_choice(key): """ This function returns the actual `doctest` module flag value, we want to do it as late as possible to avoid importing `doctest` and all its dependencies when parsing options, as it adds overhead and breaks tests. """ import doctest return { DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF, DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF, DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF, DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE, DOCTEST_REPORT_CHOICE_NONE: 0, }[key] def _fix_spoof_python2(runner, encoding): """ Installs a "SpoofOut" into the given DebugRunner so it properly deals with unicode output. This should patch only doctests for text files because they don't have a way to declare their encoding. Doctests in docstrings from Python modules don't have the same problem given that Python already decoded the strings. This fixes the problem related in issue #2434. """ from _pytest.compat import _PY2 if not _PY2: return from doctest import _SpoofOut class UnicodeSpoof(_SpoofOut): def getvalue(self): result = _SpoofOut.getvalue(self) if encoding: result = result.decode(encoding) return result runner._fakeout = UnicodeSpoof() @pytest.fixture(scope='session') def doctest_namespace(): """ Inject names into the doctest namespace. """ return dict()
lgpl-2.1
jumpserver/jumpserver
apps/ops/ansible/runner.py
1
8827
# ~*~ coding: utf-8 ~*~ import os import shutil from collections import namedtuple from ansible import context from ansible.playbook import Playbook from ansible.module_utils.common.collections import ImmutableDict from ansible.executor.task_queue_manager import TaskQueueManager from ansible.vars.manager import VariableManager from ansible.parsing.dataloader import DataLoader from ansible.executor.playbook_executor import PlaybookExecutor from ansible.playbook.play import Play import ansible.constants as C from .callback import ( AdHocResultCallback, PlaybookResultCallBack, CommandResultCallback ) from common.utils import get_logger from .exceptions import AnsibleError from .display import AdHocDisplay __all__ = ["AdHocRunner", "PlayBookRunner", "CommandRunner"] C.HOST_KEY_CHECKING = False logger = get_logger(__name__) Options = namedtuple('Options', [ 'listtags', 'listtasks', 'listhosts', 'syntax', 'connection', 'module_path', 'forks', 'remote_user', 'private_key_file', 'timeout', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args', 'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check', 'extra_vars', 'playbook_path', 'passwords', 'diff', 'gathering', 'remote_tmp', ]) def get_default_options(): options = dict( syntax=False, timeout=30, connection='ssh', forks=10, remote_user='root', private_key_file=None, become=None, become_method=None, become_user=None, verbosity=1, check=False, diff=False, gathering='implicit', remote_tmp='/tmp/.ansible' ) return options # JumpServer not use playbook class PlayBookRunner: """ 用于执行AnsiblePlaybook的接口.简化Playbook对象的使用. """ # Default results callback results_callback_class = PlaybookResultCallBack loader_class = DataLoader variable_manager_class = VariableManager options = get_default_options() def __init__(self, inventory=None, options=None): """ :param options: Ansible options like ansible.cfg :param inventory: Ansible inventory """ if options: self.options = options C.RETRY_FILES_ENABLED = False self.inventory = inventory self.loader = self.loader_class() self.results_callback = self.results_callback_class() self.playbook_path = options.playbook_path self.variable_manager = self.variable_manager_class( loader=self.loader, inventory=self.inventory ) self.passwords = options.passwords self.__check() def __check(self): if self.options.playbook_path is None or \ not os.path.exists(self.options.playbook_path): raise AnsibleError( "Not Found the playbook file: {}.".format(self.options.playbook_path) ) if not self.inventory.list_hosts('all'): raise AnsibleError('Inventory is empty') def run(self): executor = PlaybookExecutor( playbooks=[self.playbook_path], inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, passwords={"conn_pass": self.passwords} ) context.CLIARGS = ImmutableDict(self.options) if executor._tqm: executor._tqm._stdout_callback = self.results_callback executor.run() executor._tqm.cleanup() return self.results_callback.output class AdHocRunner: """ ADHoc Runner接口 """ results_callback_class = AdHocResultCallback results_callback = None loader_class = DataLoader variable_manager_class = VariableManager default_options = get_default_options() command_modules_choices = ('shell', 'raw', 'command', 'script', 'win_shell') def __init__(self, inventory, options=None): self.options = self.update_options(options) self.inventory = inventory self.loader = DataLoader() self.variable_manager = VariableManager( loader=self.loader, inventory=self.inventory ) def get_result_callback(self, execution_id=None): return self.__class__.results_callback_class(display=AdHocDisplay(execution_id)) @staticmethod def check_module_args(module_name, module_args=''): if module_name in C.MODULE_REQUIRE_ARGS and not module_args: err = "No argument passed to '%s' module." % module_name raise AnsibleError(err) def check_pattern(self, pattern): if not pattern: raise AnsibleError("Pattern `{}` is not valid!".format(pattern)) if not self.inventory.list_hosts("all"): raise AnsibleError("Inventory is empty.") if not self.inventory.list_hosts(pattern): raise AnsibleError( "pattern: %s dose not match any hosts." % pattern ) def clean_args(self, module, args): if not args: return '' if module not in self.command_modules_choices: return args if isinstance(args, str): if args.startswith('executable='): _args = args.split(' ') executable, command = _args[0].split('=')[1], ' '.join(_args[1:]) args = {'executable': executable, '_raw_params': command} else: args = {'_raw_params': args} return args else: return args def clean_tasks(self, tasks): cleaned_tasks = [] for task in tasks: module = task['action']['module'] args = task['action'].get('args') cleaned_args = self.clean_args(module, args) task['action']['args'] = cleaned_args self.check_module_args(module, cleaned_args) cleaned_tasks.append(task) return cleaned_tasks def update_options(self, options): _options = {k: v for k, v in self.default_options.items()} if options and isinstance(options, dict): _options.update(options) return _options def set_control_master_if_need(self, cleaned_tasks): modules = [task.get('action', {}).get('module') for task in cleaned_tasks] if {'ping', 'win_ping'} & set(modules): self.results_callback.context = { 'ssh_args': '-C -o ControlMaster=no' } def run(self, tasks, pattern, play_name='Ansible Ad-hoc', gather_facts='no', execution_id=None): """ :param tasks: [{'action': {'module': 'shell', 'args': 'ls'}, ...}, ] :param pattern: all, *, or others :param play_name: The play name :param gather_facts: :return: """ self.check_pattern(pattern) self.results_callback = self.get_result_callback(execution_id) cleaned_tasks = self.clean_tasks(tasks) self.set_control_master_if_need(cleaned_tasks) context.CLIARGS = ImmutableDict(self.options) play_source = dict( name=play_name, hosts=pattern, gather_facts=gather_facts, tasks=cleaned_tasks ) play = Play().load( play_source, variable_manager=self.variable_manager, loader=self.loader, ) loader = DataLoader() # used in start callback playbook = Playbook(loader) playbook._entries.append(play) playbook._file_name = '__adhoc_playbook__' tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, stdout_callback=self.results_callback, passwords={"conn_pass": self.options.get("password", "")} ) try: tqm.send_callback('v2_playbook_on_start', playbook) tqm.run(play) tqm.send_callback('v2_playbook_on_stats', tqm._stats) return self.results_callback except Exception as e: raise AnsibleError(e) finally: if tqm is not None: tqm.cleanup() shutil.rmtree(C.DEFAULT_LOCAL_TMP, True) self.results_callback.close() class CommandRunner(AdHocRunner): results_callback_class = CommandResultCallback modules_choices = ('shell', 'raw', 'command', 'script', 'win_shell') def execute(self, cmd, pattern, module='shell'): if module and module not in self.modules_choices: raise AnsibleError("Module should in {}".format(self.modules_choices)) tasks = [ {"action": {"module": module, "args": cmd}} ] return self.run(tasks, pattern, play_name=cmd)
gpl-2.0
luiseduardohdbackup/odoo
addons/mrp_repair/wizard/cancel_repair.py
384
3683
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import osv,fields from openerp.tools.translate import _ class repair_cancel(osv.osv_memory): _name = 'mrp.repair.cancel' _description = 'Cancel Repair' def cancel_repair(self, cr, uid, ids, context=None): """ Cancels the repair @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of IDs selected @param context: A standard dictionary @return: """ if context is None: context = {} record_id = context and context.get('active_id', False) or False assert record_id, _('Active ID not Found') repair_order_obj = self.pool.get('mrp.repair') repair_line_obj = self.pool.get('mrp.repair.line') repair_order = repair_order_obj.browse(cr, uid, record_id, context=context) if repair_order.invoiced or repair_order.invoice_method == 'none': repair_order_obj.action_cancel(cr, uid, [record_id], context=context) else: raise osv.except_osv(_('Warning!'),_('Repair order is not invoiced.')) return {'type': 'ir.actions.act_window_close'} def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): """ Changes the view dynamically @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param context: A standard dictionary @return: New arch of view. """ if context is None: context = {} res = super(repair_cancel, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False) record_id = context and context.get('active_id', False) or False active_model = context.get('active_model') if not record_id or (active_model and active_model != 'mrp.repair'): return res repair_order = self.pool.get('mrp.repair').browse(cr, uid, record_id, context=context) if not repair_order.invoiced: res['arch'] = """ <form string="Cancel Repair" version="7.0"> <header> <button name="cancel_repair" string="_Yes" type="object" class="oe_highlight"/> or <button string="Cancel" class="oe_link" special="cancel"/> </header> <label string="Do you want to continue?"/> </form> """ return res # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
wilvk/ansible
lib/ansible/modules/web_infrastructure/jenkins_plugin.py
9
25319
#!/usr/bin/python # encoding: utf-8 # (c) 2016, Jiri Tyr <jiri.tyr@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: jenkins_plugin author: Jiri Tyr (@jtyr) version_added: '2.2' short_description: Add or remove Jenkins plugin description: - Ansible module which helps to manage Jenkins plugins. options: group: required: false default: jenkins description: - Name of the Jenkins group on the OS. jenkins_home: required: false default: /var/lib/jenkins description: - Home directory of the Jenkins user. mode: required: false default: '0664' description: - File mode applied on versioned plugins. name: required: true description: - Plugin name. owner: required: false default: jenkins description: - Name of the Jenkins user on the OS. state: required: false choices: [absent, present, pinned, unpinned, enabled, disabled, latest] default: present description: - Desired plugin state. - If the C(latest) is set, the check for new version will be performed every time. This is suitable to keep the plugin up-to-date. timeout: required: false default: 30 description: - Server connection timeout in secs. updates_expiration: required: false default: 86400 description: - Number of seconds after which a new copy of the I(update-center.json) file is downloaded. This is used to avoid the need to download the plugin to calculate its checksum when C(latest) is specified. - Set it to C(0) if no cache file should be used. In that case, the plugin file will always be downloaded to calculate its checksum when C(latest) is specified. updates_url: required: false default: https://updates.jenkins-ci.org description: - URL of the Update Centre. - Used as the base URL to download the plugins and the I(update-center.json) JSON file. url: required: false default: http://localhost:8080 description: - URL of the Jenkins server. version: required: false default: null description: - Plugin version number. - If this option is specified, all plugin dependencies must be installed manually. - It might take longer to verify that the correct version is installed. This is especially true if a specific version number is specified. - Quote the version to prevent the value to be interpreted as float. For example if C(1.20) would be unquoted, it would become C(1.2). with_dependencies: required: false choices: ['yes', 'no'] default: 'yes' description: - Defines whether to install plugin dependencies. - This option takes effect only if the I(version) is not defined. notes: - Plugin installation should be run under root or the same user which owns the plugin files on the disk. Only if the plugin is not installed yet and no version is specified, the API installation is performed which requires only the Web UI credentials. - It's necessary to notify the handler or call the I(service) module to restart the Jenkins service after a new plugin was installed. - Pinning works only if the plugin is installed and Jenkis service was successfully restarted after the plugin installation. - It is not possible to run the module remotely by changing the I(url) parameter to point to the Jenkins server. The module must be used on the host where Jenkins runs as it needs direct access to the plugin files. - "The C(params) option was removed in Ansible 2.5 due to circumventing Ansible's option handling" extends_documentation_fragment: - url ''' EXAMPLES = ''' - name: Install plugin jenkins_plugin: name: build-pipeline-plugin - name: Install plugin without its dependencies jenkins_plugin: name: build-pipeline-plugin with_dependencies: no - name: Make sure the plugin is always up-to-date jenkins_plugin: name: token-macro state: latest - name: Install specific version of the plugin jenkins_plugin: name: token-macro version: "1.15" - name: Pin the plugin jenkins_plugin: name: token-macro state: pinned - name: Unpin the plugin jenkins_plugin: name: token-macro state: unpinned - name: Enable the plugin jenkins_plugin: name: token-macro state: enabled - name: Disable the plugin jenkins_plugin: name: token-macro state: disabled - name: Uninstall plugin jenkins_plugin: name: build-pipeline-plugin state: absent # # Example of how to authenticate # - name: Install plugin jenkins_plugin: name: build-pipeline-plugin url_username: admin url_password: p4ssw0rd url: http://localhost:8888 # # Example of a Play which handles Jenkins restarts during the state changes # - name: Jenkins Master play hosts: jenkins-master vars: my_jenkins_plugins: token-macro: enabled: yes build-pipeline-plugin: version: "1.4.9" pinned: no enabled: yes tasks: - name: Install plugins without a specific version jenkins_plugin: name: "{{ item.key }}" register: my_jenkins_plugin_unversioned when: > 'version' not in item.value with_dict: "{{ my_jenkins_plugins }}" - name: Install plugins with a specific version jenkins_plugin: name: "{{ item.key }}" version: "{{ item.value['version'] }}" register: my_jenkins_plugin_versioned when: > 'version' in item.value with_dict: "{{ my_jenkins_plugins }}" - name: Initiate the fact set_fact: jenkins_restart_required: no - name: Check if restart is required by any of the versioned plugins set_fact: jenkins_restart_required: yes when: item.changed with_items: "{{ my_jenkins_plugin_versioned.results }}" - name: Check if restart is required by any of the unversioned plugins set_fact: jenkins_restart_required: yes when: item.changed with_items: "{{ my_jenkins_plugin_unversioned.results }}" - name: Restart Jenkins if required service: name: jenkins state: restarted when: jenkins_restart_required - name: Wait for Jenkins to start up uri: url: http://localhost:8080 status_code: 200 timeout: 5 register: jenkins_service_status # Keep trying for 5 mins in 5 sec intervals retries: 60 delay: 5 until: > 'status' in jenkins_service_status and jenkins_service_status['status'] == 200 when: jenkins_restart_required - name: Reset the fact set_fact: jenkins_restart_required: no when: jenkins_restart_required - name: Plugin pinning jenkins_plugin: name: "{{ item.key }}" state: "{{ 'pinned' if item.value['pinned'] else 'unpinned'}}" when: > 'pinned' in item.value with_dict: "{{ my_jenkins_plugins }}" - name: Plugin enabling jenkins_plugin: name: "{{ item.key }}" state: "{{ 'enabled' if item.value['enabled'] else 'disabled'}}" when: > 'enabled' in item.value with_dict: "{{ my_jenkins_plugins }}" ''' RETURN = ''' plugin: description: plugin name returned: success type: string sample: build-pipeline-plugin state: description: state of the target, after execution returned: success type: string sample: "present" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils.six.moves.urllib.parse import urlencode from ansible.module_utils.urls import fetch_url, url_argument_spec from ansible.module_utils._text import to_native import base64 import hashlib import json import os import tempfile import time class JenkinsPlugin(object): def __init__(self, module): # To be able to call fail_json self.module = module # Shortcuts for the params self.params = self.module.params self.url = self.params['url'] self.timeout = self.params['timeout'] # Crumb self.crumb = {} if self._csrf_enabled(): self.crumb = self._get_crumb() # Get list of installed plugins self._get_installed_plugins() def _csrf_enabled(self): csrf_data = self._get_json_data( "%s/%s" % (self.url, "api/json"), 'CSRF') if 'useCrumbs' not in csrf_data: self.module.fail_json( msg="Required fields not found in the Crumbs response.", details=csrf_data) return csrf_data['useCrumbs'] def _get_json_data(self, url, what, **kwargs): # Get the JSON data r = self._get_url_data(url, what, **kwargs) # Parse the JSON data try: json_data = json.loads(to_native(r.read())) except Exception: e = get_exception() self.module.fail_json( msg="Cannot parse %s JSON data." % what, details=to_native(e)) return json_data def _get_url_data( self, url, what=None, msg_status=None, msg_exception=None, **kwargs): # Compose default messages if msg_status is None: msg_status = "Cannot get %s" % what if msg_exception is None: msg_exception = "Retrieval of %s failed." % what # Get the URL data try: response, info = fetch_url( self.module, url, timeout=self.timeout, **kwargs) if info['status'] != 200: self.module.fail_json(msg=msg_status, details=info['msg']) except Exception: e = get_exception() self.module.fail_json(msg=msg_exception, details=to_native(e)) return response def _get_crumb(self): crumb_data = self._get_json_data( "%s/%s" % (self.url, "crumbIssuer/api/json"), 'Crumb') if 'crumbRequestField' in crumb_data and 'crumb' in crumb_data: ret = { crumb_data['crumbRequestField']: crumb_data['crumb'] } else: self.module.fail_json( msg="Required fields not found in the Crum response.", details=crumb_data) return ret def _get_installed_plugins(self): plugins_data = self._get_json_data( "%s/%s" % (self.url, "pluginManager/api/json?depth=1"), 'list of plugins') # Check if we got valid data if 'plugins' not in plugins_data: self.module.fail_json(msg="No valid plugin data found.") # Create final list of installed/pined plugins self.is_installed = False self.is_pinned = False self.is_enabled = False for p in plugins_data['plugins']: if p['shortName'] == self.params['name']: self.is_installed = True if p['pinned']: self.is_pinned = True if p['enabled']: self.is_enabled = True break def install(self): changed = False plugin_file = ( '%s/plugins/%s.jpi' % ( self.params['jenkins_home'], self.params['name'])) if not self.is_installed and self.params['version'] is None: if not self.module.check_mode: # Install the plugin (with dependencies) install_script = ( 'd = Jenkins.instance.updateCenter.getPlugin("%s")' '.deploy(); d.get();' % self.params['name']) if self.params['with_dependencies']: install_script = ( 'Jenkins.instance.updateCenter.getPlugin("%s")' '.getNeededDependencies().each{it.deploy()}; %s' % ( self.params['name'], install_script)) script_data = { 'script': install_script } script_data.update(self.crumb) data = urlencode(script_data) # Send the installation request r = self._get_url_data( "%s/scriptText" % self.url, msg_status="Cannot install plugin.", msg_exception="Plugin installation has failed.", data=data) hpi_file = '%s/plugins/%s.hpi' % ( self.params['jenkins_home'], self.params['name']) if os.path.isfile(hpi_file): os.remove(hpi_file) changed = True else: # Check if the plugin directory exists if not os.path.isdir(self.params['jenkins_home']): self.module.fail_json( msg="Jenkins home directory doesn't exist.") md5sum_old = None if os.path.isfile(plugin_file): # Make the checksum of the currently installed plugin md5sum_old = hashlib.md5( open(plugin_file, 'rb').read()).hexdigest() if self.params['version'] in [None, 'latest']: # Take latest version plugin_url = ( "%s/latest/%s.hpi" % ( self.params['updates_url'], self.params['name'])) else: # Take specific version plugin_url = ( "{0}/download/plugins/" "{1}/{2}/{1}.hpi".format( self.params['updates_url'], self.params['name'], self.params['version'])) if ( self.params['updates_expiration'] == 0 or self.params['version'] not in [None, 'latest'] or md5sum_old is None): # Download the plugin file directly r = self._download_plugin(plugin_url) # Write downloaded plugin into file if checksums don't match if md5sum_old is None: # No previously installed plugin if not self.module.check_mode: self._write_file(plugin_file, r) changed = True else: # Get data for the MD5 data = r.read() # Make new checksum md5sum_new = hashlib.md5(data).hexdigest() # If the checksum is different from the currently installed # plugin, store the new plugin if md5sum_old != md5sum_new: if not self.module.check_mode: self._write_file(plugin_file, data) changed = True else: # Check for update from the updates JSON file plugin_data = self._download_updates() try: sha1_old = hashlib.sha1(open(plugin_file, 'rb').read()) except Exception: e = get_exception() self.module.fail_json( msg="Cannot calculate SHA1 of the old plugin.", details=e.message) sha1sum_old = base64.b64encode(sha1_old.digest()) # If the latest version changed, download it if sha1sum_old != plugin_data['sha1']: if not self.module.check_mode: r = self._download_plugin(plugin_url) self._write_file(plugin_file, r) changed = True # Change file attributes if needed if os.path.isfile(plugin_file): params = { 'dest': plugin_file } params.update(self.params) file_args = self.module.load_file_common_arguments(params) if not self.module.check_mode: # Not sure how to run this in the check mode changed = self.module.set_fs_attributes_if_different( file_args, changed) else: # See the comment above changed = True return changed def _download_updates(self): updates_filename = 'jenkins-plugin-cache.json' updates_dir = os.path.expanduser('~/.ansible/tmp') updates_file = "%s/%s" % (updates_dir, updates_filename) download_updates = True # Check if we need to download new updates file if os.path.isfile(updates_file): # Get timestamp when the file was changed last time ts_file = os.stat(updates_file).st_mtime ts_now = time.time() if ts_now - ts_file < self.params['updates_expiration']: download_updates = False updates_file_orig = updates_file # Download the updates file if needed if download_updates: url = "%s/update-center.json" % self.params['updates_url'] # Get the data r = self._get_url_data( url, msg_status="Remote updates not found.", msg_exception="Updates download failed.") # Write the updates file update_fd, updates_file = tempfile.mkstemp() os.write(update_fd, r.read()) try: os.close(update_fd) except IOError: e = get_exception() self.module.fail_json( msg="Cannot close the tmp updates file %s." % updates_file, details=to_native(e)) # Open the updates file try: f = open(updates_file) except IOError: e = get_exception() self.module.fail_json( msg="Cannot open temporal updates file.", details=to_native(e)) i = 0 for line in f: # Read only the second line if i == 1: try: data = json.loads(line) except Exception: e = get_exception() self.module.fail_json( msg="Cannot load JSON data from the tmp updates file.", details=e.message) break i += 1 # Move the updates file to the right place if we could read it if download_updates: # Make sure the destination directory exists if not os.path.isdir(updates_dir): try: os.makedirs(updates_dir, int('0700', 8)) except OSError: e = get_exception() self.module.fail_json( msg="Cannot create temporal directory.", details=e.message) self.module.atomic_move(updates_file, updates_file_orig) # Check if we have the plugin data available if 'plugins' not in data or self.params['name'] not in data['plugins']: self.module.fail_json( msg="Cannot find plugin data in the updates file.") return data['plugins'][self.params['name']] def _download_plugin(self, plugin_url): # Download the plugin r = self._get_url_data( plugin_url, msg_status="Plugin not found.", msg_exception="Plugin download failed.") return r def _write_file(self, f, data): # Store the plugin into a temp file and then move it tmp_f_fd, tmp_f = tempfile.mkstemp() if isinstance(data, str): os.write(tmp_f_fd, data) else: os.write(tmp_f_fd, data.read()) try: os.close(tmp_f_fd) except IOError: e = get_exception() self.module.fail_json( msg='Cannot close the temporal plugin file %s.' % tmp_f, details=to_native(e)) # Move the file onto the right place self.module.atomic_move(tmp_f, f) def uninstall(self): changed = False # Perform the action if self.is_installed: if not self.module.check_mode: self._pm_query('doUninstall', 'Uninstallation') changed = True return changed def pin(self): return self._pinning('pin') def unpin(self): return self._pinning('unpin') def _pinning(self, action): changed = False # Check if the plugin is pinned/unpinned if ( action == 'pin' and not self.is_pinned or action == 'unpin' and self.is_pinned): # Perform the action if not self.module.check_mode: self._pm_query(action, "%sning" % action.capitalize()) changed = True return changed def enable(self): return self._enabling('enable') def disable(self): return self._enabling('disable') def _enabling(self, action): changed = False # Check if the plugin is pinned/unpinned if ( action == 'enable' and not self.is_enabled or action == 'disable' and self.is_enabled): # Perform the action if not self.module.check_mode: self._pm_query( "make%sd" % action.capitalize(), "%sing" % action[:-1].capitalize()) changed = True return changed def _pm_query(self, action, msg): url = "%s/pluginManager/plugin/%s/%s" % ( self.params['url'], self.params['name'], action) data = urlencode(self.crumb) # Send the request self._get_url_data( url, msg_status="Plugin not found. %s" % url, msg_exception="%s has failed." % msg, data=data) def main(): # Module arguments argument_spec = url_argument_spec() argument_spec.update( group=dict(default='jenkins'), jenkins_home=dict(default='/var/lib/jenkins'), mode=dict(default='0644', type='raw'), name=dict(required=True), owner=dict(default='jenkins'), params=dict(type='dict'), state=dict( choices=[ 'present', 'absent', 'pinned', 'unpinned', 'enabled', 'disabled', 'latest'], default='present'), timeout=dict(default=30, type="int"), updates_expiration=dict(default=86400, type="int"), updates_url=dict(default='https://updates.jenkins-ci.org'), url=dict(default='http://localhost:8080'), url_password=dict(no_log=True), version=dict(), with_dependencies=dict(default=True, type='bool'), ) # Module settings module = AnsibleModule( argument_spec=argument_spec, add_file_common_args=True, supports_check_mode=True, ) # Params was removed # https://meetbot.fedoraproject.org/ansible-meeting/2017-09-28/ansible_dev_meeting.2017-09-28-15.00.log.html if module.params['params']: module.fail_json(msg="The params option to jenkins_plugin was removed in Ansible 2.5" "since it circumvents Ansible's option handling") # Force basic authentication module.params['force_basic_auth'] = True # Convert timeout to float try: module.params['timeout'] = float(module.params['timeout']) except ValueError: e = get_exception() module.fail_json( msg='Cannot convert %s to float.' % module.params['timeout'], details=to_native(e)) # Set version to latest if state is latest if module.params['state'] == 'latest': module.params['state'] = 'present' module.params['version'] = 'latest' # Create some shortcuts name = module.params['name'] state = module.params['state'] # Initial change state of the task changed = False # Instantiate the JenkinsPlugin object jp = JenkinsPlugin(module) # Perform action depending on the requested state if state == 'present': changed = jp.install() elif state == 'absent': changed = jp.uninstall() elif state == 'pinned': changed = jp.pin() elif state == 'unpinned': changed = jp.unpin() elif state == 'enabled': changed = jp.enable() elif state == 'disabled': changed = jp.disable() # Print status of the change module.exit_json(changed=changed, plugin=name, state=state) if __name__ == '__main__': main()
gpl-3.0
chamikaramj/beam
sdks/python/apache_beam/coders/stream_test.py
18
5990
# # 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. # """Tests for the stream implementations.""" import logging import math import unittest from apache_beam.coders import slow_stream class StreamTest(unittest.TestCase): # pylint: disable=invalid-name InputStream = slow_stream.InputStream OutputStream = slow_stream.OutputStream ByteCountingOutputStream = slow_stream.ByteCountingOutputStream # pylint: enable=invalid-name def test_read_write(self): out_s = self.OutputStream() out_s.write('abc') out_s.write('\0\t\n') out_s.write('xyz', True) out_s.write('', True) in_s = self.InputStream(out_s.get()) self.assertEquals('abc\0\t\n', in_s.read(6)) self.assertEquals('xyz', in_s.read_all(True)) self.assertEquals('', in_s.read_all(True)) def test_read_all(self): out_s = self.OutputStream() out_s.write('abc') in_s = self.InputStream(out_s.get()) self.assertEquals('abc', in_s.read_all(False)) def test_read_write_byte(self): out_s = self.OutputStream() out_s.write_byte(1) out_s.write_byte(0) out_s.write_byte(0xFF) in_s = self.InputStream(out_s.get()) self.assertEquals(1, in_s.read_byte()) self.assertEquals(0, in_s.read_byte()) self.assertEquals(0xFF, in_s.read_byte()) def test_read_write_large(self): values = range(4 * 1024) out_s = self.OutputStream() for v in values: out_s.write_bigendian_int64(v) in_s = self.InputStream(out_s.get()) for v in values: self.assertEquals(v, in_s.read_bigendian_int64()) def run_read_write_var_int64(self, values): out_s = self.OutputStream() for v in values: out_s.write_var_int64(v) in_s = self.InputStream(out_s.get()) for v in values: self.assertEquals(v, in_s.read_var_int64()) def test_small_var_int64(self): self.run_read_write_var_int64(range(-10, 30)) def test_medium_var_int64(self): base = -1.7 self.run_read_write_var_int64( [int(base**pow) for pow in range(1, int(63 * math.log(2) / math.log(-base)))]) def test_large_var_int64(self): self.run_read_write_var_int64([0, 2**63 - 1, -2**63, 2**63 - 3]) def test_read_write_double(self): values = 0, 1, -1, 1e100, 1.0/3, math.pi, float('inf') out_s = self.OutputStream() for v in values: out_s.write_bigendian_double(v) in_s = self.InputStream(out_s.get()) for v in values: self.assertEquals(v, in_s.read_bigendian_double()) def test_read_write_bigendian_int64(self): values = 0, 1, -1, 2**63-1, -2**63, int(2**61 * math.pi) out_s = self.OutputStream() for v in values: out_s.write_bigendian_int64(v) in_s = self.InputStream(out_s.get()) for v in values: self.assertEquals(v, in_s.read_bigendian_int64()) def test_read_write_bigendian_uint64(self): values = 0, 1, 2**64-1, int(2**61 * math.pi) out_s = self.OutputStream() for v in values: out_s.write_bigendian_uint64(v) in_s = self.InputStream(out_s.get()) for v in values: self.assertEquals(v, in_s.read_bigendian_uint64()) def test_read_write_bigendian_int32(self): values = 0, 1, -1, 2**31-1, -2**31, int(2**29 * math.pi) out_s = self.OutputStream() for v in values: out_s.write_bigendian_int32(v) in_s = self.InputStream(out_s.get()) for v in values: self.assertEquals(v, in_s.read_bigendian_int32()) def test_byte_counting(self): bc_s = self.ByteCountingOutputStream() self.assertEquals(0, bc_s.get_count()) bc_s.write('def') self.assertEquals(3, bc_s.get_count()) bc_s.write('') self.assertEquals(3, bc_s.get_count()) bc_s.write_byte(10) self.assertEquals(4, bc_s.get_count()) # "nested" also writes the length of the string, which should # cause 1 extra byte to be counted. bc_s.write('2345', nested=True) self.assertEquals(9, bc_s.get_count()) bc_s.write_var_int64(63) self.assertEquals(10, bc_s.get_count()) bc_s.write_bigendian_int64(42) self.assertEquals(18, bc_s.get_count()) bc_s.write_bigendian_int32(36) self.assertEquals(22, bc_s.get_count()) bc_s.write_bigendian_double(6.25) self.assertEquals(30, bc_s.get_count()) bc_s.write_bigendian_uint64(47) self.assertEquals(38, bc_s.get_count()) try: # pylint: disable=wrong-import-position from apache_beam.coders import stream class FastStreamTest(StreamTest): """Runs the test with the compiled stream classes.""" InputStream = stream.InputStream OutputStream = stream.OutputStream ByteCountingOutputStream = stream.ByteCountingOutputStream class SlowFastStreamTest(StreamTest): """Runs the test with compiled and uncompiled stream classes.""" InputStream = stream.InputStream OutputStream = slow_stream.OutputStream ByteCountingOutputStream = slow_stream.ByteCountingOutputStream class FastSlowStreamTest(StreamTest): """Runs the test with uncompiled and compiled stream classes.""" InputStream = slow_stream.InputStream OutputStream = stream.OutputStream ByteCountingOutputStream = stream.ByteCountingOutputStream except ImportError: pass if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) unittest.main()
apache-2.0
MatthewWilkes/django
tests/forms_tests/widget_tests/test_checkboxselectmultiple.py
161
4824
from django.forms import CheckboxSelectMultiple from .base import WidgetTest class CheckboxSelectMultipleTest(WidgetTest): widget = CheckboxSelectMultiple() def test_render_value(self): self.check_html(self.widget, 'beatles', ['J'], choices=self.beatles, html=( """<ul> <li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> <li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> <li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> <li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> </ul>""" )) def test_render_value_multiple(self): self.check_html(self.widget, 'beatles', ['J', 'P'], choices=self.beatles, html=( """<ul> <li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> <li><label><input checked="checked" type="checkbox" name="beatles" value="P" /> Paul</label></li> <li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> <li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> </ul>""" )) def test_render_none(self): """ If the value is None, none of the options are selected. """ self.check_html(self.widget, 'beatles', None, choices=self.beatles, html=( """<ul> <li><label><input type="checkbox" name="beatles" value="J" /> John</label></li> <li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> <li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> <li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> </ul>""" )) def test_nested_choices(self): nested_choices = ( ('unknown', 'Unknown'), ('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))), ('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))), ) html = """ <ul id="media"> <li> <label for="media_0"><input id="media_0" name="nestchoice" type="checkbox" value="unknown" /> Unknown</label> </li> <li>Audio<ul id="media_1"> <li> <label for="media_1_0"> <input checked="checked" id="media_1_0" name="nestchoice" type="checkbox" value="vinyl" /> Vinyl </label> </li> <li> <label for="media_1_1"><input id="media_1_1" name="nestchoice" type="checkbox" value="cd" /> CD</label> </li> </ul></li> <li>Video<ul id="media_2"> <li> <label for="media_2_0"><input id="media_2_0" name="nestchoice" type="checkbox" value="vhs" /> VHS</label> </li> <li> <label for="media_2_1"> <input checked="checked" id="media_2_1" name="nestchoice" type="checkbox" value="dvd" /> DVD </label> </li> </ul></li> </ul> """ self.check_html( self.widget, 'nestchoice', ('vinyl', 'dvd'), choices=nested_choices, attrs={'id': 'media'}, html=html, ) def test_separate_ids(self): """ Each input gets a separate ID. """ choices = [('a', 'A'), ('b', 'B'), ('c', 'C')] html = """ <ul id="abc"> <li> <label for="abc_0"><input checked="checked" type="checkbox" name="letters" value="a" id="abc_0" /> A</label> </li> <li><label for="abc_1"><input type="checkbox" name="letters" value="b" id="abc_1" /> B</label></li> <li> <label for="abc_2"><input checked="checked" type="checkbox" name="letters" value="c" id="abc_2" /> C</label> </li> </ul> """ self.check_html(self.widget, 'letters', ['a', 'c'], choices=choices, attrs={'id': 'abc'}, html=html) def test_separate_ids_constructor(self): """ Each input gets a separate ID when the ID is passed to the constructor. """ widget = CheckboxSelectMultiple(attrs={'id': 'abc'}) choices = [('a', 'A'), ('b', 'B'), ('c', 'C')] html = """ <ul id="abc"> <li> <label for="abc_0"><input checked="checked" type="checkbox" name="letters" value="a" id="abc_0" /> A</label> </li> <li><label for="abc_1"><input type="checkbox" name="letters" value="b" id="abc_1" /> B</label></li> <li> <label for="abc_2"><input checked="checked" type="checkbox" name="letters" value="c" id="abc_2" /> C</label> </li> </ul> """ self.check_html(widget, 'letters', ['a', 'c'], choices=choices, html=html)
bsd-3-clause
madhurauti/Map-Polygon
modules/tests/staff/staff.py
27
1563
# -*- coding: utf-8 -*- """ Sahana Eden Staff Module Automated Tests @copyright: 2011-2012 (c) Sahana Software Foundation @license: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from tests.web2unittest import SeleniumUnitTest class Staff(SeleniumUnitTest): def test_staff001_create_staff(self): """ @case: asset001 @description: Create a Staff Member - IN PROGRESS * RENE: Insert instructions """ print "\n"
mit
levkar/odoo-addons
account_partner_balance/account_move_line.py
2
1130
# -*- coding: utf-8 -*- import time from datetime import datetime from openerp.osv import fields, osv, orm from openerp.tools.translate import _ from openerp import tools import openerp.addons.decimal_precision as dp class account_move_line(osv.osv): _inherit = "account.move.line" def _net(self, cr, uid, ids, field_name, args,context=None): res = {} for line in self.browse(cr, uid, ids, context=None): res[line.id] = line.debit - line.credit return res _columns = { # 'net': fields.function(_net, store={'account.move.line': (lambda self, cr, uid, ids, c={}: ids, # ['debit', 'credit'],10)}, method=True, string='Net'), # quise hacer la funcion con store pero el problema es que solo me calcula cuando modifico un campo y no me hace el calculo la primer vez 'net': fields.function(_net, string='Net', type='float', digits_compute=dp.get_precision( 'Account'), ), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
ronfung/incubator-airflow
airflow/contrib/operators/__init__.py
15
1570
# -*- coding: utf-8 -*- # # 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. # # Contrib operators are not imported by default. They should be accessed # directly: from airflow.contrib.operators.operator_module import Operator import sys # ------------------------------------------------------------------------ # # #TODO #FIXME Airflow 2.0 # # Old import machinary below. # # This is deprecated but should be kept until Airflow 2.0 # for compatibility. # # ------------------------------------------------------------------------ _operators = { 'ssh_execute_operator': ['SSHExecuteOperator'], 'vertica_operator': ['VerticaOperator'], 'vertica_to_hive': ['VerticaToHiveTransfer'], 'qubole_operator': ['QuboleOperator'], 'spark_submit_operator': ['SparkSubmitOperator'], 'file_to_wasb': ['FileToWasbOperator'], 'fs_operator': ['FileSensor'] } import os as _os if not _os.environ.get('AIRFLOW_USE_NEW_IMPORTS', False): from airflow.utils.helpers import AirflowImporter airflow_importer = AirflowImporter(sys.modules[__name__], _operators)
apache-2.0
stoodz/secretsanta
vendor/psy/psysh/test/tools/gen_unvis_fixtures.py
536
3120
#! /usr/bin/env python3 import sys from os.path import abspath, expanduser, dirname, join from itertools import chain import json import argparse from vis import vis, unvis, VIS_WHITE __dir__ = dirname(abspath(__file__)) OUTPUT_FILE = join(__dir__, '..', 'fixtures', 'unvis_fixtures.json') # Add custom fixtures here CUSTOM_FIXTURES = [ # test long multibyte string ''.join(chr(cp) for cp in range(1024)), 'foo bar', 'foo\nbar', "$bar = 'baz';", r'$foo = "\x20\\x20\\\x20\\\\x20"', '$foo = function($bar) use($baz) {\n\treturn $baz->getFoo()\n};' ] RANGES = { # All valid codepoints in the BMP 'bmp': chain(range(0x0000, 0xD800), range(0xE000, 0xFFFF)), # Smaller set of pertinent? codepoints inside BMP # see: http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane 'small': chain( # latin blocks range(0x0000, 0x0250), # Greek, Cyrillic range(0x0370, 0x0530), # Hebrew, Arabic range(0x590, 0x0700), # CJK radicals range(0x2E80, 0x2F00), # Hiragana, Katakana range(0x3040, 0x3100) ) } if __name__ == '__main__': argp = argparse.ArgumentParser( description='Generates test data for Psy\\Test\\Util\\StrTest') argp.add_argument('-f', '--format-output', action='store_true', help='Indent JSON output to ease debugging') argp.add_argument('-a', '--all', action='store_true', help="""Generates test data for all codepoints of the BMP. (same as --range=bmp). WARNING: You will need quite a lot of RAM to run the testsuite ! """) argp.add_argument('-r', '--range', help="""Choose the range of codepoints used to generate test data.""", choices=list(RANGES.keys()), default='small') argp.add_argument('-o', '--output-file', help="""Write test data to OUTPUT_FILE (defaults to PSYSH_DIR/test/fixtures)""") args = argp.parse_args() cp_range = RANGES['bmp'] if args.all else RANGES[args.range] indent = 2 if args.format_output else None if args.output_file: OUTPUT_FILE = abspath(expanduser(args.output_file)) fixtures = [] # use SMALL_RANGE by default, it should be enough. # use BMP_RANGE for a more complete smoke test for codepoint in cp_range: char = chr(codepoint) encoded = vis(char, VIS_WHITE) decoded = unvis(encoded) fixtures.append((encoded, decoded)) # Add our own custom fixtures at the end, # since they would fail anyway if one of the previous did. for fixture in CUSTOM_FIXTURES: encoded = vis(fixture, VIS_WHITE) decoded = unvis(encoded) fixtures.append((encoded, decoded)) with open(OUTPUT_FILE, 'w') as fp: # dump as json to avoid backslashin and quotin nightmare # between php and python json.dump(fixtures, fp, indent=indent) sys.exit(0)
mit
hassanibi/erpnext
erpnext/hr/report/monthly_attendance_sheet/monthly_attendance_sheet.py
14
3383
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import cstr, cint, getdate from frappe import msgprint, _ from calendar import monthrange def execute(filters=None): if not filters: filters = {} conditions, filters = get_conditions(filters) columns = get_columns(filters) att_map = get_attendance_list(conditions, filters) emp_map = get_employee_details() data = [] for emp in sorted(att_map): emp_det = emp_map.get(emp) if not emp_det: continue row = [emp, emp_det.employee_name, emp_det.branch, emp_det.department, emp_det.designation, emp_det.company] total_p = total_a = total_l = 0.0 for day in range(filters["total_days_in_month"]): status = att_map.get(emp).get(day + 1, "None") status_map = {"Present": "P", "Absent": "A", "Half Day": "H", "On Leave": "L", "None": ""} row.append(status_map[status]) if status == "Present": total_p += 1 elif status == "Absent": total_a += 1 elif status == "On Leave": total_l += 1 elif status == "Half Day": total_p += 0.5 total_a += 0.5 row += [total_p, total_l, total_a] data.append(row) return columns, data def get_columns(filters): columns = [ _("Employee") + ":Link/Employee:120", _("Employee Name") + "::140", _("Branch")+ ":Link/Branch:120", _("Department") + ":Link/Department:120", _("Designation") + ":Link/Designation:120", _("Company") + ":Link/Company:120" ] for day in range(filters["total_days_in_month"]): columns.append(cstr(day+1) +"::20") columns += [_("Total Present") + ":Float:80", _("Total Leaves") + ":Float:80", _("Total Absent") + ":Float:80"] return columns def get_attendance_list(conditions, filters): attendance_list = frappe.db.sql("""select employee, day(attendance_date) as day_of_month, status from tabAttendance where docstatus = 1 %s order by employee, attendance_date""" % conditions, filters, as_dict=1) att_map = {} for d in attendance_list: att_map.setdefault(d.employee, frappe._dict()).setdefault(d.day_of_month, "") att_map[d.employee][d.day_of_month] = d.status return att_map def get_conditions(filters): if not (filters.get("month") and filters.get("year")): msgprint(_("Please select month and year"), raise_exception=1) filters["month"] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"].index(filters.month) + 1 filters["total_days_in_month"] = monthrange(cint(filters.year), filters.month)[1] conditions = " and month(attendance_date) = %(month)s and year(attendance_date) = %(year)s" if filters.get("company"): conditions += " and company = %(company)s" if filters.get("employee"): conditions += " and employee = %(employee)s" return conditions, filters def get_employee_details(): emp_map = frappe._dict() for d in frappe.db.sql("""select name, employee_name, designation, department, branch, company from tabEmployee""", as_dict=1): emp_map.setdefault(d.name, d) return emp_map @frappe.whitelist() def get_attendance_years(): year_list = frappe.db.sql_list("""select distinct YEAR(attendance_date) from tabAttendance ORDER BY YEAR(attendance_date) DESC""") if not year_list: year_list = [getdate().year] return "\n".join(str(year) for year in year_list)
gpl-3.0
gangadhar-kadam/sms-erpnext
accounts/doctype/gl_entry/gl_entry.py
2
8223
# ERPNext - web based ERP (http://erpnext.com) # Copyright (C) 2012 Web Notes Technologies Pvt Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import webnotes from webnotes.utils import flt, fmt_money, getdate from webnotes.model.code import get_obj from webnotes import msgprint, _ sql = webnotes.conn.sql class DocType: def __init__(self,d,dl): self.doc, self.doclist = d, dl def validate(self): # not called on cancel self.check_mandatory() self.pl_must_have_cost_center() self.validate_posting_date() self.doc.is_cancelled = 'No' # will be reset by GL Control if cancelled self.check_credit_limit() self.check_pl_account() def on_update(self, adv_adj, cancel, update_outstanding = 'Yes'): self.validate_account_details(adv_adj) self.validate_cost_center() self.check_freezing_date(adv_adj) self.check_negative_balance(adv_adj) # Update outstanding amt on against voucher if self.doc.against_voucher and self.doc.against_voucher_type != "POS" \ and update_outstanding == 'Yes': self.update_outstanding_amt() def check_mandatory(self): mandatory = ['account','remarks','voucher_type','voucher_no','fiscal_year','company'] for k in mandatory: if not self.doc.fields.get(k): msgprint(k + _(" is mandatory for GL Entry"), raise_exception=1) # Zero value transaction is not allowed if not (flt(self.doc.debit) or flt(self.doc.credit)): msgprint(_("GL Entry: Debit or Credit amount is mandatory for ") + self.doc.account, raise_exception=1) def pl_must_have_cost_center(self): if webnotes.conn.get_value("Account", self.doc.account, "is_pl_account") == "Yes": if not self.doc.cost_center and self.doc.voucher_type != 'Period Closing Voucher': msgprint(_("Cost Center must be specified for PL Account: ") + self.doc.account, raise_exception=1) else: if self.doc.cost_center: self.doc.cost_center = "" def validate_posting_date(self): from accounts.utils import validate_fiscal_year validate_fiscal_year(self.doc.posting_date, self.doc.fiscal_year, "Posting Date") def check_credit_limit(self): master_type, master_name = webnotes.conn.get_value("Account", self.doc.account, ["master_type", "master_name"]) tot_outstanding = 0 #needed when there is no GL Entry in the system for that acc head if (self.doc.voucher_type=='Journal Voucher' or self.doc.voucher_type=='Sales Invoice') \ and (master_type =='Customer' and master_name): dbcr = sql("""select sum(debit), sum(credit) from `tabGL Entry` where account = '%s' and is_cancelled='No'""" % self.doc.account) if dbcr: tot_outstanding = flt(dbcr[0][0]) - flt(dbcr[0][1]) + \ flt(self.doc.debit) - flt(self.doc.credit) get_obj('Account',self.doc.account).check_credit_limit(self.doc.account, self.doc.company, tot_outstanding) def check_pl_account(self): if self.doc.is_opening=='Yes' and \ webnotes.conn.get_value("Account", self.doc.account, "is_pl_account") == "Yes": msgprint(_("For opening balance entry account can not be a PL account"), raise_exception=1) def validate_account_details(self, adv_adj): """Account must be ledger, active and not freezed""" ret = sql("""select group_or_ledger, docstatus, freeze_account, company from tabAccount where name=%s""", self.doc.account, as_dict=1) if ret and ret[0]["group_or_ledger"]=='Group': msgprint(_("Account") + ": " + self.doc.account + _(" is not a ledger"), raise_exception=1) if ret and ret[0]["docstatus"]==2: msgprint(_("Account") + ": " + self.doc.account + _(" is not active"), raise_exception=1) # Account has been freezed for other users except account manager if ret and ret[0]["freeze_account"]== 'Yes' and not adv_adj \ and not 'Accounts Manager' in webnotes.user.get_roles(): msgprint(_("Account") + ": " + self.doc.account + _(" has been freezed. \ Only Accounts Manager can do transaction against this account"), raise_exception=1) if self.doc.is_cancelled in ("No", None) and ret and ret[0]["company"] != self.doc.company: msgprint(_("Account") + ": " + self.doc.account + _(" does not belong to the company") \ + ": " + self.doc.company, raise_exception=1) def validate_cost_center(self): if not hasattr(self, "cost_center_company"): self.cost_center_company = {} def _get_cost_center_company(): if not self.cost_center_company.get(self.doc.cost_center): self.cost_center_company[self.doc.cost_center] = webnotes.conn.get_value("Cost Center", self.doc.cost_center, "company_name") return self.cost_center_company[self.doc.cost_center] if self.doc.is_cancelled in ("No", None) and \ self.doc.cost_center and _get_cost_center_company() != self.doc.company: msgprint(_("Cost Center") + ": " + self.doc.cost_center \ + _(" does not belong to the company") + ": " + self.doc.company, raise_exception=True) def check_freezing_date(self, adv_adj): """ Nobody can do GL Entries where posting date is before freezing date except authorized person """ if not adv_adj: acc_frozen_upto = webnotes.conn.get_value('Global Defaults', None, 'acc_frozen_upto') if acc_frozen_upto: bde_auth_role = webnotes.conn.get_value( 'Global Defaults', None,'bde_auth_role') if getdate(self.doc.posting_date) <= getdate(acc_frozen_upto) \ and not bde_auth_role in webnotes.user.get_roles(): msgprint(_("You are not authorized to do/modify back dated entries before ") + getdate(acc_frozen_upto).strftime('%d-%m-%Y'), raise_exception=1) def check_negative_balance(self, adv_adj): if not adv_adj: account = webnotes.conn.get_value("Account", self.doc.account, ["allow_negative_balance", "debit_or_credit"], as_dict=True) if not account["allow_negative_balance"]: balance = webnotes.conn.sql("""select sum(debit) - sum(credit) from `tabGL Entry` where account = %s and ifnull(is_cancelled, 'No') = 'No'""", self.doc.account) balance = account["debit_or_credit"] == "Debit" and \ balance[0][0] or -1*balance[0][0] if flt(balance) < 0: msgprint(_("Negative balance is not allowed for account ") + self.doc.account, raise_exception=1) def update_outstanding_amt(self): # get final outstanding amt bal = flt(sql("""select sum(debit) - sum(credit) from `tabGL Entry` where against_voucher=%s and against_voucher_type=%s and ifnull(is_cancelled,'No') = 'No'""", (self.doc.against_voucher, self.doc.against_voucher_type))[0][0] or 0.0) if self.doc.against_voucher_type == 'Purchase Invoice': bal = -bal elif self.doc.against_voucher_type == "Journal Voucher": against_voucher_amount = flt(webnotes.conn.sql("""select sum(debit) - sum(credit) from `tabGL Entry` where voucher_type = 'Journal Voucher' and voucher_no = %s and account = %s""", (self.doc.against_voucher, self.doc.account))[0][0]) bal = against_voucher_amount + bal if against_voucher_amount < 0: bal = -bal # Validation : Outstanding can not be negative if bal < 0 and self.doc.is_cancelled == 'No': msgprint(_("Outstanding for Voucher ") + self.doc.against_voucher + _(" will become ") + fmt_money(bal) + _(". Outstanding cannot be less than zero. \ Please match exact outstanding."), raise_exception=1) # Update outstanding amt on against voucher if self.doc.against_voucher_type in ["Sales Invoice", "Purchase Invoice"]: sql("update `tab%s` set outstanding_amount=%s where name='%s'"% (self.doc.against_voucher_type, bal, self.doc.against_voucher))
agpl-3.0
enikesha/ga-bitbot
bcfeed_synch.py
17
3179
#converts bitcoincharts csv download into the #1min format used by the genetic trade framework from time import * import urllib2 import sys __app_version__ = "0.01a" print "-"*80 print """ Bitcoin Data Feed Synchronizer v%s \tConverts the data into a weighted price 1min data feed format To automaticaly download and process the mtgox usd historic data run with the following option: python bcfeed_synch -d Without the -d switch the output will only be written to the datafeed_reboot folder """%(__app_version__) print "-"*80 link = """http://bitcoincharts.com/t/trades.csv?symbol=mtgoxUSD&start={START_TIME}""" start_time = 0 #don't change these variables - they are automaticaly configured incremental_update = 0 #based on command line options auto_move_output = 0 # if len(sys.argv) >= 2: if sys.argv[1] == '-d': try: print "bcfeed_synch: Checking potential for incremental update..." for line in open('./datafeed/bcfeed_mtgoxUSD_1min.csv'):pass line = line.split(',')[0] line = line.split('.')[0] start_time = int(line) + 60 incremental_update = 1 except: print "bcfeed_synch: Incremental update not possible." pass print "bcfeed_synch: Downloading mtgox historic data..." link = link.replace('{START_TIME}',str(start_time)) data = urllib2.urlopen(link).read() f = open("./datafeed_reboot/download_mtgoxUSD.csv",'w') f.write(data) f.close() auto_move_output = 1 print "bcfeed_synch: Download complete." else: print "bcfeed_synch: Invalid argument",sys.argv[1] f = open("./datafeed_reboot/download_mtgoxUSD.csv",'r') d = f.readlines() f.close() print "bcfeed_synch: Processing input..." one_min = [] accum_r = [] #exception handling to address issue #11 - unhandled exception when download or input file has no data try: last_t = d[0].split(',')[0] except: print "bcfeed_synch: No new data to process" sys.exit() last_m = ctime(int(last_t)).split(':')[1] for r in d: sr = r.replace('\n','').split(',') t,p,v = sr if (ctime(int(t)).split(':')[1] == last_m): accum_r.append(map(float,sr)) else: tv = 0 twp = 0 for r in accum_r: #print r twp += (r[1] * r[2]) tv += r[2] if tv > 0: wp = twp / tv one_min.append([last_t,wp,tv]) #print last_t,wp,tv accum_r = [map(float,sr)] last_t = int(t) last_m = ctime(last_t).split(':')[1] print "bcfeed_synch: Writing output file..." if auto_move_output == 1 : print "bcfeed_synch: Updating the datafeed directory directly...no need to manualy move the output file" if incremental_update == 1: print "bcfeed_synch: Writing incremental update..." f = open('./datafeed/bcfeed_mtgoxUSD_1min.csv','a') else: f = open('./datafeed/bcfeed_mtgoxUSD_1min.csv','w') else: f = open('./datafeed_reboot/bcfeed_mtgoxUSD_1min.csv','w') for t,p,v in one_min: f.write(",".join(map(str,[t,p,v])) + '\n') f.close() print "bcfeed_synch: Done."
gpl-3.0
pyconll/pyconll
tests/test_util.py
1
6012
import operator import pytest from pyconll.util import find_ngrams, find_nonprojective_deps from pyconll import load_from_file from tests.util import fixture_location def test_ngram_standard(): """ Test if the find_ngram method works for standard situations. """ c = load_from_file(fixture_location('basic.conll')) s, i, _ = next(find_ngrams(c, 'un film sur la'.split())) assert s.id == 'fr-ud-dev_00001' assert i == 2 def test_ngram_multiple_per_sentence(): """ Test that all ngrams are found when there are multiple in the same sentence. """ c = load_from_file(fixture_location('long.conll')) results = list(find_ngrams(c, 'telle ou telle'.split())) actual_ids = list(map(lambda res: res[0].id, results)) actual_indices = list(map(operator.itemgetter(1), results)) expected_ids = ['fr-ud-test_00008', 'fr-ud-test_00008'] expected_indices = [21, 26] assert actual_ids == expected_ids assert actual_indices == expected_indices def test_ngram_none(): """ Test that no ngram is identified when none exist """ c = load_from_file(fixture_location('long.conll')) it = find_ngrams(c, 'cabinet'.split()) with pytest.raises(StopIteration): next(it) def test_ngram_first_word_match(): """ Test that a first word match is not enough to match. """ c = load_from_file(fixture_location('long.conll')) it = find_ngrams(c, 'un cabinet'.split()) with pytest.raises(StopIteration): next(it) def test_ngram_multiword_split(): """ Test that ngram searches still work when they go over a multiword token. """ c = load_from_file(fixture_location('long.conll')) it = find_ngrams(c, 'de " décentrement de le Sujet "'.split()) s, i, tokens = next(it) actual_token_ids = list(map(lambda token: token.id, tokens)) expected_token_ids = ['9', '10', '11', '12', '13', '14', '15'] assert s.id == 'fr-ud-test_00002' assert i == 8 assert actual_token_ids == expected_token_ids with pytest.raises(StopIteration): next(it) def test_ngram_multiple_multiword_splits(): """ Test that ngram searches work when they there is more than one multiword token. """ c = load_from_file(fixture_location('long.conll')) it = find_ngrams( c, 'civile de le territoire non autonome de le Sahara'.split()) s, i, tokens = next(it) actual_token_ids = list(map(lambda token: token.id, tokens)) expected_token_ids = ['10', '11', '12', '13', '14', '15', '16', '17', '18'] assert s.id == 'fr-ud-test_00003' assert i == 9 assert actual_token_ids == expected_token_ids with pytest.raises(StopIteration): next(it) def test_ngram_case_insensitive_first_token(): """ Test that the case sensitivity function works, when it is the first token. """ c = load_from_file(fixture_location('long.conll')) results = list(find_ngrams(c, 'Il'.split(), case_sensitive=False)) actual_ids = list(map(lambda res: res[0].id, results)) actual_indices = list(map(operator.itemgetter(1), results)) expected_ids = ['fr-ud-test_00003', 'fr-ud-test_00005', 'fr-ud-test_00008'] expected_indices = [1, 16, 0] assert actual_ids == expected_ids assert actual_indices == expected_indices def test_ngram_case_insensitive_n_token(): """ Test that the case sensitivity function works, when it is the nth token. """ c = load_from_file(fixture_location('long.conll')) s, i, tokens = next( find_ngrams(c, 'l\' orgaNisaTion pour La sécurité et la'.split(), case_sensitive=False)) actual_token_ids = list(map(lambda token: token.id, tokens)) expected_token_ids = ['9', '10', '11', '12', '13', '14', '15'] assert s.id == 'fr-ud-test_00004' assert i == 8 assert actual_token_ids == expected_token_ids def test_no_nonprojectivities(): """ Test with a sentence with no non-projective dependencies. """ c = load_from_file(fixture_location('projectivities.conll')) sent = c[0] deps = find_nonprojective_deps(sent) assert not deps def test_simple_nonprojectivities(): """ Test logic with a sentence with one single non-projectivity. """ c = load_from_file(fixture_location('projectivities.conll')) sent1 = c[1] deps1 = find_nonprojective_deps(sent1) sent2 = c[2] deps2 = find_nonprojective_deps(sent2) assert deps1 == [(sent1['16'], sent1['4'])] assert deps2 == [(sent2['8'], sent2['5'])] def test_multiword_ignore(): """ Test that multiword tokens are ignored and do not cause errors. """ c = load_from_file(fixture_location('projectivities.conll')) sent = c[3] deps = find_nonprojective_deps(sent) assert deps == [(sent['16'], sent['4'])] def test_overlapping_nonprojectivities(): """ Test that multiple non-projectivities can overlap. """ c = load_from_file(fixture_location('projectivities.conll')) sent = c[4] deps = find_nonprojective_deps(sent) assert set(deps) == set([(sent['16'], sent['4']), (sent['16'], sent['11'])]) def test_multiple_nonprojectivities(): """ Test that multiple disjoint projectivities are properly identified. """ c = load_from_file(fixture_location('projectivities.conll')) sent = c[5] deps = find_nonprojective_deps(sent) assert set(deps) == set([(sent['22'], sent['3']), (sent['22'], sent['21']), (sent['28'], sent['25'])]) def test_simple_nonprojectivities(): """ Test logic with a sentence with one single non-projectivity. """ c = load_from_file(fixture_location('projectivities.conll')) sent1 = c[3] deps1 = find_nonprojective_deps(sent1) sent2 = c[2] deps2 = find_nonprojective_deps(sent2) assert deps1 == [(sent1['16'], sent1['4'])] assert deps2 == [(sent2['8'], sent2['5'])]
mit
Tesora/tesora-nodepool
tools/fake-servers.py
3
3845
#!/usr/bin/env python # Copyright 2013 Hewlett-Packard Development Company, L.P. # Copyright 2011-2013 OpenStack Foundation # # 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. # A test script to stand in for a zeromq enabled jenkins. It sends zmq # events that simulate the jenkins node lifecycle. # # Usage: # zmq-server.py start HOSTNAME # zmq-server.py complete HOSTNAME import gear import json import logging import select import socket import threading import zmq class MyGearmanServer(gear.Server): def handleStatus(self, request): request.connection.conn.send(("build:fake_job\t%s\t0\t0\n" % self._count).encode('utf8')) request.connection.conn.send(("build:fake_job:devstack-precise\t%s\t0\t0\n" % 0).encode('utf8')) request.connection.conn.send(b'.\n') class FakeStatsd(object): def __init__(self): self.thread = threading.Thread(target=self.run) self.thread.daemon = True self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('', 8125)) self.stats = [] self.thread.start() def run(self): while True: poll = select.poll() poll.register(self.sock, select.POLLIN) ret = poll.poll() for (fd, event) in ret: if fd == self.sock.fileno(): data = self.sock.recvfrom(1024) if not data: return print data[0] self.stats.append(data[0]) def main(): logging.basicConfig(level=logging.DEBUG) context = zmq.Context() zsocket = context.socket(zmq.PUB) zsocket.bind("tcp://*:8881") geard = MyGearmanServer(statsd_host='localhost', statsd_port=8125, statsd_prefix='zuul.geard') geard._count = 0 statsd = FakeStatsd() print('ready') while True: line = raw_input() command, arg = line.split() if command == 'queue': geard._count = int(arg) elif command == 'start': topic = 'onStarted' data = {"name":"test","url":"job/test/","build":{"full_url":"http://localhost:8080/job/test/1/","number":1,"phase":"STARTED","url":"job/test/1/","node_name":arg}} zsocket.send("%s %s" % (topic, json.dumps(data))) elif command == 'complete': topic = 'onFinalized' data = {"name":"test","url":"job/test/","build":{"full_url":"http://localhost:8080/job/test/1/","number":1,"phase":"FINISHED","status":"SUCCESS","url":"job/test/1/","node_name":arg, "parameters":{"BASE_LOG_PATH":"05/60105/3/gate","LOG_PATH":"05/60105/3/gate/gate-tempest-dsvm-postgres-full/bf0f215","OFFLINE_NODE_WHEN_COMPLETE":"1","ZUUL_BRANCH":"master","ZUUL_CHANGE":"60105","ZUUL_CHANGE_IDS":"60105,3","ZUUL_CHANGES":"openstack/cinder:master:refs/changes/05/60105/3","ZUUL_COMMIT":"ccd02fce4148d5ac2b3e1e68532b55eb5c1c356d","ZUUL_PATCHSET":"3","ZUUL_PIPELINE":"gate","ZUUL_PROJECT":"openstack/cinder","ZUUL_REF":"refs/zuul/master/Z6726d84e57a04ec79585b895ace08f7e","ZUUL_URL":"http://zuul.openstack.org/p","ZUUL_UUID":"bf0f21577026492a985ca98a9ea14cc1"}}} zsocket.send("%s %s" % (topic, json.dumps(data))) if __name__ == '__main__': main()
apache-2.0
alf3r/GidroGraf-Sirius
src/main_satelite.py
1
2207
import cv2 import numpy as np import matplotlib.pyplot as plt from scipy import ndimage as sc # Загрузка filename = '../img/satelite.tif' img = sc.imread(filename) # img = img[0:8000, 0:8000] # # Коррекция гистограммы for i in range(1, 30): alpha = 1 * i a = cv2.convertScaleAbs(img, alpha=alpha, beta=0) beta = 127 - np.median(a, [0, 1]) a = cv2.convertScaleAbs(img, alpha=alpha, beta=beta) condition = np.mod(a, 255) == 0 K = np.sum(condition) / a.size if K > 0.1: break # a1 = np.median(a, 0) # plt.hist(a1, 256, range=[0, 255], fc='k', ec='k') # plt.show() img = [] clahe = cv2.createCLAHE(clipLimit=2, tileGridSize=(30, 30)) img = clahe.apply(a) # # # Размытие и бинаризация a = [] a = cv2.blur(img, (20, 20)) # a = cv2.adaptiveThreshold(a, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 201, 1) retval2, a = cv2.threshold(a, 80, 255, cv2.THRESH_BINARY) # Поиск контуров im2, contours, hierarchy = cv2.findContours(a, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) new_boxes = [] new_contours = [] for cnt in contours: area = cv2.contourArea(cnt) if (area < 1000000) & (area > 1000): rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) # convert all coordinates floating point values to int box = np.int0(box) # draw a red 'nghien' rectangle new_contours.append(cnt) new_boxes.append(box) area = float(area)/9698 area_m = "%.1f km2" % area cv2.putText(img, area_m, (box[0][0] + 50, box[0][1] + 50), cv2.FONT_HERSHEY_COMPLEX, 4, (0, 0, 0), 8, cv2.LINE_AA) # 5.35 # 51883 contours = [] cv2.drawContours(img, new_contours, -1, (0, 255, 0), 2) cv2.drawContours(img, new_boxes, -1, (255, 0, 0), 10) # Отображение # figure, axes = plt.subplots(1, 2, sharey=True) # axes[0].imshow(a, cmap='inferno', interpolation='bicubic', clim=(0, 255)) # axes[1].imshow(img, interpolation='bicubic', clim=(0, 255)) plt.imshow(img, interpolation='bicubic', clim=(0, 255)) plt.show()
gpl-3.0
endlessm/chromium-browser
third_party/blink/renderer/bindings/scripts/web_idl/ir_map.py
8
7613
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from .composition_parts import Identifier from .composition_parts import WithIdentifier class IRMap(object): """ Manages an identifier-IR map, where IR is IdIRMap.IR. This class is designed to work together with IdlCompiler closely. See also IdlCompiler, especially how IdlCompiler uses compilation phases. This class manages IDL definitions' IRs in following style. [ # phase 0 { kind : { identifier : definition(s) }, ... }, # phase 1 ... ] The outermost list represents compilation phases. Each phase stores the IRs that are processed in that compilation phase. IRs at the initial phase (= phase 0) is a direct translation from an AST. The innermost dict maps an identifier to an IR at a certain phase(*1). A certain phase is responsible to process certain group(s) of IR.Kind, so not all phases have all the kinds, there may be missing kinds in a certain phase. (*1) In case of partial definitions and includes, the dict maps an identifier to a list of IRs, as there may be multiple definitions with the same identifier. """ class IR(WithIdentifier): """ Represents an intermediate representation of IDL definitions used in IdlCompiler. IR is used only by IdlCompiler. See also IdlCompiler and its compilation strategy. IR supports identifier-IR maps grouped by Kind (see below). """ class Kind(object): """ Enumerates supported kinds of IDL definitions in IR, such as "interface", "typedef", or "partial dictionary". """ CALLBACK_FUNCTION = 'callback function' CALLBACK_INTERFACE = 'callback interface' DICTIONARY = 'dictionary' ENUMERATION = 'enumeration' INCLUDES = 'includes' INTERFACE = 'interface' INTERFACE_MIXIN = 'interface mixin' NAMESPACE = 'namespace' PARTIAL_DICTIONARY = 'partial dictionary' PARTIAL_INTERFACE = 'partial interface' PARTIAL_INTERFACE_MIXIN = 'partial interface mixin' PARTIAL_NAMESPACE = 'partial namespace' TYPEDEF = 'typedef' _MULTI_VALUE_KINDS = ( INCLUDES, PARTIAL_DICTIONARY, PARTIAL_INTERFACE, PARTIAL_INTERFACE_MIXIN, PARTIAL_NAMESPACE, ) @classmethod def does_support_multiple_defs(cls, kind): return kind in cls._MULTI_VALUE_KINDS def __init__(self, identifier, kind): WithIdentifier.__init__(self, identifier) self._kind = kind @property def kind(self): return self._kind @property def does_support_multiple_defs(self): """ Returns True if multiple IRs may have a same identifier. For most kinds, an identifier points to a single IR. However, it's reasonable and convenient to allow multiple IRs to have the same identifier for some kinds, e.g. partial interface and includes. This function returns True for such kinds. """ return IRMap.IR.Kind.does_support_multiple_defs(self.kind) def __init__(self): # IRs whose does_support_multiple_defs is False self._single_value_irs = [dict()] # IRs whose does_support_multiple_defs is True self._multiple_value_irs = [dict()] self._current_phase = 0 def move_to_new_phase(self): assert len(self._single_value_irs) == self._current_phase + 1 assert len(self._multiple_value_irs) == self._current_phase + 1 self._current_phase += 1 self._single_value_irs.append(dict()) self._multiple_value_irs.append(dict()) def register(self, ir): """ Registers the given IR to this map. Duplicated registration is not allowed. The registration must be for the first time. """ assert isinstance(ir, IRMap.IR), ir # Assert |ir| doesn't yet exist in this map. try: if ir.does_support_multiple_defs: irs = self.find_by_kind(ir.kind) assert ir not in irs[ir.identifier] else: duplicated_ir = self.find_by_identifier(ir.identifier) # We don't allow to declare a definition of an IDL definition in # multiple places. raise ValueError('{} {} is defined twice.\n {}\n {}'.format( ir.kind, ir.identifier, ir.debug_info.location, duplicated_ir.debug_info.location)) except KeyError: pass self.add(ir) def add(self, ir): assert isinstance(ir, IRMap.IR) ir_map = (self._multiple_value_irs if ir.does_support_multiple_defs else self._single_value_irs) current_irs = ir_map[self._current_phase] kind = ir.kind if kind not in current_irs: current_irs[kind] = dict() irs_per_kind = current_irs[kind] identifier = ir.identifier if ir.does_support_multiple_defs: if identifier not in irs_per_kind: irs_per_kind[identifier] = [] irs_per_kind[identifier].append(ir) else: assert identifier not in irs_per_kind, ( 'Duplicated definition: {}\n {}\n {}'.format( identifier, ir.debug_info.location, irs_per_kind[identifier].debug_info.location)) irs_per_kind[identifier] = ir def find_by_identifier(self, identifier): """ Returns the latest IR whose identifier is |identifier| and |does_support_multiple_defs| is False. Raises KeyError if not found. """ assert isinstance(identifier, Identifier) for irs_per_phase in self._single_value_irs[self._current_phase::-1]: for irs_per_kind in irs_per_phase.values(): if identifier in irs_per_kind: return irs_per_kind[identifier] raise KeyError(identifier) def find_by_kind(self, kind): """ Returns a map from identifiers to the latest IRs of |kind|. Returns an empty map if not found. """ ir_map = (self._multiple_value_irs if IRMap.IR.Kind.does_support_multiple_defs(kind) else self._single_value_irs) for irs_per_phase in ir_map[self._current_phase::-1]: if kind in irs_per_phase: return irs_per_phase[kind] return dict() def irs_of_kind(self, kind): """Returns a flattened list of IRs of the given kind.""" if IRMap.IR.Kind.does_support_multiple_defs(kind): accumulated = [] for irs in self.find_by_kind(kind).values(): accumulated.extend(irs) return accumulated else: return list(self.find_by_kind(kind).values()) def irs_of_kinds(self, *kinds): """ Returns a flattened and concatenated list of IRs of all given kinds. """ accumulated = [] for kind in kinds: accumulated.extend(self.irs_of_kind(kind)) return accumulated
bsd-3-clause
geodynamics/pylith
pylith/mpi/Communicator.py
1
2985
# ---------------------------------------------------------------------- # # Brad T. Aagaard, U.S. Geological Survey # Charles A. Williams, GNS Science # Matthew G. Knepley, University at Buffalo # # This code was developed as part of the Computational Infrastructure # for Geodynamics (http://geodynamics.org). # # Copyright (c) 2010-2021 University of California, Davis # # See LICENSE.md for license information. # # ---------------------------------------------------------------------- # # @file pylith/mpi/Communicator.py ## # @brief Python MPI communicator object. ## # Provides SWIG friendly interface to MPI communicator object. ## # The communicator requires special treatment because we do not have # a normal SWIG interface definition. SWIG treats the communicator in # the same way it treats a pointer to an object, even if it is an # integer. import pylith.mpi.mpi as mpimodule # Communicator class class Communicator(object): """Python MPI communicator object. """ # PUBLIC METHODS ///////////////////////////////////////////////////// def __init__(self, handle): """Constructor. """ # Transfer responsibility of memory management from module to this # class. handle.disown() self.handle = handle self.rank = mpimodule.rank(self.handle) self.size = mpimodule.size(self.handle) return def __del__(self): del self.rank del self.size mpimodule.destroy_comm(self.handle) del self.handle return def barrier(self): """MPI Barrier. """ mpimodule.barrier(self.handle) return # ---------------------------------------------------------------------- def petsc_comm_world(): """Python wrapper around PETSC_COMM_WORLD. """ global _petsc_world if _petsc_world is None: _petsc_world = Communicator(mpimodule.petsc_comm_world()) return _petsc_world # ---------------------------------------------------------------------- def petsc_comm_self(): """Python wrapper around PETSC_COMM_SELF. """ global _petsc_self if _petsc_self is None: _petsc_self = Communicator(mpimodule.petsc_comm_self()) return _petsc_self # ---------------------------------------------------------------------- def mpi_comm_world(): """Python wrapper around MPI_COMM_WORLD. """ global _mpi_world if _mpi_world is None: _mpi_world = Communicator(mpimodule.mpi_comm_world()) return _mpi_world # ---------------------------------------------------------------------- def mpi_comm_self(): """Python wrapper around MPI_COMM_SELF. """ global _mpi_self if _mpi_self is None: _mpi_self = Communicator(mpimodule.mpi_comm_self()) return _mpi_self # ---------------------------------------------------------------------- # Singletons _petsc_world = None _petsc_self = None _mpi_world = None _mpi_self = None # End of file
mit
Changaco/oh-mainline
vendor/packages/scrapy/scrapy/core/scraper.py
17
8686
"""This module implements the Scraper component which parses responses and extracts information from them""" from collections import deque from twisted.python.failure import Failure from twisted.internet import defer from scrapy.utils.defer import defer_result, defer_succeed, parallel, iter_errback from scrapy.utils.spider import iterate_spider_output from scrapy.utils.misc import load_object from scrapy.utils.signal import send_catch_log, send_catch_log_deferred from scrapy.exceptions import CloseSpider, DropItem from scrapy import signals from scrapy.http import Request, Response from scrapy.item import BaseItem from scrapy.core.spidermw import SpiderMiddlewareManager from scrapy import log from scrapy.stats import stats class Slot(object): """Scraper slot (one per running spider)""" MIN_RESPONSE_SIZE = 1024 def __init__(self, max_active_size=5000000): self.max_active_size = max_active_size self.queue = deque() self.active = set() self.active_size = 0 self.itemproc_size = 0 self.closing = None def add_response_request(self, response, request): deferred = defer.Deferred() self.queue.append((response, request, deferred)) if isinstance(response, Response): self.active_size += max(len(response.body), self.MIN_RESPONSE_SIZE) else: self.active_size += self.MIN_RESPONSE_SIZE return deferred def next_response_request_deferred(self): response, request, deferred = self.queue.popleft() self.active.add(request) return response, request, deferred def finish_response(self, response, request): self.active.remove(request) if isinstance(response, Response): self.active_size -= max(len(response.body), self.MIN_RESPONSE_SIZE) else: self.active_size -= self.MIN_RESPONSE_SIZE def is_idle(self): return not (self.queue or self.active) def needs_backout(self): return self.active_size > self.max_active_size class Scraper(object): def __init__(self, crawler): self.slots = {} self.spidermw = SpiderMiddlewareManager.from_crawler(crawler) itemproc_cls = load_object(crawler.settings['ITEM_PROCESSOR']) self.itemproc = itemproc_cls.from_crawler(crawler) self.concurrent_items = crawler.settings.getint('CONCURRENT_ITEMS') self.crawler = crawler @defer.inlineCallbacks def open_spider(self, spider): """Open the given spider for scraping and allocate resources for it""" assert spider not in self.slots, "Spider already opened: %s" % spider self.slots[spider] = Slot() yield self.itemproc.open_spider(spider) def close_spider(self, spider): """Close a spider being scraped and release its resources""" assert spider in self.slots, "Spider not opened: %s" % spider slot = self.slots[spider] slot.closing = defer.Deferred() slot.closing.addCallback(self.itemproc.close_spider) self._check_if_closing(spider, slot) return slot.closing def is_idle(self): """Return True if there isn't any more spiders to process""" return not self.slots def _check_if_closing(self, spider, slot): if slot.closing and slot.is_idle(): del self.slots[spider] slot.closing.callback(spider) def enqueue_scrape(self, response, request, spider): slot = self.slots[spider] dfd = slot.add_response_request(response, request) def finish_scraping(_): slot.finish_response(response, request) self._check_if_closing(spider, slot) self._scrape_next(spider, slot) return _ dfd.addBoth(finish_scraping) dfd.addErrback(log.err, 'Scraper bug processing %s' % request, \ spider=spider) self._scrape_next(spider, slot) return dfd def _scrape_next(self, spider, slot): while slot.queue: response, request, deferred = slot.next_response_request_deferred() self._scrape(response, request, spider).chainDeferred(deferred) def _scrape(self, response, request, spider): """Handle the downloaded response or failure trough the spider callback/errback""" assert isinstance(response, (Response, Failure)) dfd = self._scrape2(response, request, spider) # returns spiders processed output dfd.addErrback(self.handle_spider_error, request, response, spider) dfd.addCallback(self.handle_spider_output, request, response, spider) return dfd def _scrape2(self, request_result, request, spider): """Handle the diferent cases of request's result been a Response or a Failure""" if not isinstance(request_result, Failure): return self.spidermw.scrape_response(self.call_spider, \ request_result, request, spider) else: # FIXME: don't ignore errors in spider middleware dfd = self.call_spider(request_result, request, spider) return dfd.addErrback(self._log_download_errors, \ request_result, request, spider) def call_spider(self, result, request, spider): dfd = defer_result(result) dfd.addCallbacks(request.callback or spider.parse, request.errback) return dfd.addCallback(iterate_spider_output) def handle_spider_error(self, _failure, request, response, spider): exc = _failure.value if isinstance(exc, CloseSpider): self.crawler.engine.close_spider(spider, exc.reason or 'cancelled') return log.err(_failure, "Spider error processing %s" % request, spider=spider) send_catch_log(signal=signals.spider_error, failure=_failure, response=response, \ spider=spider) stats.inc_value("spider_exceptions/%s" % _failure.value.__class__.__name__, \ spider=spider) def handle_spider_output(self, result, request, response, spider): if not result: return defer_succeed(None) it = iter_errback(result, self.handle_spider_error, request, response, spider) dfd = parallel(it, self.concurrent_items, self._process_spidermw_output, request, response, spider) return dfd def _process_spidermw_output(self, output, request, response, spider): """Process each Request/Item (given in the output parameter) returned from the given spider """ if isinstance(output, Request): send_catch_log(signal=signals.request_received, request=output, \ spider=spider) self.crawler.engine.crawl(request=output, spider=spider) elif isinstance(output, BaseItem): self.slots[spider].itemproc_size += 1 dfd = self.itemproc.process_item(output, spider) dfd.addBoth(self._itemproc_finished, output, response, spider) return dfd elif output is None: pass else: log.msg("Spider must return Request, BaseItem or None, got %r in %s" % \ (type(output).__name__, request), log.ERROR, spider=spider) def _log_download_errors(self, spider_failure, download_failure, request, spider): """Log and silence errors that come from the engine (typically download errors that got propagated thru here) """ if spider_failure is download_failure: log.msg("Error downloading %s: %s" % \ (request, spider_failure.getErrorMessage()), log.ERROR, spider=spider) return return spider_failure def _itemproc_finished(self, output, item, response, spider): """ItemProcessor finished for the given ``item`` and returned ``output`` """ self.slots[spider].itemproc_size -= 1 if isinstance(output, Failure): ex = output.value if isinstance(ex, DropItem): log.msg(log.formatter.dropped(item, ex, response, spider), \ level=log.WARNING, spider=spider) return send_catch_log_deferred(signal=signals.item_dropped, \ item=item, spider=spider, exception=output.value) else: log.err(output, 'Error processing %s' % item, spider=spider) else: log.msg(log.formatter.scraped(output, response, spider), \ log.DEBUG, spider=spider) return send_catch_log_deferred(signal=signals.item_scraped, \ item=output, response=response, spider=spider)
agpl-3.0
scavarda/mysql-dbcompare
mysql-utilities-1.6.0/info.py
1
6742
# # Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # import distutils.command.build_scripts import distutils.util import glob import os import mysql.utilities def find_packages(*args, **kwrds): """Find all packages and sub-packages and return a list of them. The function accept any number of directory names that will be searched to find packages. Packages are identified as sub-directories containing an __init__.py file. All duplicates will be removed from the list and it will be sorted alphabetically. Packages can be excluded by pattern using the 'exclude' keyword, which accepts a list of patterns. All packages with names that match the beginning of an exclude pattern will be excluded. Root base path can be attached to each package by using 'inc_base' keyword. """ from fnmatch import fnmatch excludes = kwrds.get('exclude', []) inc_base = kwrds.get('inc_base', False) pkgs = {} for base_path in args: for root, _dirs, files in os.walk(base_path): if '__init__.py' in files: assert root.startswith(base_path) pkg = root[len(base_path)+1:].replace(os.sep, '.') if inc_base and pkg: pkg = os.path.join(base_path, pkg).replace(os.sep, '.') elif inc_base: pkg = base_path.replace(os.sep, '.') pkgs[pkg] = root result = pkgs.keys() for excl in excludes: # We exclude packages that *begin* with an exclude pattern. result = [pkg for pkg in result if not fnmatch(pkg, excl + "*")] result.sort() return result def add_optional_resources(*args, **kwrds): """Adds additional resources, as source packages, scripts and data files. The function will try to find all resources in the directory names given, that will be searched to find packages, data files and scripts. Packages are identified as sub-directories containing an __init__.py file. All duplicates will be removed from the list and it will be sorted alphabetically. This function uses the find_packages function; see his help to know more how packages are found. Scripts must be set on 'scripts', and a list of the desired scripts to add must be given by 'scripts' keyword. Data files can be set in a dictionary with the keyword 'data_files', where destination is used as key and a list of source files, are the item for that key. """ excludes = kwrds.get('exclude', []) inc_base = kwrds.get('inc_base', True) data_files = kwrds.get('data_files', {}) packages_found = [] pkg_base = args[0] print('checking {0} for packages to distribute'.format(pkg_base)) pkgs = find_packages(pkg_base, exclude=excludes, inc_base=inc_base) print("packages found: {0}".format(pkgs)) packages_found.extend(pkgs) scripts_found = [] for root, _dirs, scripts in os.walk('scripts'): for script in scripts: script_path = os.path.join('scripts', script) if (not script_path.endswith('.py') and not os.path.exists('{0}.py'.format(script_path))): os.rename(script_path, '{0}.py'.format(script_path)) script_path = '{0}.py'.format(script_path) if script_path.endswith('.py'): scripts_found.append(script_path) print("scripts found: {0}".format(scripts_found)) data_files_found = [] for root, _dirs, data_files in os.walk('data'): datafiles = [] zipfiles = [] otherfiles = [] for src in data_files: name, ext = os.path.splitext(src) if ext == '.zip' and os.name != 'nt': zipfiles.append(os.path.join('data', src)) else: datafiles.append(os.path.join('data', src)) if datafiles: data_files_found.append(('data', datafiles)) if zipfiles: data_files_found.append(('/etc/mysql', zipfiles)) if otherfiles: data_files_found.append(('other', otherfiles)) if packages_found: INSTALL['packages'].extend(packages_found) print("package set {0}".format(set(INSTALL['packages']))) INSTALL['packages'] = list(set(INSTALL['packages'])) if scripts_found: INSTALL['scripts'].extend(scripts_found) INSTALL['scripts'] = list(set(INSTALL['scripts'])) if data_files_found: INSTALL['data_files'] = data_files_found META_INFO = { 'name': 'mysql-utilities', 'description': 'MySQL Utilities', 'maintainer': 'Oracle', 'maintainer_email': '', 'version': mysql.utilities.VERSION_STRING, 'url': 'http://dev.mysql.com', 'license': 'GNU GPLv2 (with FOSS License Exception)', 'keywords': "mysql db", 'classifiers': [ 'Development Status :: 3 - Alpha', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Environment :: Console', 'Environment :: Win32 (MS Windows)', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Intended Audience :: Database Administrators', 'Operating System :: Microsoft :: Windows', 'Operating System :: OS Independent', 'Operating System :: POSIX', 'Topic :: Utilities', ], } INSTALL = { 'packages': [ 'mysql', 'mysql.utilities', 'mysql.utilities.command', 'mysql.utilities.common', ], 'scripts': glob.glob('scripts/*.py'), 'requires': [ 'distutils', ], 'provides': [ 'mysql.utilities', ], } # This adds any optional resource add_optional_resources('mysql', exclude=["tests"]) if __name__=="__main__": for key, item in INSTALL.iteritems(): print("--> {0}".format(key)) print(" {0}".format(item)) print
apache-2.0
sunlianqiang/kbengine
kbe/res/scripts/common/Lib/tkinter/test/test_tkinter/test_variables.py
67
5546
import unittest from tkinter import Variable, StringVar, IntVar, DoubleVar, BooleanVar, Tcl class Var(Variable): _default = "default" side_effect = False def set(self, value): self.side_effect = True super().set(value) class TestBase(unittest.TestCase): def setUp(self): self.root = Tcl() def tearDown(self): del self.root class TestVariable(TestBase): def info_exists(self, *args): return self.root.getboolean(self.root.call("info", "exists", *args)) def test_default(self): v = Variable(self.root) self.assertEqual("", v.get()) self.assertRegex(str(v), r"^PY_VAR(\d+)$") def test_name_and_value(self): v = Variable(self.root, "sample string", "varname") self.assertEqual("sample string", v.get()) self.assertEqual("varname", str(v)) def test___del__(self): self.assertFalse(self.info_exists("varname")) v = Variable(self.root, "sample string", "varname") self.assertTrue(self.info_exists("varname")) del v self.assertFalse(self.info_exists("varname")) def test_dont_unset_not_existing(self): self.assertFalse(self.info_exists("varname")) v1 = Variable(self.root, name="name") v2 = Variable(self.root, name="name") del v1 self.assertFalse(self.info_exists("name")) # shouldn't raise exception del v2 self.assertFalse(self.info_exists("name")) def test___eq__(self): # values doesn't matter, only class and name are checked v1 = Variable(self.root, name="abc") v2 = Variable(self.root, name="abc") self.assertEqual(v1, v2) v3 = Variable(self.root, name="abc") v4 = StringVar(self.root, name="abc") self.assertNotEqual(v3, v4) def test_invalid_name(self): with self.assertRaises(TypeError): Variable(self.root, name=123) def test_null_in_name(self): with self.assertRaises(ValueError): Variable(self.root, name='var\x00name') with self.assertRaises(ValueError): self.root.globalsetvar('var\x00name', "value") with self.assertRaises(ValueError): self.root.globalsetvar(b'var\x00name', "value") with self.assertRaises(ValueError): self.root.setvar('var\x00name', "value") with self.assertRaises(ValueError): self.root.setvar(b'var\x00name', "value") def test_initialize(self): v = Var(self.root) self.assertFalse(v.side_effect) v.set("value") self.assertTrue(v.side_effect) class TestStringVar(TestBase): def test_default(self): v = StringVar(self.root) self.assertEqual("", v.get()) def test_get(self): v = StringVar(self.root, "abc", "name") self.assertEqual("abc", v.get()) self.root.globalsetvar("name", "value") self.assertEqual("value", v.get()) def test_get_null(self): v = StringVar(self.root, "abc\x00def", "name") self.assertEqual("abc\x00def", v.get()) self.root.globalsetvar("name", "val\x00ue") self.assertEqual("val\x00ue", v.get()) class TestIntVar(TestBase): def test_default(self): v = IntVar(self.root) self.assertEqual(0, v.get()) def test_get(self): v = IntVar(self.root, 123, "name") self.assertEqual(123, v.get()) self.root.globalsetvar("name", "345") self.assertEqual(345, v.get()) def test_invalid_value(self): v = IntVar(self.root, name="name") self.root.globalsetvar("name", "value") with self.assertRaises(ValueError): v.get() self.root.globalsetvar("name", "345.0") with self.assertRaises(ValueError): v.get() class TestDoubleVar(TestBase): def test_default(self): v = DoubleVar(self.root) self.assertEqual(0.0, v.get()) def test_get(self): v = DoubleVar(self.root, 1.23, "name") self.assertAlmostEqual(1.23, v.get()) self.root.globalsetvar("name", "3.45") self.assertAlmostEqual(3.45, v.get()) def test_get_from_int(self): v = DoubleVar(self.root, 1.23, "name") self.assertAlmostEqual(1.23, v.get()) self.root.globalsetvar("name", "3.45") self.assertAlmostEqual(3.45, v.get()) self.root.globalsetvar("name", "456") self.assertAlmostEqual(456, v.get()) def test_invalid_value(self): v = DoubleVar(self.root, name="name") self.root.globalsetvar("name", "value") with self.assertRaises(ValueError): v.get() class TestBooleanVar(TestBase): def test_default(self): v = BooleanVar(self.root) self.assertEqual(False, v.get()) def test_get(self): v = BooleanVar(self.root, True, "name") self.assertAlmostEqual(True, v.get()) self.root.globalsetvar("name", "0") self.assertAlmostEqual(False, v.get()) def test_invalid_value_domain(self): v = BooleanVar(self.root, name="name") self.root.globalsetvar("name", "value") with self.assertRaises(ValueError): v.get() self.root.globalsetvar("name", "1.0") with self.assertRaises(ValueError): v.get() tests_gui = (TestVariable, TestStringVar, TestIntVar, TestDoubleVar, TestBooleanVar) if __name__ == "__main__": from test.support import run_unittest run_unittest(*tests_gui)
lgpl-3.0
aitzol/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
Chapter3_MCMC/github_pull.py
13
2349
#github data scrapper """ variables of interest: indp. variables - language, given as a binary variable. Need 4 positions for 5 langagues - #number of days created ago, 1 position - has wiki? Boolean, 1 position - followers, 1 position - following, 1 position - constant dep. variables -stars/watchers -forks """ from json import loads import datetime import numpy as np from requests import get MAX = 8000000 today = datetime.datetime.today() randint = np.random.randint N = 120 #sample size. auth = ("username", "password" ) language_mappings = {"Python": 0, "JavaScript": 1, "Ruby": 2, "Java":3, "Shell":4, "PHP":5} #define data matrix: X = np.zeros( (N , 12), dtype = int ) for i in xrange(N): is_fork = True is_valid_language = False while is_fork == True or is_valid_language == False: is_fork = True is_valid_language = False params = {"since":randint(0, MAX ) } r = get("https://api.github.com/repositories", params = params, auth=auth ) results = loads( r.text )[0] #im only interested in the first one, and if it is not a fork. is_fork = results["fork"] r = get( results["url"], auth = auth) #check the language repo_results = loads( r.text ) try: language_mappings[ repo_results["language" ] ] is_valid_language = True except: pass #languages X[ i, language_mappings[ repo_results["language" ] ] ] = 1 #delta time X[ i, 6] = ( today - datetime.datetime.strptime( repo_results["created_at"][:10], "%Y-%m-%d" ) ).days #haswiki X[i, 7] = repo_results["has_wiki"] #get user information r = get( results["owner"]["url"] , auth = auth) user_results = loads( r.text ) X[i, 8] = user_results["following"] X[i, 9] = user_results["followers"] #get dep. data X[i, 10] = repo_results["watchers_count"] X[i, 11] = repo_results["forks_count"] print print " -------------- " print i, ": ", results["full_name"], repo_results["language" ], repo_results["watchers_count"], repo_results["forks_count"] print " -------------- " print np.savetxt("data/github_data.csv", X, delimiter=",", fmt="%d" )
mit
heathseals/CouchPotatoServer
libs/pyutil/scripts/passphrase.py
92
2747
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse, math, random from pyutil.mathutil import div_ceil from pkg_resources import resource_stream def recursive_subset_sum(entropy_needed, wordlists): # Pick a minimalish set of numbers which sum to at least # entropy_needed. # Okay now what's the smallest number of words which will give us # at least this much entropy? entropy_of_biggest_wordlist = wordlists[-1][0] assert isinstance(entropy_of_biggest_wordlist, float), wordlists[-1] needed_words = div_ceil(entropy_needed, entropy_of_biggest_wordlist) # How much entropy do we need from each word? needed_entropy_per_word = entropy_needed / needed_words # What's the smallest wordlist that offers at least this much # entropy per word? for (wlentropy, wl) in wordlists: if wlentropy >= needed_entropy_per_word: break assert wlentropy >= needed_entropy_per_word, (wlentropy, needed_entropy_per_word) result = [(wlentropy, wl)] # If we need more, recurse... if wlentropy < entropy_needed: rest = recursive_subset_sum(entropy_needed - wlentropy, wordlists) result.extend(rest) return result def gen_passphrase(entropy, allwords): maxlenwords = [] i = 2 # The smallest set is words of length 1 or 2. words = [x for x in allwords if len(x) <= i] maxlenwords.append((math.log(len(words), 2), words)) while len(maxlenwords[-1][1]) < len(allwords): i += 1 words = [x for x in allwords if len(x) <= i] maxlenwords.append((math.log(len(words), 2), words)) sr = random.SystemRandom() passphrase = [] wordlists_to_use = recursive_subset_sum(entropy, maxlenwords) passphraseentropy = 0.0 for (wle, wl) in wordlists_to_use: passphrase.append(sr.choice(wl)) passphraseentropy += wle return (u".".join(passphrase), passphraseentropy) def main(): parser = argparse.ArgumentParser(prog="chbs", description="Create a random passphrase by picking a few random words.") parser.add_argument('-d', '--dictionary', help="what file to read a list of words from (or omit this option to use chbs's bundled dictionary)", type=argparse.FileType('rU'), metavar="DICT") parser.add_argument('bits', help="how many bits of entropy minimum", type=float, metavar="BITS") args = parser.parse_args() dicti = args.dictionary if not dicti: dicti = resource_stream('pyutil', 'data/wordlist.txt') allwords = set([x.decode('utf-8').strip().lower() for x in dicti.readlines()]) passphrase, bits = gen_passphrase(args.bits, allwords) print u"Your new password is: '%s'. It is worth about %s bits." % (passphrase, bits)
gpl-3.0
jasonbot/django
django/contrib/syndication/views.py
192
8680
from __future__ import unicode_literals from calendar import timegm from django.conf import settings from django.contrib.sites.shortcuts import get_current_site from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.http import Http404, HttpResponse from django.template import TemplateDoesNotExist, loader from django.utils import feedgenerator, six from django.utils.encoding import force_text, iri_to_uri, smart_text from django.utils.html import escape from django.utils.http import http_date from django.utils.timezone import get_default_timezone, is_naive, make_aware def add_domain(domain, url, secure=False): protocol = 'https' if secure else 'http' if url.startswith('//'): # Support network-path reference (see #16753) - RSS requires a protocol url = '%s:%s' % (protocol, url) elif not url.startswith(('http://', 'https://', 'mailto:')): url = iri_to_uri('%s://%s%s' % (protocol, domain, url)) return url class FeedDoesNotExist(ObjectDoesNotExist): pass class Feed(object): feed_type = feedgenerator.DefaultFeed title_template = None description_template = None def __call__(self, request, *args, **kwargs): try: obj = self.get_object(request, *args, **kwargs) except ObjectDoesNotExist: raise Http404('Feed object does not exist.') feedgen = self.get_feed(obj, request) response = HttpResponse(content_type=feedgen.content_type) if hasattr(self, 'item_pubdate') or hasattr(self, 'item_updateddate'): # if item_pubdate or item_updateddate is defined for the feed, set # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED response['Last-Modified'] = http_date( timegm(feedgen.latest_post_date().utctimetuple())) feedgen.write(response, 'utf-8') return response def item_title(self, item): # Titles should be double escaped by default (see #6533) return escape(force_text(item)) def item_description(self, item): return force_text(item) def item_link(self, item): try: return item.get_absolute_url() except AttributeError: raise ImproperlyConfigured( 'Give your %s class a get_absolute_url() method, or define an ' 'item_link() method in your Feed class.' % item.__class__.__name__ ) def __get_dynamic_attr(self, attname, obj, default=None): try: attr = getattr(self, attname) except AttributeError: return default if callable(attr): # Check co_argcount rather than try/excepting the function and # catching the TypeError, because something inside the function # may raise the TypeError. This technique is more accurate. try: code = six.get_function_code(attr) except AttributeError: code = six.get_function_code(attr.__call__) if code.co_argcount == 2: # one argument is 'self' return attr(obj) else: return attr() return attr def feed_extra_kwargs(self, obj): """ Returns an extra keyword arguments dictionary that is used when initializing the feed generator. """ return {} def item_extra_kwargs(self, item): """ Returns an extra keyword arguments dictionary that is used with the `add_item` call of the feed generator. """ return {} def get_object(self, request, *args, **kwargs): return None def get_context_data(self, **kwargs): """ Returns a dictionary to use as extra context if either ``self.description_template`` or ``self.item_template`` are used. Default implementation preserves the old behavior of using {'obj': item, 'site': current_site} as the context. """ return {'obj': kwargs.get('item'), 'site': kwargs.get('site')} def get_feed(self, obj, request): """ Returns a feedgenerator.DefaultFeed object, fully populated, for this feed. Raises FeedDoesNotExist for invalid parameters. """ current_site = get_current_site(request) link = self.__get_dynamic_attr('link', obj) link = add_domain(current_site.domain, link, request.is_secure()) feed = self.feed_type( title=self.__get_dynamic_attr('title', obj), subtitle=self.__get_dynamic_attr('subtitle', obj), link=link, description=self.__get_dynamic_attr('description', obj), language=settings.LANGUAGE_CODE, feed_url=add_domain( current_site.domain, self.__get_dynamic_attr('feed_url', obj) or request.path, request.is_secure(), ), author_name=self.__get_dynamic_attr('author_name', obj), author_link=self.__get_dynamic_attr('author_link', obj), author_email=self.__get_dynamic_attr('author_email', obj), categories=self.__get_dynamic_attr('categories', obj), feed_copyright=self.__get_dynamic_attr('feed_copyright', obj), feed_guid=self.__get_dynamic_attr('feed_guid', obj), ttl=self.__get_dynamic_attr('ttl', obj), **self.feed_extra_kwargs(obj) ) title_tmp = None if self.title_template is not None: try: title_tmp = loader.get_template(self.title_template) except TemplateDoesNotExist: pass description_tmp = None if self.description_template is not None: try: description_tmp = loader.get_template(self.description_template) except TemplateDoesNotExist: pass for item in self.__get_dynamic_attr('items', obj): context = self.get_context_data(item=item, site=current_site, obj=obj, request=request) if title_tmp is not None: title = title_tmp.render(context, request) else: title = self.__get_dynamic_attr('item_title', item) if description_tmp is not None: description = description_tmp.render(context, request) else: description = self.__get_dynamic_attr('item_description', item) link = add_domain( current_site.domain, self.__get_dynamic_attr('item_link', item), request.is_secure(), ) enc = None enc_url = self.__get_dynamic_attr('item_enclosure_url', item) if enc_url: enc = feedgenerator.Enclosure( url=smart_text(enc_url), length=smart_text(self.__get_dynamic_attr('item_enclosure_length', item)), mime_type=smart_text(self.__get_dynamic_attr('item_enclosure_mime_type', item)) ) author_name = self.__get_dynamic_attr('item_author_name', item) if author_name is not None: author_email = self.__get_dynamic_attr('item_author_email', item) author_link = self.__get_dynamic_attr('item_author_link', item) else: author_email = author_link = None tz = get_default_timezone() pubdate = self.__get_dynamic_attr('item_pubdate', item) if pubdate and is_naive(pubdate): pubdate = make_aware(pubdate, tz) updateddate = self.__get_dynamic_attr('item_updateddate', item) if updateddate and is_naive(updateddate): updateddate = make_aware(updateddate, tz) feed.add_item( title=title, link=link, description=description, unique_id=self.__get_dynamic_attr('item_guid', item, link), unique_id_is_permalink=self.__get_dynamic_attr( 'item_guid_is_permalink', item), enclosure=enc, pubdate=pubdate, updateddate=updateddate, author_name=author_name, author_email=author_email, author_link=author_link, categories=self.__get_dynamic_attr('item_categories', item), item_copyright=self.__get_dynamic_attr('item_copyright', item), **self.item_extra_kwargs(item) ) return feed
bsd-3-clause
mitchelljkotler/django-cacheback
sandbox/settings.py
1
5883
import os DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'db.sqlite3', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'a5my98-t4si@aoegk1tm4!3w3&amp;vmsehkpez+5xp@b0kvk42t#b' # List of callables that know how to import templates from various sources. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'wsgi.application' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'dummyapp', 'django_rq', 'cacheback', ) INTERNAL_IPS = ('10.0.2.2',) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'cacheback': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, } } # CACHEBACK SETTINGS BROKER_URL = 'amqp://guest:guest@localhost/' CELERY_RESULT_BACKEND = 'amqp://' CELERY_TASK_SERIALIZER = 'json' RQ_QUEUES = { 'default': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } CACHEBACK_TASK_QUEUE = dict([(q, q) for q in ('celery', 'rq')]).get( os.environ.get('QUEUE', ''), 'celery')
mit
eonpatapon/nova
nova/db/sqlalchemy/migrate_repo/versions/291_enforce_flavors_migrated.py
79
1586
# 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 sqlalchemy import MetaData, Table, func, select from sqlalchemy.sql import and_ from nova import exception from nova.i18n import _ def upgrade(migrate_engine): meta = MetaData(migrate_engine) instances = Table('instances', meta, autoload=True) sysmeta = Table('instance_system_metadata', meta, autoload=True) count = select([func.count()]).select_from(sysmeta).where( and_(instances.c.uuid == sysmeta.c.instance_uuid, sysmeta.c.key == 'instance_type_id', sysmeta.c.deleted != sysmeta.c.id, instances.c.deleted != instances.c.id)).execute().scalar() if count > 0: msg = _('There are still %(count)i unmigrated flavor records. ' 'Migration cannot continue until all instance flavor ' 'records have been migrated to the new format. Please run ' '`nova-manage db migrate_flavor_data\' first.') % { 'count': count} raise exception.ValidationError(detail=msg)
apache-2.0
eXcomm/MozDef
mq/plugins/complianceitems.py
9
2980
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Copyright (c) 2014 Mozilla Corporation # # Contributors: # Julien Vehent jvehent@mozilla.com # Aaron Meihm ameihm@mozilla.com import hashlib import sys class message(object): def __init__(self): self.registration = ['complianceitems'] self.priority = 20 def validate(self,item): """ Validate that a compliance item has all the necessary keys """ for key in ['target', 'policy', 'check', 'compliance', 'link', 'utctimestamp']: if key not in item.keys(): return False for key in ['level', 'name', 'url']: if key not in item['policy'].keys(): return False for key in ['description', 'location', 'name', 'test']: if key not in item['check'].keys(): return False for key in ['type', 'value']: if key not in item['check']['test'].keys(): return False return True def cleanup_item(self,item): ci = {} ci['target'] = item['target'] ci['policy'] = {} ci['policy']['level'] = item['policy']['level'] ci['policy']['name'] = item['policy']['name'] ci['policy']['url'] = item['policy']['url'] ci['check'] = {} ci['check']['description'] = item['check']['description'] ci['check']['location'] = item['check']['location'] ci['check']['name'] = item['check']['name'] ci['check']['test'] = {} ci['check']['test']['type'] = item['check']['test']['type'] ci['check']['test']['value'] = item['check']['test']['value'] ci['check']['ref'] = item['check']['ref'] ci['compliance'] = item['compliance'] ci['link'] = item['link'] ci['utctimestamp'] = item['utctimestamp'] if 'tags' in item: ci['tags'] = item['tags'] return ci def onMessage(self, message, metadata): """ The complianceitems plugin is called when an event is posted with a doctype 'complianceitems'. Compliance items are stored in the complianceitems index, with doctype last_known_state """ if not self.validate(message['details']): sys.stderr.write('error: invalid format for complianceitem {0}'.format(message)) return (None, None) item = self.cleanup_item(message['details']) docidstr = 'complianceitems' docidstr += item['check']['ref'] docidstr += item['check']['test']['value'] docidstr += item['target'] metadata['id'] = hashlib.md5(docidstr).hexdigest() metadata['doc_type'] = 'last_known_state' metadata['index'] = 'complianceitems' return (item, metadata)
mpl-2.0
erkrishna9/odoo
openerp/tools/mail.py
15
28938
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (C) 2012-TODAY OpenERP S.A. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from lxml import etree import cgi import logging import lxml.html import lxml.html.clean as clean import random import re import socket import threading import time from email.utils import getaddresses import openerp from openerp.loglevels import ustr _logger = logging.getLogger(__name__) #---------------------------------------------------------- # HTML Sanitizer #---------------------------------------------------------- tags_to_kill = ["script", "head", "meta", "title", "link", "style", "frame", "iframe", "base", "object", "embed"] tags_to_remove = ['html', 'body', 'font'] # allow new semantic HTML5 tags allowed_tags = clean.defs.tags | frozenset('article section header footer hgroup nav aside figure main'.split() + [etree.Comment]) safe_attrs = clean.defs.safe_attrs | frozenset( ['style', 'data-oe-model', 'data-oe-id', 'data-oe-field', 'data-oe-type', 'data-oe-expression', 'data-oe-translate', 'data-oe-nodeid', 'data-snippet-id', 'data-publish', 'data-id', 'data-res_id', 'data-member_id', 'data-view-id' ]) def html_sanitize(src, silent=True, strict=False): if not src: return src src = ustr(src, errors='replace') logger = logging.getLogger(__name__ + '.html_sanitize') # html encode email tags part = re.compile(r"(<(([^a<>]|a[^<>\s])[^<>]*)@[^<>]+>)", re.IGNORECASE | re.DOTALL) src = part.sub(lambda m: cgi.escape(m.group(1)), src) kwargs = { 'page_structure': True, 'style': False, # do not remove style attributes 'forms': True, # remove form tags 'remove_unknown_tags': False, 'allow_tags': allowed_tags, 'comments': False, 'processing_instructions' : False } if etree.LXML_VERSION >= (2, 3, 1): # kill_tags attribute has been added in version 2.3.1 kwargs.update({ 'kill_tags': tags_to_kill, 'remove_tags': tags_to_remove, }) else: kwargs['remove_tags'] = tags_to_kill + tags_to_remove if strict: if etree.LXML_VERSION >= (3, 1, 0): # lxml < 3.1.0 does not allow to specify safe_attrs. We keep all attributes in order to keep "style" kwargs.update({ 'safe_attrs_only': True, 'safe_attrs': safe_attrs, }) else: kwargs['safe_attrs_only'] = False # keep oe-data attributes + style kwargs['frames'] = False, # do not remove frames (embbed video in CMS blogs) try: # some corner cases make the parser crash (such as <SCRIPT/XSS SRC=\"http://ha.ckers.org/xss.js\"></SCRIPT> in test_mail) cleaner = clean.Cleaner(**kwargs) cleaned = cleaner.clean_html(src) # MAKO compatibility: $, { and } inside quotes are escaped, preventing correct mako execution cleaned = cleaned.replace('%24', '$') cleaned = cleaned.replace('%7B', '{') cleaned = cleaned.replace('%7D', '}') cleaned = cleaned.replace('%20', ' ') cleaned = cleaned.replace('%5B', '[') cleaned = cleaned.replace('%5D', ']') except etree.ParserError, e: if 'empty' in str(e): return "" if not silent: raise logger.warning('ParserError obtained when sanitizing %r', src, exc_info=True) cleaned = '<p>ParserError when sanitizing</p>' except Exception: if not silent: raise logger.warning('unknown error obtained when sanitizing %r', src, exc_info=True) cleaned = '<p>Unknown error when sanitizing</p>' # this is ugly, but lxml/etree tostring want to put everything in a 'div' that breaks the editor -> remove that if cleaned.startswith('<div>') and cleaned.endswith('</div>'): cleaned = cleaned[5:-6] return cleaned #---------------------------------------------------------- # HTML Cleaner #---------------------------------------------------------- def html_email_clean(html, remove=False, shorten=False, max_length=300, expand_options=None, protect_sections=False): """ html_email_clean: clean the html by doing the following steps: - try to strip email quotes, by removing blockquotes or having some client- specific heuristics - try to strip signatures - shorten the html to a maximum number of characters if requested Some specific use case: - MsOffice: ``div.style = border-top:solid;`` delimitates the beginning of a quote; detecting by finding WordSection1 of MsoNormal - Hotmail: ``hr.stopSpelling`` delimitates the beginning of a quote; detect Hotmail by funding ``SkyDrivePlaceholder`` :param string html: sanitized html; tags like html or head should not be present in the html string. This method therefore takes as input html code coming from a sanitized source, like fields.html. :param boolean remove: remove the html code that is unwanted; otherwise it is only flagged and tagged :param boolean shorten: shorten the html; every excessing content will be flagged as to remove :param int max_length: if shortening, maximum number of characters before shortening :param dict expand_options: options for the read more link when shortening the content.The used keys are the following: - oe_expand_container_tag: class applied to the container of the whole read more link - oe_expand_container_class: class applied to the link container (default: oe_mail_expand) - oe_expand_container_content: content of the container (default: ...) - oe_expand_separator_node: optional separator, like adding ... <br /><br /> <a ...>read more</a> (default: void) - oe_expand_a_href: href of the read more link itself (default: #) - oe_expand_a_class: class applied to the <a> containing the link itself (default: oe_mail_expand) - oe_expand_a_content: content of the <a> (default: read more) The formatted read more link is the following: <cont_tag class="oe_expand_container_class"> oe_expand_container_content if expand_options.get('oe_expand_separator_node'): <oe_expand_separator_node/> <a href="oe_expand_a_href" class="oe_expand_a_class"> oe_expand_a_content </a> </span> """ def _replace_matching_regex(regex, source, replace=''): """ Replace all matching expressions in source by replace """ if not source: return source dest = '' idx = 0 for item in re.finditer(regex, source): dest += source[idx:item.start()] + replace idx = item.end() dest += source[idx:] return dest def _create_node(tag, text, tail=None, attrs={}): new_node = etree.Element(tag) new_node.text = text new_node.tail = tail for key, val in attrs.iteritems(): new_node.set(key, val) return new_node def _insert_new_node(node, index, new_node_tag, new_node_text, new_node_tail=None, new_node_attrs={}): new_node = _create_node(new_node_tag, new_node_text, new_node_tail, new_node_attrs) node.insert(index, new_node) return new_node def _tag_matching_regex_in_text(regex, node, new_node_tag='span', new_node_attrs={}): text = node.text or '' if not re.search(regex, text): return cur_node = node node.text = '' idx, iteration = 0, 0 for item in re.finditer(regex, text): if iteration == 0: cur_node.text = text[idx:item.start()] else: _insert_new_node(node, (iteration - 1) * 2 + 1, new_node_tag, text[idx:item.start()]) new_node = _insert_new_node(node, iteration * 2, new_node_tag, text[item.start():item.end()], None, new_node_attrs) cur_node = new_node idx = item.end() iteration += 1 new_node = _insert_new_node(node, -1, new_node_tag, text[idx:] + (cur_node.tail or ''), None, {}) def _truncate_node(node, position, simplify_whitespaces=True): """ Truncate a node text at a given position. This algorithm will shorten at the end of the word whose ending character exceeds position. :param bool simplify_whitespaces: whether to try to count all successive whitespaces as one character. This option should not be True when trying to keep 'pre' consistency. """ if node.text is None: node.text = '' truncate_idx = -1 if simplify_whitespaces: cur_char_nbr = 0 word = None node_words = node.text.strip(' \t\r\n').split() for word in node_words: cur_char_nbr += len(word) if cur_char_nbr >= position: break if word: truncate_idx = node.text.find(word) + len(word) else: truncate_idx = position if truncate_idx == -1 or truncate_idx > len(node.text): truncate_idx = len(node.text) # compose new text bits innertext = node.text[0:truncate_idx] outertext = node.text[truncate_idx:] node.text = innertext # create <span> ... <a href="#">read more</a></span> node read_more_node = _create_node( expand_options.get('oe_expand_container_tag', 'span'), expand_options.get('oe_expand_container_content', ' ... '), None, {'class': expand_options.get('oe_expand_container_class', 'oe_mail_expand')} ) if expand_options.get('oe_expand_separator_node'): read_more_separator_node = _create_node( expand_options.get('oe_expand_separator_node'), '', None, {} ) read_more_node.append(read_more_separator_node) read_more_link_node = _create_node( 'a', expand_options.get('oe_expand_a_content', 'read more'), None, { 'href': expand_options.get('oe_expand_a_href', '#'), 'class': expand_options.get('oe_expand_a_class', 'oe_mail_expand'), } ) read_more_node.append(read_more_link_node) # create outertext node overtext_node = _create_node('span', outertext) # tag node overtext_node.set('in_overlength', '1') # add newly created nodes in dom node.append(read_more_node) node.append(overtext_node) if expand_options is None: expand_options = {} if not html or not isinstance(html, basestring): return html html = ustr(html) # Pre processing # ------------------------------------------------------------ # TDE TODO: --- MAIL ORIGINAL ---: '[\-]{4,}([^\-]*)[\-]{4,}' # html: remove encoding attribute inside tags doctype = re.compile(r'(<[^>]*\s)(encoding=(["\'][^"\']*?["\']|[^\s\n\r>]+)(\s[^>]*|/)?>)', re.IGNORECASE | re.DOTALL) html = doctype.sub(r"", html) # html: ClEditor seems to love using <div><br /><div> -> replace with <br /> br_div_tags = re.compile(r'(<div>\s*<br\s*\/>\s*<\/div>)', re.IGNORECASE) html = _replace_matching_regex(br_div_tags, html, '<br />') # form a tree root = lxml.html.fromstring(html) if not len(root) and root.text is None and root.tail is None: html = '<div>%s</div>' % html root = lxml.html.fromstring(html) quote_tags = re.compile(r'(\n(>)+[^\n\r]*)') signature = re.compile(r'([-]{2,}[\s]?[\r\n]{1,2}[\s\S]+)') for node in root.iter(): # remove all tails and replace them by a span element, because managing text and tails can be a pain in the ass if node.tail: tail_node = _create_node('span', node.tail) node.tail = None node.addnext(tail_node) # form node and tag text-based quotes and signature _tag_matching_regex_in_text(quote_tags, node, 'span', {'text_quote': '1'}) _tag_matching_regex_in_text(signature, node, 'span', {'text_signature': '1'}) # Processing # ------------------------------------------------------------ # tree: tag nodes # signature_begin = False # try dynamic signature recognition quote_begin = False overlength = False overlength_section_id = None overlength_section_count = 0 cur_char_nbr = 0 for node in root.iter(): # comments do not need processing # note: bug in node.get(value, default) for HtmlComments, default never returned if node.tag == etree.Comment: continue # do not take into account multiple spaces that are displayed as max 1 space in html node_text = ' '.join((node.text and node.text.strip(' \t\r\n') or '').split()) # root: try to tag the client used to write the html if 'WordSection1' in node.get('class', '') or 'MsoNormal' in node.get('class', ''): root.set('msoffice', '1') if 'SkyDrivePlaceholder' in node.get('class', '') or 'SkyDrivePlaceholder' in node.get('id', ''): root.set('hotmail', '1') # protect sections by tagging section limits and blocks contained inside sections, using an increasing id to re-find them later if node.tag == 'section': overlength_section_count += 1 node.set('section_closure', str(overlength_section_count)) if node.getparent() is not None and (node.getparent().get('section_closure') or node.getparent().get('section_inner')): node.set('section_inner', str(overlength_section_count)) # state of the parsing: flag quotes and tails to remove if quote_begin: node.set('in_quote', '1') node.set('tail_remove', '1') # state of the parsing: flag when being in over-length content, depending on section content if defined (only when having protect_sections) if overlength: if not overlength_section_id or int(node.get('section_inner', overlength_section_count + 1)) > overlength_section_count: node.set('in_overlength', '1') node.set('tail_remove', '1') # find quote in msoffice / hotmail / blockquote / text quote and signatures if root.get('msoffice') and node.tag == 'div' and 'border-top:solid' in node.get('style', ''): quote_begin = True node.set('in_quote', '1') node.set('tail_remove', '1') if root.get('hotmail') and node.tag == 'hr' and ('stopSpelling' in node.get('class', '') or 'stopSpelling' in node.get('id', '')): quote_begin = True node.set('in_quote', '1') node.set('tail_remove', '1') if node.tag == 'blockquote' or node.get('text_quote') or node.get('text_signature'): node.set('in_quote', '1') # shorten: # if protect section: # 1/ find the first parent not being inside a section # 2/ add the read more link # else: # 1/ truncate the text at the next available space # 2/ create a 'read more' node, next to current node # 3/ add the truncated text in a new node, next to 'read more' node node_text = (node.text or '').strip().strip('\n').strip() if shorten and not overlength and cur_char_nbr + len(node_text) > max_length: node_to_truncate = node while node_to_truncate.getparent() is not None: if node_to_truncate.get('in_quote'): node_to_truncate = node_to_truncate.getparent() elif protect_sections and (node_to_truncate.getparent().get('section_inner') or node_to_truncate.getparent().get('section_closure')): node_to_truncate = node_to_truncate.getparent() overlength_section_id = node_to_truncate.get('section_closure') else: break overlength = True node_to_truncate.set('truncate', '1') if node_to_truncate == node: node_to_truncate.set('truncate_position', str(max_length - cur_char_nbr)) else: node_to_truncate.set('truncate_position', str(len(node.text or ''))) cur_char_nbr += len(node_text) # Tree modification # ------------------------------------------------------------ for node in root.iter(): if node.get('truncate'): _truncate_node(node, int(node.get('truncate_position', '0')), node.tag != 'pre') # Post processing # ------------------------------------------------------------ to_remove = [] for node in root.iter(): if node.get('in_quote') or node.get('in_overlength'): # copy the node tail into parent text if node.tail and not node.get('tail_remove'): parent = node.getparent() parent.tail = node.tail + (parent.tail or '') to_remove.append(node) if node.get('tail_remove'): node.tail = '' # clean node for attribute_name in ['in_quote', 'tail_remove', 'in_overlength', 'msoffice', 'hotmail', 'truncate', 'truncate_position']: node.attrib.pop(attribute_name, None) for node in to_remove: if remove: node.getparent().remove(node) else: if not expand_options.get('oe_expand_a_class', 'oe_mail_expand') in node.get('class', ''): # trick: read more link should be displayed even if it's in overlength node_class = node.get('class', '') + ' oe_mail_cleaned' node.set('class', node_class) # html: \n that were tail of elements have been encapsulated into <span> -> back to \n html = etree.tostring(root, pretty_print=False) linebreaks = re.compile(r'<span[^>]*>([\s]*[\r\n]+[\s]*)<\/span>', re.IGNORECASE | re.DOTALL) html = _replace_matching_regex(linebreaks, html, '\n') return html #---------------------------------------------------------- # HTML/Text management #---------------------------------------------------------- def html2plaintext(html, body_id=None, encoding='utf-8'): """ From an HTML text, convert the HTML to plain text. If @param body_id is provided then this is the tag where the body (not necessarily <body>) starts. """ ## (c) Fry-IT, www.fry-it.com, 2007 ## <peter@fry-it.com> ## download here: http://www.peterbe.com/plog/html2plaintext html = ustr(html) tree = etree.fromstring(html, parser=etree.HTMLParser()) if body_id is not None: source = tree.xpath('//*[@id=%s]' % (body_id,)) else: source = tree.xpath('//body') if len(source): tree = source[0] url_index = [] i = 0 for link in tree.findall('.//a'): url = link.get('href') if url: i += 1 link.tag = 'span' link.text = '%s [%s]' % (link.text, i) url_index.append(url) html = ustr(etree.tostring(tree, encoding=encoding)) # \r char is converted into &#13;, must remove it html = html.replace('&#13;', '') html = html.replace('<strong>', '*').replace('</strong>', '*') html = html.replace('<b>', '*').replace('</b>', '*') html = html.replace('<h3>', '*').replace('</h3>', '*') html = html.replace('<h2>', '**').replace('</h2>', '**') html = html.replace('<h1>', '**').replace('</h1>', '**') html = html.replace('<em>', '/').replace('</em>', '/') html = html.replace('<tr>', '\n') html = html.replace('</p>', '\n') html = re.sub('<br\s*/?>', '\n', html) html = re.sub('<.*?>', ' ', html) html = html.replace(' ' * 2, ' ') html = html.replace('&gt;', '>') html = html.replace('&lt;', '<') # strip all lines html = '\n'.join([x.strip() for x in html.splitlines()]) html = html.replace('\n' * 2, '\n') for i, url in enumerate(url_index): if i == 0: html += '\n\n' html += ustr('[%s] %s\n') % (i + 1, url) return html def plaintext2html(text, container_tag=False): """ Convert plaintext into html. Content of the text is escaped to manage html entities, using cgi.escape(). - all \n,\r are replaced by <br /> - enclose content into <p> - 2 or more consecutive <br /> are considered as paragraph breaks :param string container_tag: container of the html; by default the content is embedded into a <div> """ text = cgi.escape(ustr(text)) # 1. replace \n and \r text = text.replace('\n', '<br/>') text = text.replace('\r', '<br/>') # 2-3: form paragraphs idx = 0 final = '<p>' br_tags = re.compile(r'(([<]\s*[bB][rR]\s*\/?[>]\s*){2,})') for item in re.finditer(br_tags, text): final += text[idx:item.start()] + '</p><p>' idx = item.end() final += text[idx:] + '</p>' # 4. container if container_tag: final = '<%s>%s</%s>' % (container_tag, final, container_tag) return ustr(final) def append_content_to_html(html, content, plaintext=True, preserve=False, container_tag=False): """ Append extra content at the end of an HTML snippet, trying to locate the end of the HTML document (</body>, </html>, or EOF), and converting the provided content in html unless ``plaintext`` is False. Content conversion can be done in two ways: - wrapping it into a pre (preserve=True) - use plaintext2html (preserve=False, using container_tag to wrap the whole content) A side-effect of this method is to coerce all HTML tags to lowercase in ``html``, and strip enclosing <html> or <body> tags in content if ``plaintext`` is False. :param str html: html tagsoup (doesn't have to be XHTML) :param str content: extra content to append :param bool plaintext: whether content is plaintext and should be wrapped in a <pre/> tag. :param bool preserve: if content is plaintext, wrap it into a <pre> instead of converting it into html """ html = ustr(html) if plaintext and preserve: content = u'\n<pre>%s</pre>\n' % ustr(content) elif plaintext: content = '\n%s\n' % plaintext2html(content, container_tag) else: content = re.sub(r'(?i)(</?html.*>|</?body.*>|<!\W*DOCTYPE.*>)', '', content) content = u'\n%s\n' % ustr(content) # Force all tags to lowercase html = re.sub(r'(</?)\W*(\w+)([ >])', lambda m: '%s%s%s' % (m.group(1), m.group(2).lower(), m.group(3)), html) insert_location = html.find('</body>') if insert_location == -1: insert_location = html.find('</html>') if insert_location == -1: return '%s%s' % (html, content) return '%s%s%s' % (html[:insert_location], content, html[insert_location:]) #---------------------------------------------------------- # Emails #---------------------------------------------------------- # matches any email in a body of text email_re = re.compile(r"""([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})""", re.VERBOSE) # matches a string containing only one email single_email_re = re.compile(r"""^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$""", re.VERBOSE) res_re = re.compile(r"\[([0-9]+)\]", re.UNICODE) command_re = re.compile("^Set-([a-z]+) *: *(.+)$", re.I + re.UNICODE) # Updated in 7.0 to match the model name as well # Typical form of references is <timestamp-openerp-record_id-model_name@domain> # group(1) = the record ID ; group(2) = the model (if any) ; group(3) = the domain reference_re = re.compile("<.*-open(?:object|erp)-(\\d+)(?:-([\w.]+))?.*@(.*)>", re.UNICODE) # Bounce regex # Typical form of bounce is bounce-128-crm.lead-34@domain # group(1) = the mail ID; group(2) = the model (if any); group(3) = the record ID bounce_re = re.compile("[\w]+-(\d+)-?([\w.]+)?-?(\d+)?", re.UNICODE) def generate_tracking_message_id(res_id): """Returns a string that can be used in the Message-ID RFC822 header field Used to track the replies related to a given object thanks to the "In-Reply-To" or "References" fields that Mail User Agents will set. """ try: rnd = random.SystemRandom().random() except NotImplementedError: rnd = random.random() rndstr = ("%.15f" % rnd)[2:] return "<%.15f.%s-openerp-%s@%s>" % (time.time(), rndstr, res_id, socket.gethostname()) def email_send(email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False, attachments=None, message_id=None, references=None, openobject_id=False, debug=False, subtype='plain', headers=None, smtp_server=None, smtp_port=None, ssl=False, smtp_user=None, smtp_password=None, cr=None, uid=None): """Low-level function for sending an email (deprecated). :deprecate: since OpenERP 6.1, please use ir.mail_server.send_email() instead. :param email_from: A string used to fill the `From` header, if falsy, config['email_from'] is used instead. Also used for the `Reply-To` header if `reply_to` is not provided :param email_to: a sequence of addresses to send the mail to. """ # If not cr, get cr from current thread database local_cr = None if not cr: db_name = getattr(threading.currentThread(), 'dbname', None) if db_name: local_cr = cr = openerp.registry(db_name).cursor() else: raise Exception("No database cursor found, please pass one explicitly") # Send Email try: mail_server_pool = openerp.registry(cr.dbname)['ir.mail_server'] res = False # Pack Message into MIME Object email_msg = mail_server_pool.build_email(email_from, email_to, subject, body, email_cc, email_bcc, reply_to, attachments, message_id, references, openobject_id, subtype, headers=headers) res = mail_server_pool.send_email(cr, uid or 1, email_msg, mail_server_id=None, smtp_server=smtp_server, smtp_port=smtp_port, smtp_user=smtp_user, smtp_password=smtp_password, smtp_encryption=('ssl' if ssl else None), smtp_debug=debug) except Exception: _logger.exception("tools.email_send failed to deliver email") return False finally: if local_cr: cr.close() return res def email_split(text): """ Return a list of the email addresses found in ``text`` """ if not text: return [] return [addr[1] for addr in getaddresses([text]) # getaddresses() returns '' when email parsing fails, and # sometimes returns emails without at least '@'. The '@' # is strictly required in RFC2822's `addr-spec`. if addr[1] if '@' in addr[1]]
agpl-3.0
CentroGeo/geonode
geonode/base/management/commands/lib/gn20_to_24.py
6
9294
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################### import re import datetime import json from django.utils import timezone class DefaultMangler(json.JSONDecoder): def __init__(self, *args, **kwargs): self.basepk = kwargs.get('basepk', -1) self.owner = kwargs.get('owner', 'admin') self.datastore = kwargs.get('datastore', '') self.siteurl = kwargs.get('siteurl', '') super(DefaultMangler, self).__init__(*args) def default(self, obj): # Let the base class default method raise the TypeError return json.JSONEncoder.default(self, obj) def decode(self, json_string): """ json_string is basicly string that you give to json.loads method """ default_obj = super(DefaultMangler, self).decode(json_string) # manipulate your object any way you want # .... return default_obj class ResourceBaseMangler(DefaultMangler): def default(self, obj): # Let the base class default method raise the TypeError return json.JSONEncoder.default(self, obj) def decode(self, json_string): """ json_string is basicly string that you give to json.loads method """ default_obj = super(ResourceBaseMangler, self).decode(json_string) # manipulate your object any way you want # .... upload_sessions = [] for obj in default_obj: obj['pk'] = obj['pk'] + self.basepk obj['fields']['featured'] = False obj['fields']['rating'] = 0 obj['fields']['popular_count'] = 0 obj['fields']['share_count'] = 0 obj['fields']['is_published'] = True obj['fields']['thumbnail_url'] = '' if 'distribution_url' in obj['fields']: if not obj['fields']['distribution_url'] is None and 'layers' in obj['fields']['distribution_url']: obj['fields']['polymorphic_ctype'] = ["layers", "layer"] try: p = '(?P<protocol>http.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*)(?P<details_url>.*)' m = re.search(p, obj['fields']['distribution_url']) if 'http' in m.group('protocol'): obj['fields']['detail_url'] = self.siteurl + m.group('details_url') else: obj['fields']['detail_url'] = self.siteurl + obj['fields']['distribution_url'] except Exception: obj['fields']['detail_url'] = obj['fields']['distribution_url'] else: obj['fields']['polymorphic_ctype'] = ["maps", "map"] try: obj['fields'].pop("distribution_description", None) except Exception: pass try: obj['fields'].pop("distribution_url", None) except Exception: pass try: obj['fields'].pop("thumbnail", None) except Exception: pass upload_sessions.append(self.add_upload_session(obj['pk'], obj['fields']['owner'])) default_obj.extend(upload_sessions) return default_obj def add_upload_session(self, pk, owner): obj = dict() obj['pk'] = pk obj['model'] = 'layers.uploadsession' obj['fields'] = dict() obj['fields']['user'] = owner obj['fields']['traceback'] = None obj['fields']['context'] = None obj['fields']['error'] = None obj['fields']['processed'] = True obj['fields']['date'] = datetime.datetime.now(timezone.get_current_timezone()).strftime("%Y-%m-%dT%H:%M:%S") return obj class LayerMangler(DefaultMangler): def default(self, obj): # Let the base class default method raise the TypeError return json.JSONEncoder.default(self, obj) def decode(self, json_string): """ json_string is basicly string that you give to json.loads method """ default_obj = super(LayerMangler, self).decode(json_string) # manipulate your object any way you want # .... for obj in default_obj: obj['pk'] = obj['pk'] + self.basepk # Retrieve the ResourceBase associated to this Layer from geonode.base.models import ResourceBase resource = ResourceBase.objects.get(pk=obj['pk']) obj['fields']['upload_session'] = obj['pk'] obj['fields']['service'] = None obj['fields']['charset'] = "UTF-8" obj['fields']['title_en'] = resource.title obj['fields']['data_quality_statement_en'] = "" obj['fields']['regions'] = [] obj['fields']['supplemental_information_en'] = "No information provided" obj['fields']['abstract_en'] = "No abstract provided" obj['fields']['purpose_en'] = "" obj['fields']['constraints_other_en'] = "" obj['fields']['default_style'] = None if self.datastore: obj['fields']['store'] = self.datastore else: obj['fields']['store'] = obj['fields']['name'] try: obj['fields'].pop("popular_count", None) except Exception: pass try: obj['fields'].pop("share_count", None) except Exception: pass try: obj['fields'].pop("title", None) except Exception: pass return default_obj class LayerAttributesMangler(DefaultMangler): def default(self, obj): # Let the base class default method raise the TypeError return json.JSONEncoder.default(self, obj) def decode(self, json_string): """ json_string is basicly string that you give to json.loads method """ default_obj = super(LayerAttributesMangler, self).decode(json_string) # manipulate your object any way you want # .... for obj in default_obj: obj['pk'] = obj['pk'] + self.basepk obj['fields']['layer'] = obj['fields']['layer'] + self.basepk return default_obj class MapMangler(DefaultMangler): def default(self, obj): # Let the base class default method raise the TypeError return json.JSONEncoder.default(self, obj) def decode(self, json_string): """ json_string is basicly string that you give to json.loads method """ default_obj = super(MapMangler, self).decode(json_string) # manipulate your object any way you want # .... for obj in default_obj: obj['pk'] = obj['pk'] + self.basepk # Retrieve the ResourceBase associated to this Layer from geonode.base.models import ResourceBase resource = ResourceBase.objects.get(pk=obj['pk']) obj['fields']['urlsuffix'] = "" obj['fields']['title_en'] = resource.title obj['fields']['featuredurl'] = "" obj['fields']['data_quality_statement_en'] = None obj['fields']['supplemental_information_en'] = "No information provided" obj['fields']['abstract_en'] = "" obj['fields']['purpose_en'] = None obj['fields']['constraints_other_en'] = None try: obj['fields'].pop("popular_count", None) except Exception: pass try: obj['fields'].pop("share_count", None) except Exception: pass try: obj['fields'].pop("title", None) except Exception: pass return default_obj class MapLayersMangler(DefaultMangler): def default(self, obj): # Let the base class default method raise the TypeError return json.JSONEncoder.default(self, obj) def decode(self, json_string): """ json_string is basicly string that you give to json.loads method """ default_obj = super(MapLayersMangler, self).decode(json_string) # manipulate your object any way you want # .... for obj in default_obj: obj['pk'] = obj['pk'] + self.basepk obj['fields']['map'] = obj['fields']['map'] + self.basepk return default_obj
gpl-3.0
isslayne/Enigma2-CN
lib/python/Plugins/SystemPlugins/Videomode/plugin.py
32
9361
from Screens.Screen import Screen from Plugins.Plugin import PluginDescriptor from Components.SystemInfo import SystemInfo from Components.ConfigList import ConfigListScreen from Components.config import getConfigListEntry, config, ConfigBoolean, ConfigNothing, ConfigSlider from Components.Label import Label from Components.Sources.StaticText import StaticText from VideoHardware import video_hw config.misc.videowizardenabled = ConfigBoolean(default = True) class VideoSetup(Screen, ConfigListScreen): def __init__(self, session, hw): Screen.__init__(self, session) # for the skin: first try VideoSetup, then Setup, this allows individual skinning self.skinName = ["VideoSetup", "Setup" ] self.setup_title = _("A/V settings") self.hw = hw self.onChangedEntry = [ ] # handle hotplug by re-creating setup self.onShow.append(self.startHotplug) self.onHide.append(self.stopHotplug) self.list = [ ] ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changedEntry) from Components.ActionMap import ActionMap self["actions"] = ActionMap(["SetupActions", "MenuActions"], { "cancel": self.keyCancel, "save": self.apply, "menu": self.closeRecursive, }, -2) self["key_red"] = StaticText(_("Cancel")) self["key_green"] = StaticText(_("OK")) self["description"] = Label("") self.createSetup() self.grabLastGoodMode() self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): self.setTitle(self.setup_title) def startHotplug(self): self.hw.on_hotplug.append(self.createSetup) def stopHotplug(self): self.hw.on_hotplug.remove(self.createSetup) def createSetup(self): level = config.usage.setup_level.index self.list = [ getConfigListEntry(_("Video output"), config.av.videoport, _("Configures which video output connector will be used.")) ] # if we have modes for this port: if config.av.videoport.value in config.av.videomode: # add mode- and rate-selection: self.list.append(getConfigListEntry(pgettext("Video output mode", "Mode"), config.av.videomode[config.av.videoport.value], _("Configure the video output mode (or resolution)."))) if config.av.videomode[config.av.videoport.value].value == 'PC': self.list.append(getConfigListEntry(_("Resolution"), config.av.videorate[config.av.videomode[config.av.videoport.value].value], _("Configure the screen resolution in PC output mode."))) else: self.list.append(getConfigListEntry(_("Refresh rate"), config.av.videorate[config.av.videomode[config.av.videoport.value].value], _("Configure the refresh rate of the screen."))) port = config.av.videoport.value if port not in config.av.videomode: mode = None else: mode = config.av.videomode[port].value # some modes (720p, 1080i) are always widescreen. Don't let the user select something here, "auto" is not what he wants. force_wide = self.hw.isWidescreenMode(port, mode) if not force_wide: self.list.append(getConfigListEntry(_("Aspect ratio"), config.av.aspect, _("Configure the aspect ratio of the screen."))) if force_wide or config.av.aspect.value in ("16_9", "16_10"): self.list.extend(( getConfigListEntry(_("Display 4:3 content as"), config.av.policy_43, _("When the content has an aspect ratio of 4:3, choose whether to scale/stretch the picture.")), getConfigListEntry(_("Display >16:9 content as"), config.av.policy_169, _("When the content has an aspect ratio of 16:9, choose whether to scale/stretch the picture.")) )) elif config.av.aspect.value == "4_3": self.list.append(getConfigListEntry(_("Display 16:9 content as"), config.av.policy_169, _("When the content has an aspect ratio of 16:9, choose whether to scale/stretch the picture."))) # if config.av.videoport.value == "DVI": # self.list.append(getConfigListEntry(_("Allow Unsupported Modes"), config.av.edid_override)) if config.av.videoport.value == "Scart": self.list.append(getConfigListEntry(_("Color format"), config.av.colorformat, _("Configure which color format should be used on the SCART output."))) if level >= 1: self.list.append(getConfigListEntry(_("WSS on 4:3"), config.av.wss, _("When enabled, content with an aspect ratio of 4:3 will be stretched to fit the screen."))) if SystemInfo["ScartSwitch"]: self.list.append(getConfigListEntry(_("Auto scart switching"), config.av.vcrswitch, _("When enabled, your receiver will detect activity on the VCR SCART input."))) if level >= 1: if SystemInfo["CanDownmixAC3"]: self.list.append(getConfigListEntry(_("AC3 downmix"), config.av.downmix_ac3, _("Configure whether multi channel sound tracks should be downmixed to stereo."))) if SystemInfo["CanDownmixDTS"]: self.list.append(getConfigListEntry(_("DTS downmix"), config.av.downmix_dts, _("Configure whether multi channel sound tracks should be downmixed to stereo."))) if SystemInfo["CanDownmixAAC"]: self.list.append(getConfigListEntry(_("AAC downmix"), config.av.downmix_aac, _("Configure whether multi channel sound tracks should be downmixed to stereo."))) self.list.extend(( getConfigListEntry(_("General AC3 delay"), config.av.generalAC3delay, _("Configure the general audio delay of Dolby Digital sound tracks.")), getConfigListEntry(_("General PCM delay"), config.av.generalPCMdelay, _("Configure the general audio delay of stereo sound tracks.")) )) if SystemInfo["CanChangeOsdAlpha"]: self.list.append(getConfigListEntry(_("OSD transparency"), config.av.osd_alpha, _("Configure the transparency of the OSD."))) if not isinstance(config.av.scaler_sharpness, ConfigNothing): self.list.append(getConfigListEntry(_("Scaler sharpness"), config.av.scaler_sharpness, _("Configure the sharpness of the video scaling."))) self["config"].list = self.list self["config"].l.setList(self.list) def keyLeft(self): ConfigListScreen.keyLeft(self) self.createSetup() def keyRight(self): ConfigListScreen.keyRight(self) self.createSetup() def confirm(self, confirmed): if not confirmed: config.av.videoport.value = self.last_good[0] config.av.videomode[self.last_good[0]].value = self.last_good[1] config.av.videorate[self.last_good[1]].value = self.last_good[2] self.hw.setMode(*self.last_good) else: self.keySave() def grabLastGoodMode(self): port = config.av.videoport.value mode = config.av.videomode[port].value rate = config.av.videorate[mode].value self.last_good = (port, mode, rate) def apply(self): port = config.av.videoport.value mode = config.av.videomode[port].value rate = config.av.videorate[mode].value if (port, mode, rate) != self.last_good: self.hw.setMode(port, mode, rate) from Screens.MessageBox import MessageBox self.session.openWithCallback(self.confirm, MessageBox, _("Is this video mode ok?"), MessageBox.TYPE_YESNO, timeout = 20, default = False) else: self.keySave() # for summary: def changedEntry(self): for x in self.onChangedEntry: x() def getCurrentEntry(self): return self["config"].getCurrent()[0] def getCurrentValue(self): return str(self["config"].getCurrent()[1].getText()) def getCurrentDescription(self): return self["config"].getCurrent() and len(self["config"].getCurrent()) > 2 and self["config"].getCurrent()[2] or "" def createSummary(self): from Screens.Setup import SetupSummary return SetupSummary class VideomodeHotplug: def __init__(self, hw): self.hw = hw def start(self): self.hw.on_hotplug.append(self.hotplug) def stop(self): self.hw.on_hotplug.remove(self.hotplug) def hotplug(self, what): print "hotplug detected on port '%s'" % (what) port = config.av.videoport.value mode = config.av.videomode[port].value rate = config.av.videorate[mode].value if not self.hw.isModeAvailable(port, mode, rate): print "mode %s/%s/%s went away!" % (port, mode, rate) modelist = self.hw.getModeList(port) if not len(modelist): print "sorry, no other mode is available (unplug?). Doing nothing." return mode = modelist[0][0] rate = modelist[0][1] print "setting %s/%s/%s" % (port, mode, rate) self.hw.setMode(port, mode, rate) hotplug = None def startHotplug(): global hotplug, video_hw hotplug = VideomodeHotplug(video_hw) hotplug.start() def stopHotplug(): global hotplug hotplug.stop() def autostart(reason, session = None, **kwargs): if session is not None: global my_global_session my_global_session = session return if reason == 0: startHotplug() elif reason == 1: stopHotplug() def videoSetupMain(session, **kwargs): session.open(VideoSetup, video_hw) def startSetup(menuid): if menuid != "system": return [ ] return [(_("A/V settings"), videoSetupMain, "av_setup", 40)] def VideoWizard(*args, **kwargs): from VideoWizard import VideoWizard return VideoWizard(*args, **kwargs) def Plugins(**kwargs): list = [ # PluginDescriptor(where = [PluginDescriptor.WHERE_SESSIONSTART, PluginDescriptor.WHERE_AUTOSTART], fnc = autostart), PluginDescriptor(name=_("Video setup"), description=_("Advanced video setup"), where = PluginDescriptor.WHERE_MENU, needsRestart = False, fnc=startSetup) ] if config.misc.videowizardenabled.value: list.append(PluginDescriptor(name=_("Video wizard"), where = PluginDescriptor.WHERE_WIZARD, needsRestart = False, fnc=(0, VideoWizard))) return list
gpl-2.0
hakuji/game3
src/constants.py
1
2653
# Copyright 2013 by akuji # # This file is part of game 3. # # game 3 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. # # game 3 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 game 3. If not, see <http://www.gnu.org/licenses/>. import os from pyglet.window import key DEBUG = os.path.exists('../debug') WINDOW_WIDTH = 640 WINDOW_HEIGHT = 480 FIELD_FONT_SIZE = 12 OBJECT_FONT_SIZE = 10 STATS_PANEL_X = 460 STATS_PANEL_Y = 70 STATUS_PANEL_HEIGHT = 65.0 ST_BOUND_X = 480 ST_BOUND_Y = 470 WALL_WIDTH = 10 NORMAL_DIFICULTY = True GAME_NAME = 'GAME 3' OBJECT_FONT_FACE = 'Monospace' INTERVAL = 0.1 VICTORY = 'YOU WIN!' GAME_OVER = 'GAME OVER' ROAM_LIST = [-1, 0, 1] ROAM_RATE = 0.1 HITBOX_GAP = 3 BACKGROUND_COLOR = [0, 0, 0, 0] class Direction(object): NORTH = 'N' EAST = 'E' SOUTH = 'S' WEST = 'W' FADEOUT_STEP = 30 HERO_ID = -1 TEXT_WIDTH = 400 TEXT_HEIGHT = 5 * 20 TEXT_X = 30 TEXT_Y = 0 TEXT_FONT = 'Times' TEXT_SIZE = 12 class Color(object): RED = (255, 0, 0, 255) GREEN = (0, 255, 0, 255) BLUE = (0, 0, 255, 255) BLACK = (0, 0, 0, 255) WHITE = (255, 255, 255, 255) GOLD = (255, 215, 0, 255) UMBER = (99, 81, 71, 255) BURLYWOOD = (222, 184, 135, 255) ARTICHOKE = (143, 151, 121, 255) BATTLESHIPGREY = (132, 132, 130, 255) ARSENIC = (59, 68, 75, 255) BROWNNOSE = (107, 68, 35, 255) ROOM_FLOOR_COLOR = Color.ARSENIC TEXT_COLOR = Color.WHITE HEALTH_BAR_WIDTH = 100 HEALTH_BAR_HEIGHT = 18 class Controls(object): NORTH = key.W EAST = key.D WEST = key.A SOUTH = key.S ATTACK = key.J ACCEPT = key.I SCROLL_UP = key.PAGEUP SCROLL_DOWN = key.PAGEDOWN kss = key.symbol_string MOVE_AROUND_MESSAGE = 'Use the {0} {1} {2} {3} keys to move around'.format( kss(Controls.WEST), kss(Controls.SOUTH), kss(Controls.EAST), kss(Controls.NORTH) ) ATTACK_MESSAGE = 'Use the {0} key to attack creatures'.format( kss(Controls.ATTACK) ) SCROLL_MESSAGE = 'You can press {0} and {1} to scroll through these messages'.format( kss(Controls.SCROLL_UP), kss(Controls.SCROLL_DOWN) ) INTERACT_MESSAGE = 'Some objects and creatures can be interacted with using the\ {0} key'.format( kss(Controls.ACCEPT) )
gpl-3.0
louietsai/python-for-android
python-modules/twisted/twisted/test/test_enterprise.py
61
1151
# Copyright (c) 2001-2008 Twisted Matrix Laboratories. # See LICENSE for details. """ General tests for twisted.enterprise. """ from twisted.trial import unittest from twisted.enterprise import util class QuotingTestCase(unittest.TestCase): def testQuoting(self): for value, typ, expected in [ (12, "integer", "12"), ("foo'd", "text", "'foo''d'"), ("\x00abc\\s\xFF", "bytea", "'\\\\000abc\\\\\\\\s\\377'"), (12, "text", "'12'"), (u"123'456", "text", u"'123''456'") ]: self.assertEquals( self.callDeprecated(util._deprecatedVersion, util.quote, value, typ), expected) def test_safeDeprecation(self): """ L{safe} is deprecated. """ self.callDeprecated(util._deprecatedVersion, util.safe, "foo") def test_getKeyColumnDeprecation(self): """ L{getKeyColumn} is deprecated. """ class Row(object): rowKeyColumns = () self.callDeprecated(util._deprecatedVersion, util.getKeyColumn, Row, "foo")
apache-2.0
veger/ansible
lib/ansible/modules/cloud/vmware/vmware_host_ntp_facts.py
54
4256
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = r''' --- module: vmware_host_ntp_facts short_description: Gathers facts about NTP configuration on an ESXi host description: - This module can be used to gather facts about NTP configurations on an ESXi host. version_added: 2.7 author: - Abhijeet Kasurde (@Akasurde) notes: - Tested on vSphere 6.5 requirements: - python >= 2.6 - PyVmomi options: cluster_name: description: - Name of the cluster. - NTP config facts about each ESXi server will be returned for the given cluster. - If C(esxi_hostname) is not given, this parameter is required. esxi_hostname: description: - ESXi hostname. - NTP config facts about this ESXi server will be returned. - If C(cluster_name) is not given, this parameter is required. extends_documentation_fragment: vmware.documentation ''' EXAMPLES = r''' - name: Gather NTP facts about all ESXi Host in the given Cluster vmware_host_ntp_facts: hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}' cluster_name: cluster_name delegate_to: localhost register: cluster_host_ntp - name: Gather NTP facts about ESXi Host vmware_host_ntp_facts: hostname: '{{ vcenter_hostname }}' username: '{{ vcenter_username }}' password: '{{ vcenter_password }}' esxi_hostname: '{{ esxi_hostname }}' delegate_to: localhost register: host_ntp ''' RETURN = r''' hosts_ntp_facts: description: - dict with hostname as key and dict with NTP facts as value returned: hosts_ntp_facts type: dict sample: { "10.76.33.226": [ { "ntp_servers": [], "time_zone_description": "UTC", "time_zone_gmt_offset": 0, "time_zone_identifier": "UTC", "time_zone_name": "UTC" } ] } ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi class VmwareNtpFactManager(PyVmomi): def __init__(self, module): super(VmwareNtpFactManager, self).__init__(module) cluster_name = self.params.get('cluster_name', None) esxi_host_name = self.params.get('esxi_hostname', None) self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name) def gather_ntp_facts(self): hosts_facts = {} for host in self.hosts: host_ntp_facts = [] host_date_time_manager = host.configManager.dateTimeSystem if host_date_time_manager: host_ntp_facts.append( dict( time_zone_identifier=host_date_time_manager.dateTimeInfo.timeZone.key, time_zone_name=host_date_time_manager.dateTimeInfo.timeZone.name, time_zone_description=host_date_time_manager.dateTimeInfo.timeZone.description, time_zone_gmt_offset=host_date_time_manager.dateTimeInfo.timeZone.gmtOffset, ntp_servers=[ntp_server for ntp_server in host_date_time_manager.dateTimeInfo.ntpConfig.server] ) ) hosts_facts[host.name] = host_ntp_facts return hosts_facts def main(): argument_spec = vmware_argument_spec() argument_spec.update( cluster_name=dict(type='str', required=False), esxi_hostname=dict(type='str', required=False), ) module = AnsibleModule( argument_spec=argument_spec, required_one_of=[ ['cluster_name', 'esxi_hostname'], ], supports_check_mode=True, ) vmware_host_ntp_config = VmwareNtpFactManager(module) module.exit_json(changed=False, hosts_ntp_facts=vmware_host_ntp_config.gather_ntp_facts()) if __name__ == "__main__": main()
gpl-3.0
whdghks913/Mir-kernel
scripts/tracing/draw_functrace.py
14676
3560
#!/usr/bin/python """ Copyright 2008 (c) Frederic Weisbecker <fweisbec@gmail.com> Licensed under the terms of the GNU GPL License version 2 This script parses a trace provided by the function tracer in kernel/trace/trace_functions.c The resulted trace is processed into a tree to produce a more human view of the call stack by drawing textual but hierarchical tree of calls. Only the functions's names and the the call time are provided. Usage: Be sure that you have CONFIG_FUNCTION_TRACER # mount -t debugfs nodev /sys/kernel/debug # echo function > /sys/kernel/debug/tracing/current_tracer $ cat /sys/kernel/debug/tracing/trace_pipe > ~/raw_trace_func Wait some times but not too much, the script is a bit slow. Break the pipe (Ctrl + Z) $ scripts/draw_functrace.py < raw_trace_func > draw_functrace Then you have your drawn trace in draw_functrace """ import sys, re class CallTree: """ This class provides a tree representation of the functions call stack. If a function has no parent in the kernel (interrupt, syscall, kernel thread...) then it is attached to a virtual parent called ROOT. """ ROOT = None def __init__(self, func, time = None, parent = None): self._func = func self._time = time if parent is None: self._parent = CallTree.ROOT else: self._parent = parent self._children = [] def calls(self, func, calltime): """ If a function calls another one, call this method to insert it into the tree at the appropriate place. @return: A reference to the newly created child node. """ child = CallTree(func, calltime, self) self._children.append(child) return child def getParent(self, func): """ Retrieve the last parent of the current node that has the name given by func. If this function is not on a parent, then create it as new child of root @return: A reference to the parent. """ tree = self while tree != CallTree.ROOT and tree._func != func: tree = tree._parent if tree == CallTree.ROOT: child = CallTree.ROOT.calls(func, None) return child return tree def __repr__(self): return self.__toString("", True) def __toString(self, branch, lastChild): if self._time is not None: s = "%s----%s (%s)\n" % (branch, self._func, self._time) else: s = "%s----%s\n" % (branch, self._func) i = 0 if lastChild: branch = branch[:-1] + " " while i < len(self._children): if i != len(self._children) - 1: s += "%s" % self._children[i].__toString(branch +\ " |", False) else: s += "%s" % self._children[i].__toString(branch +\ " |", True) i += 1 return s class BrokenLineException(Exception): """If the last line is not complete because of the pipe breakage, we want to stop the processing and ignore this line. """ pass class CommentLineException(Exception): """ If the line is a comment (as in the beginning of the trace file), just ignore it. """ pass def parseLine(line): line = line.strip() if line.startswith("#"): raise CommentLineException m = re.match("[^]]+?\\] +([0-9.]+): (\\w+) <-(\\w+)", line) if m is None: raise BrokenLineException return (m.group(1), m.group(2), m.group(3)) def main(): CallTree.ROOT = CallTree("Root (Nowhere)", None, None) tree = CallTree.ROOT for line in sys.stdin: try: calltime, callee, caller = parseLine(line) except BrokenLineException: break except CommentLineException: continue tree = tree.getParent(caller) tree = tree.calls(callee, calltime) print CallTree.ROOT if __name__ == "__main__": main()
gpl-2.0
ilya-epifanov/ansible-modules-core
utilities/logic/include_vars.py
112
1428
# -*- mode: python -*- # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- author: "Benno Joy (@bennojoy)" module: include_vars short_description: Load variables from files, dynamically within a task. description: - Loads variables from a YAML file dynamically during task runtime. It can work with conditionals, or use host specific variables to determine the path name to load from. options: free-form: description: - The file name from which variables should be loaded, if called from a role it will look for the file in vars/ subdirectory of the role, otherwise the path would be relative to playbook. An absolute path can also be provided. required: true version_added: "1.4" ''' EXAMPLES = """ # Conditionally decide to load in variables when x is 0, otherwise do not. - include_vars: contingency_plan.yml when: x == 0 # Load a variable file based on the OS type, or a default if not found. - include_vars: "{{ item }}" with_first_found: - "{{ ansible_distribution }}.yml" - "{{ ansible_os_family }}.yml" - "default.yml" """
gpl-3.0
enixdark/10gen-Courses
Mongo-Developer-M101P-Pyramid/Week 4/HW4.3/hw4-3/sessionDAO.py
34
2310
__author__ = 'aje' # # Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # import sys import random import string # The session Data Access Object handles interactions with the sessions collection class SessionDAO: def __init__(self, database): self.db = database self.sessions = database.sessions # will start a new session id by adding a new document to the sessions collection # returns the sessionID or None def start_session(self, username): session_id = self.get_random_str(32) session = {'username': username, '_id': session_id} try: self.sessions.insert(session, safe=True) except: print "Unexpected error on start_session:", sys.exc_info()[0] return None return str(session['_id']) # will send a new user session by deleting from sessions table def end_session(self, session_id): if session_id is None: return self.sessions.remove({'_id': session_id}) return # if there is a valid session, it is returned def get_session(self, session_id): if session_id is None: return None session = self.sessions.find_one({'_id': session_id}) return session # get the username of the current session, or None if the session is not valid def get_username(self, session_id): session = self.get_session(session_id) if session is None: return None else: return session['username'] def get_random_str(self, num_chars): random_string = "" for i in range(num_chars): random_string = random_string + random.choice(string.ascii_letters) return random_string
mit
sugarguo/Flask_Blog
ext_lib/blinker/_utilities.py
144
4457
from weakref import ref from blinker._saferef import BoundMethodWeakref try: callable except NameError: def callable(object): return hasattr(object, '__call__') try: from collections import defaultdict except: class defaultdict(dict): def __init__(self, default_factory=None, *a, **kw): if (default_factory is not None and not hasattr(default_factory, '__call__')): raise TypeError('first argument must be callable') dict.__init__(self, *a, **kw) self.default_factory = default_factory def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return self.__missing__(key) def __missing__(self, key): if self.default_factory is None: raise KeyError(key) self[key] = value = self.default_factory() return value def __reduce__(self): if self.default_factory is None: args = tuple() else: args = self.default_factory, return type(self), args, None, None, self.items() def copy(self): return self.__copy__() def __copy__(self): return type(self)(self.default_factory, self) def __deepcopy__(self, memo): import copy return type(self)(self.default_factory, copy.deepcopy(self.items())) def __repr__(self): return 'defaultdict(%s, %s)' % (self.default_factory, dict.__repr__(self)) try: from contextlib import contextmanager except ImportError: def contextmanager(fn): def oops(*args, **kw): raise RuntimeError("Python 2.5 or above is required to use " "context managers.") oops.__name__ = fn.__name__ return oops class _symbol(object): def __init__(self, name): """Construct a new named symbol.""" self.__name__ = self.name = name def __reduce__(self): return symbol, (self.name,) def __repr__(self): return self.name _symbol.__name__ = 'symbol' class symbol(object): """A constant symbol. >>> symbol('foo') is symbol('foo') True >>> symbol('foo') foo A slight refinement of the MAGICCOOKIE=object() pattern. The primary advantage of symbol() is its repr(). They are also singletons. Repeated calls of symbol('name') will all return the same instance. """ symbols = {} def __new__(cls, name): try: return cls.symbols[name] except KeyError: return cls.symbols.setdefault(name, _symbol(name)) try: text = (str, unicode) except NameError: text = str def hashable_identity(obj): if hasattr(obj, '__func__'): return (id(obj.__func__), id(obj.__self__)) elif hasattr(obj, 'im_func'): return (id(obj.im_func), id(obj.im_self)) elif isinstance(obj, text): return obj else: return id(obj) WeakTypes = (ref, BoundMethodWeakref) class annotatable_weakref(ref): """A weakref.ref that supports custom instance attributes.""" def reference(object, callback=None, **annotations): """Return an annotated weak ref.""" if callable(object): weak = callable_reference(object, callback) else: weak = annotatable_weakref(object, callback) for key, value in annotations.items(): setattr(weak, key, value) return weak def callable_reference(object, callback=None): """Return an annotated weak ref, supporting bound instance methods.""" if hasattr(object, 'im_self') and object.im_self is not None: return BoundMethodWeakref(target=object, on_delete=callback) elif hasattr(object, '__self__') and object.__self__ is not None: return BoundMethodWeakref(target=object, on_delete=callback) return annotatable_weakref(object, callback) class lazy_property(object): """A @property that is only evaluated once.""" def __init__(self, deferred): self._deferred = deferred self.__doc__ = deferred.__doc__ def __get__(self, obj, cls): if obj is None: return self value = self._deferred(obj) setattr(obj, self._deferred.__name__, value) return value
gpl-3.0
sorenk/ansible
test/units/modules/network/f5/test_bigip_configsync_action.py
17
4138
# -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import sys from nose.plugins.skip import SkipTest if sys.version_info < (2, 7): raise SkipTest("F5 Ansible modules require Python >= 2.7") from ansible.compat.tests import unittest from ansible.compat.tests.mock import Mock from ansible.compat.tests.mock import patch from ansible.module_utils.basic import AnsibleModule try: from library.bigip_configsync_actions import Parameters from library.bigip_configsync_actions import ModuleManager from library.bigip_configsync_actions import ArgumentSpec from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.common import iControlUnexpectedHTTPError from test.unit.modules.utils import set_module_args except ImportError: try: from ansible.modules.network.f5.bigip_configsync_actions import Parameters from ansible.modules.network.f5.bigip_configsync_actions import ModuleManager from ansible.modules.network.f5.bigip_configsync_actions import ArgumentSpec from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError from units.modules.utils import set_module_args except ImportError: raise SkipTest("F5 Ansible modules require the f5-sdk Python library") fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_data = {} def load_fixture(name): path = os.path.join(fixture_path, name) if path in fixture_data: return fixture_data[path] with open(path) as f: data = f.read() try: data = json.loads(data) except Exception: pass fixture_data[path] = data return data class TestParameters(unittest.TestCase): def test_module_parameters(self): args = dict( sync_device_to_group=True, sync_group_to_device=True, overwrite_config=True, device_group="foo" ) p = Parameters(params=args) assert p.sync_device_to_group is True assert p.sync_group_to_device is True assert p.overwrite_config is True assert p.device_group == 'foo' def test_module_parameters_yes_no(self): args = dict( sync_device_to_group='yes', sync_group_to_device='no', overwrite_config='yes', device_group="foo" ) p = Parameters(params=args) assert p.sync_device_to_group is True assert p.sync_group_to_device is False assert p.overwrite_config is True assert p.device_group == 'foo' class TestManager(unittest.TestCase): def setUp(self): self.spec = ArgumentSpec() self.patcher1 = patch('time.sleep') self.patcher1.start() def tearDown(self): self.patcher1.stop() def test_update_agent_status_traps(self, *args): set_module_args(dict( sync_device_to_group='yes', device_group="foo", password='passsword', server='localhost', user='admin' )) module = AnsibleModule( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode ) mm = ModuleManager(module=module) # Override methods to force specific logic in the module to happen mm._device_group_exists = Mock(return_value=True) mm._sync_to_group_required = Mock(return_value=False) mm.execute_on_device = Mock(return_value=True) mm.read_current_from_device = Mock(return_value=None) mm._get_status_from_resource = Mock() mm._get_status_from_resource.side_effect = [ 'Changes Pending', 'Awaiting Initial Sync', 'In Sync' ] results = mm.exec_module() assert results['changed'] is True
gpl-3.0
bowang/tensorflow
tensorflow/python/ops/gradients_impl.py
7
38539
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implements the graph generation for computation of gradients.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import contextlib import warnings import numpy as np import six from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.core.framework import attr_value_pb2 from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_grad # pylint: disable=unused-import from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import control_flow_grad # pylint: disable=unused-import from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import functional_ops from tensorflow.python.ops import image_grad # pylint: disable=unused-import from tensorflow.python.ops import linalg_grad # pylint: disable=unused-import from tensorflow.python.ops import linalg_ops # pylint: disable=unused-import from tensorflow.python.ops import logging_ops # pylint: disable=unused-import from tensorflow.python.ops import math_grad # pylint: disable=unused-import from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import spectral_grad # pylint: disable=unused-import from tensorflow.python.ops import tensor_array_ops from tensorflow.python.platform import tf_logging as logging # Warn the user if we convert a sparse representation to dense with at # least this number of elements. _LARGE_SPARSE_NUM_ELEMENTS = 100000000 def _IndexedSlicesToTensor(value, dtype=None, name=None, as_ref=False): """Converts an IndexedSlices object `value` to a Tensor. NOTE(mrry): This function is potentially expensive. Args: value: An ops.IndexedSlices object. dtype: The dtype of the Tensor to be returned. name: Optional name to use for the returned Tensor. as_ref: True if a ref is requested. Returns: A dense Tensor representing the values in the given IndexedSlices. Raises: ValueError: If the IndexedSlices does not have the same dtype. """ _ = as_ref if dtype and not dtype.is_compatible_with(value.dtype): raise ValueError( "Tensor conversion requested dtype %s for IndexedSlices with dtype %s" % (dtype.name, value.dtype.name)) if value.dense_shape is None: raise ValueError( "Tensor conversion requested for IndexedSlices without dense_shape: %s" % str(value)) # TODO(mrry): Consider adding static shape information to # IndexedSlices, to avoid using numpy here. dense_shape_value = tensor_util.constant_value(value.dense_shape) if dense_shape_value is not None: num_elements = np.prod(dense_shape_value) if num_elements >= _LARGE_SPARSE_NUM_ELEMENTS: warnings.warn( "Converting sparse IndexedSlices to a dense Tensor with %d elements. " "This may consume a large amount of memory." % num_elements) else: warnings.warn( "Converting sparse IndexedSlices to a dense Tensor of unknown shape. " "This may consume a large amount of memory.") return math_ops.unsorted_segment_sum( value.values, value.indices, value.dense_shape[0], name=name) ops.register_tensor_conversion_function(ops.IndexedSlices, _IndexedSlicesToTensor) def _MarkReachedOps(from_ops, reached_ops): """Mark all ops reached from "from_ops". Args: from_ops: list of Operations. reached_ops: list of booleans, indexed by operation id. """ queue = collections.deque() queue.extend(from_ops) while queue: op = queue.popleft() if not reached_ops[op._id]: reached_ops[op._id] = True for output in op.outputs: queue.extend(output.consumers()) def _GatherInputs(to_ops, reached_ops): """List all inputs of to_ops that are in reached_ops. Args: to_ops: list of Operations. reached_ops: list of booleans, indexed by operation id. Returns: The list of all inputs of to_ops that are in reached_ops. That list includes all elements of to_ops. """ inputs = [] queue = collections.deque() queue.extend(to_ops) while queue: op = queue.popleft() # We are interested in this op. if reached_ops[op._id]: inputs.append(op) # Clear the boolean so we won't add the inputs again. reached_ops[op._id] = False for inp in op.inputs: queue.append(inp.op) return inputs def _PendingCount(graph, to_ops, from_ops, colocate_gradients_with_ops): """Initialize the pending count for ops between two lists of Operations. 'pending_count[op._id]' indicates the number of backprop inputs to this operation. Args: graph: a Graph. to_ops: list of Operations. from_ops: list of Operations. colocate_gradients_with_ops: Python bool. See docstring of gradients(). Returns: A tuple containing: (1) a list of integers indexed by operation id, indicating the number of backprop inputs to this operation, and (2) a ControlFlowState object which is not None if the ops between from_ops and to_ops contain control flow loops. """ # Mark reachable ops from from_ops. reached_ops = [False] * (graph._last_id + 1) for op in to_ops: reached_ops[op._id] = True _MarkReachedOps(from_ops, reached_ops) # Mark between ops. between_ops = [False] * (graph._last_id + 1) between_op_list = [] queue = collections.deque() queue.extend(to_ops) while queue: op = queue.popleft() # We are interested in this op. if reached_ops[op._id]: between_ops[op._id] = True between_op_list.append(op) # Clear the boolean so we won't add the inputs again. reached_ops[op._id] = False for inp in op.inputs: queue.append(inp.op) # 'loop_state' is None if there are no while loops. loop_state = control_flow_ops.MaybeCreateControlFlowState( between_op_list, between_ops, colocate_gradients_with_ops) # Initialize pending count for between ops. pending_count = [0] * (graph._last_id + 1) for op in between_op_list: for x in op.inputs: if between_ops[x.op._id]: pending_count[x.op._id] += 1 return pending_count, loop_state def _AsList(x): return x if isinstance(x, (list, tuple)) else [x] def _DefaultGradYs(grad_ys, ys, colocate_gradients_with_ops): """Fill in default values for grad_ys. Args: grad_ys: List of gradients, can contain None. ys: List of tensors. colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op. Returns: A list of gradients to use, without None. Raises: ValueError: If sizes of gradients and inputs don't match TypeError: If type of any gradient is not valid for its input. """ if len(grad_ys) != len(ys): raise ValueError("Passed %d grad_ys for %d ys" % (len(grad_ys), len(ys))) grad_ys = ops.convert_n_to_tensor_or_indexed_slices(grad_ys, name="grad_y") for i in xrange(len(grad_ys)): grad_y = grad_ys[i] y = ys[i] if grad_y is None: if y.dtype.is_complex: raise TypeError( "Gradients of complex tensors must set grad_ys (y.dtype = %r)" % y.dtype) with _maybe_colocate_with(y.op, colocate_gradients_with_ops): grad_ys[i] = array_ops.fill( array_ops.shape(y), constant_op.constant( 1, dtype=y.dtype)) continue if y.dtype.is_floating or y.dtype.is_integer: if not grad_y.dtype.is_floating and not grad_y.dtype.is_integer: raise TypeError("Gradient type %s generated for real or " "integer-valued tensor %s with type %s must be " "real or integer" % (dtypes.as_dtype(grad_y.dtype).name, y, dtypes.as_dtype(y.dtype).name)) elif y.dtype.is_complex: if not grad_y.dtype.is_complex: raise TypeError("Gradient type %s generated for complex-valued " "tensor %s with type %s must be real" % (dtypes.as_dtype(grad_y.dtype).name, y, dtypes.as_dtype(y.dtype).name)) else: raise TypeError("Tensor %s with type %s must be numeric " "to obtain a default gradient" % (y, dtypes.as_dtype(y.dtype).name)) return grad_ys def _IsTrainable(tensor): dtype = dtypes.as_dtype(tensor.dtype) return dtype.base_dtype in (dtypes.float16, dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128) def _VerifyGeneratedGradients(grads, op): """Verify that gradients are valid in number and type. Args: grads: List of generated gradients. op: Operation for which the gradients where generated. Raises: ValueError: if sizes of gradients and inputs don't match. TypeError: if type of any gradient is not valid for its input. """ if len(grads) != len(op.inputs): raise ValueError("Num gradients %d generated for op %s do not match num " "inputs %d" % (len(grads), op.node_def, len(op.inputs))) def _StopOps(from_ops, stop_gradient_ops, pending_count): """The set of ops that terminate the gradient computation. This computes the frontier of the forward graph *before* which backprop should stop. Operations in the returned set will not be differentiated. This set is defined as the subset of `from_ops` containing ops that have no predecessor in `from_ops`. `pending_count` is the result of `_PendingCount(g, xs, from_ops)`. An 'op' has predecessors in `from_ops` iff pending_count[op._id] > 0. In addition, none of `stop_gradient_ops` will be differentiated. Args: from_ops: list of Operations. stop_gradient_ops: list of Operations never to backprop through. pending_count: List of integers, indexed by operation id. Returns: The set of operations. """ stop_ops = set() for op in from_ops: is_stop_op = True for inp in op.inputs: if pending_count[inp.op._id] > 0: is_stop_op = False break if is_stop_op: stop_ops.add(op._id) stop_ops.update(op._id for op in stop_gradient_ops) # pylint: disable=protected-access return stop_ops @contextlib.contextmanager def _maybe_colocate_with(op, colocate_gradients_with_ops): """Context to colocate with `op` if `colocate_gradients_with_ops`.""" if colocate_gradients_with_ops: with ops.colocate_with(op): yield else: yield def _SymGrad(op, out_grads): """Backprop through a function call node op given its outputs' gradients.""" f_in = [x for x in op.inputs] + out_grads f_types = [x.dtype for x in op.inputs] f = attr_value_pb2.NameAttrList() f.name = op.type for k in op.node_def.attr: f.attr[k].CopyFrom(op.node_def.attr[k]) # pylint: disable=protected-access in_grads = functional_ops._symbolic_gradient(input=f_in, Tout=f_types, f=f) # pylint: enable=protected-access return in_grads def _MaybeCompile(scope, op, func, grad_fn): """Compile the calculation in grad_fn if op was marked as compiled.""" scope = scope.rstrip("/").replace("/", "_") if func is not None: xla_compile = func.definition.attr["_XlaCompile"].b xla_separate_compiled_gradients = func.definition.attr[ "_XlaSeparateCompiledGradients"].b xla_scope = func.definition.attr["_XlaScope"].s.decode() else: try: xla_compile = op.get_attr("_XlaCompile") xla_separate_compiled_gradients = op.get_attr( "_XlaSeparateCompiledGradients") xla_scope = op.get_attr("_XlaScope").decode() except ValueError: return grad_fn() # Exit early if not xla_compile: return grad_fn() # Exit early # If the gradients are supposed to be compiled separately, we give them a # _XlaScope name that is based on the name_scope of the gradients. Otherwise # they just inherit the existing _XlaScope name, which lets them be merged # together with the non-gradient computation. if xla_separate_compiled_gradients: xla_grad_scope = "%s_grad_%s" % (xla_scope, scope) else: xla_grad_scope = xla_scope attrs = { "_XlaCompile": attr_value_pb2.AttrValue(b=xla_compile), "_XlaScope": attr_value_pb2.AttrValue(s=xla_grad_scope.encode()) } with ops.get_default_graph()._attr_scope(attrs): # pylint: disable=protected-access return grad_fn() def gradients(ys, xs, grad_ys=None, name="gradients", colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None, stop_gradients=None): """Constructs symbolic derivatives of sum of `ys` w.r.t. x in `xs`. `ys` and `xs` are each a `Tensor` or a list of tensors. `grad_ys` is a list of `Tensor`, holding the gradients received by the `ys`. The list must be the same length as `ys`. `gradients()` adds ops to the graph to output the derivatives of `ys` with respect to `xs`. It returns a list of `Tensor` of length `len(xs)` where each tensor is the `sum(dy/dx)` for y in `ys`. `grad_ys` is a list of tensors of the same length as `ys` that holds the initial gradients for each y in `ys`. When `grad_ys` is None, we fill in a tensor of '1's of the shape of y for each y in `ys`. A user can provide their own initial `grad_ys` to compute the derivatives using a different initial gradient for each y (e.g., if one wanted to weight the gradient differently for each value in each y). `stop_gradients` is a `Tensor` or a list of tensors to be considered constant with respect to all `xs`. These tensors will not be backpropagated through, as though they had been explicitly disconnected using `stop_gradient`. Among other things, this allows computation of partial derivatives as opposed to total derivatives. For example: a = tf.constant(0.) b = 2 * a g = tf.gradients(a + b, [a, b], stop_gradients=[a, b]) Here the partial derivatives `g` evaluate to `[1.0, 1.0]`, compared to the total derivatives `tf.gradients(a + b, [a, b])`, which take into account the influence of `a` on `b` and evaluate to `[3.0, 1.0]`. Note that the above is equivalent to: a = tf.stop_gradient(tf.constant(0.)) b = tf.stop_gradient(2 * a) g = tf.gradients(a + b, [a, b]) `stop_gradients` provides a way of stopping gradient after the graph has already been constructed, as compared to `tf.stop_gradient` which is used during graph construction. When the two approaches are combined, backpropagation stops at both `tf.stop_gradient` nodes and nodes in `stop_gradients`, whichever is encountered first. Args: ys: A `Tensor` or list of tensors to be differentiated. xs: A `Tensor` or list of tensors to be used for differentiation. grad_ys: Optional. A `Tensor` or list of tensors the same size as `ys` and holding the gradients computed for each y in `ys`. name: Optional name to use for grouping all the gradient ops together. defaults to 'gradients'. colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op. gate_gradients: If True, add a tuple around the gradients returned for an operations. This avoids some race conditions. aggregation_method: Specifies the method used to combine gradient terms. Accepted values are constants defined in the class `AggregationMethod`. stop_gradients: Optional. A `Tensor` or list of tensors not to differentiate through. Returns: A list of `sum(dy/dx)` for each x in `xs`. Raises: LookupError: if one of the operations between `x` and `y` does not have a registered gradient function. ValueError: if the arguments are invalid. RuntimeError: if called in Eager mode. """ if context.in_eager_mode(): raise RuntimeError("tf.gradients not supported in EAGER mode. Use " "functions in tf.contrib.eager.backprop instead.") ys = _AsList(ys) xs = _AsList(xs) stop_gradients = [] if stop_gradients is None else _AsList(stop_gradients) if grad_ys is None: grad_ys = [None] * len(ys) else: grad_ys = _AsList(grad_ys) with ops.name_scope( name, "gradients", list(ys) + list(xs) + list(stop_gradients) + list(grad_ys)) as grad_scope: ys = ops.convert_n_to_tensor_or_indexed_slices(ys, name="y") xs = [x.handle if isinstance(x, resource_variable_ops.ResourceVariable) else x for x in xs] xs = ops.internal_convert_n_to_tensor_or_indexed_slices(xs, name="x", as_ref=True) grad_ys = _DefaultGradYs(grad_ys, ys, colocate_gradients_with_ops) # The approach we take here is as follows: Create a list of all ops in the # subgraph between the ys and xs. Visit these ops in reverse order of ids # to ensure that when we visit an op the gradients w.r.t its outputs have # been collected. Then aggregate these gradients if needed, call the op's # gradient function, and add the generated gradients to the gradients for # its input. # Initialize the pending count for ops in the connected subgraph from ys # to the xs. if len(ys) > 1: ys = [array_ops.identity(y) if y.consumers() else y for y in ys] to_ops = [t.op for t in ys] from_ops = [t.op for t in xs] stop_gradient_ops = [t.op for t in stop_gradients] pending_count, loop_state = _PendingCount(ops.get_default_graph(), to_ops, from_ops, colocate_gradients_with_ops) # Iterate over the collected ops. # # grads: op => list of gradients received on each output endpoint of the # op. The gradients for each endpoint are initially collected as a list. # When it is time to call the op's gradient function, for each endpoint we # aggregate the list of received gradients into a Add() Operation if there # is more than one. grads = {} # Add the initial gradients for the ys. for y, grad_y in zip(ys, grad_ys): _SetGrad(grads, y, grad_y) # Initialize queue with to_ops. queue = collections.deque() # Add the ops in 'to_ops' into the queue. to_ops_set = set() for op in to_ops: # 'ready' handles the case where one output gradient relies on # another output's gradient. # pylint: disable=protected-access ready = (pending_count[op._id] == 0) if ready and op._id not in to_ops_set: to_ops_set.add(op._id) queue.append(op) # pylint: enable=protected-access if loop_state: loop_exits = loop_state.ProcessUnusedLoopExits(pending_count, to_ops_set) for y in loop_exits: if _IsTrainable(y): _SetGrad(grads, y, loop_state.ZerosLikeForExit(y)) queue.append(y.op) stop_ops = _StopOps(from_ops, stop_gradient_ops, pending_count) while queue: # generate gradient subgraph for op. op = queue.popleft() with _maybe_colocate_with(op, colocate_gradients_with_ops): if loop_state: loop_state.EnterGradWhileContext(op, before=True) out_grads = _AggregatedGrads(grads, op, loop_state, aggregation_method) if loop_state: loop_state.ExitGradWhileContext(op, before=True) grad_fn = None # pylint: disable=protected-access func_call = None is_func_call = ops.get_default_graph()._is_function(op.type) has_out_grads = any(isinstance(g, ops.Tensor) or g for g in out_grads) if has_out_grads and (op._id not in stop_ops): if is_func_call: func_call = ops.get_default_graph()._get_function(op.type) grad_fn = func_call.python_grad_func # pylint: enable=protected-access else: # A grad_fn must be defined, either as a function or as None # for ops that do not have gradients. try: grad_fn = ops.get_gradient_function(op) except LookupError: raise LookupError( "No gradient defined for operation '%s' (op type: %s)" % (op.name, op.type)) if loop_state: loop_state.EnterGradWhileContext(op, before=False) if (grad_fn or is_func_call) and has_out_grads: # NOTE: If _AggregatedGrads didn't compute a value for the i'th # output, it means that the cost does not depend on output[i], # therefore dC/doutput[i] is 0. for i, out_grad in enumerate(out_grads): if (not isinstance(out_grad, ops.Tensor) and not out_grad) and _IsTrainable(op.outputs[i]): # Only floating-point outputs get a zero gradient. Gradient # functions should ignore the gradient for other outputs. # TODO(apassos) gradients of resource handles might be an # issue here because of zeros. if loop_state: out_grads[i] = loop_state.ZerosLike(op, i) else: out_grads[i] = control_flow_ops.ZerosLikeOutsideLoop(op, i) with ops.name_scope(op.name + "_grad"): # pylint: disable=protected-access with ops.get_default_graph()._original_op(op): # pylint: enable=protected-access if grad_fn: # If grad_fn was found, do not use SymbolicGradient even for # functions. in_grads = _MaybeCompile( grad_scope, op, func_call, lambda: grad_fn(op, *out_grads)) else: # For function call ops, we add a 'SymbolicGradient' # node to the graph to compute gradients. in_grads = _MaybeCompile( grad_scope, op, func_call, lambda: _SymGrad(op, out_grads)) in_grads = _AsList(in_grads) _VerifyGeneratedGradients(in_grads, op) if gate_gradients and len( [x for x in in_grads if x is not None]) > 1: in_grads = control_flow_ops.tuple(in_grads) _LogOpGradients(op, out_grads, in_grads) else: # If no grad_fn is defined or none of out_grads is available, # just propagate a list of None backwards. in_grads = [None] * len(op.inputs) for t_in, in_grad in zip(op.inputs, in_grads): if in_grad is not None: if (isinstance(in_grad, ops.Tensor) and t_in.dtype != dtypes.resource): in_grad.set_shape(t_in.get_shape()) _SetGrad(grads, t_in, in_grad) if loop_state: loop_state.ExitGradWhileContext(op, before=False) # Update pending count for the inputs of op and enqueue ready ops. _UpdatePendingAndEnqueueReady(grads, op, queue, pending_count, loop_state) if loop_state: loop_state.PostProcessing() return [_GetGrad(grads, x) for x in xs] def _HasAnyNotNoneGrads(grads, op): """Return true iff op has real gradient.""" out_grads = _GetGrads(grads, op) for out_grad in out_grads: if isinstance(out_grad, (ops.Tensor, ops.IndexedSlices)): return True if out_grad and isinstance(out_grad, collections.Sequence): if any([g is not None for g in out_grad]): return True return False def _UpdatePendingAndEnqueueReady(grads, op, queue, pending_count, loop_state): """Update pending count for the inputs of op and enqueue ready ops.""" for x in op.inputs: # pylint: disable=protected-access pending_count[x.op._id] -= 1 ready = (pending_count[x.op._id] == 0) if loop_state and not ready: ready = (pending_count[x.op._id] > 0 and control_flow_ops.IsLoopSwitch(x.op)) # pylint: enable=protected-access if ready: if control_flow_ops.IsLoopExit(x.op): # if x is an exit without real gradient, defer processing them. grad_state = loop_state.GetGradState(x.op, before=False) grad_state.deferred_exits.append(x) grad_state.pending_exits_count -= 1 if grad_state.pending_exits_count == 0: # We now have all the exits so process them. has_real_grad = False for y in grad_state.deferred_exits: if _HasAnyNotNoneGrads(grads, y.op): has_real_grad = True queue.append(y.op) else: grad_state.unused_exits.append(y) if has_real_grad: # For an unused exit, if it has floating-point outputs, backprop # a zero gradient. Otherwise, just ignore it. for y in grad_state.unused_exits: if _IsTrainable(y): _SetGrad(grads, y, loop_state.ZerosLikeForExit(y)) queue.append(y.op) else: # All exits are "unused" so use None as gradient. for y in grad_state.unused_exits: queue.append(y.op) else: queue.append(x.op) def _SetGrad(grads, t, grad): """Sets gradient "grad" in "grads" for tensor "t".""" op = t.op op_grads = grads.get(op) if not op_grads: op_grads = [[] for _ in xrange(len(op.outputs))] grads[op] = op_grads t_grads = op_grads[t.value_index] if isinstance(t_grads, list): t_grads.append(grad) else: assert control_flow_ops.IsLoopSwitch(op) op_grads[t.value_index] = grad def _GetGrad(grads, t): """Gets gradient for tensor "t".""" op = t.op op_grads = grads.get(op) if not op_grads: return None t_grad = op_grads[t.value_index] assert not isinstance(t_grad, list), ( "gradients list should have been aggregated by now.") return t_grad def _GetGrads(grads, op): """Gets all gradients for op.""" if op in grads: return grads[op] else: return [[] for _ in xrange(len(op.outputs))] def _HandleNestedIndexedSlices(grad): assert isinstance(grad, ops.IndexedSlices) if isinstance(grad.values, ops.Tensor): return grad else: assert isinstance(grad.values, ops.IndexedSlices) g = _HandleNestedIndexedSlices(grad.values) return ops.IndexedSlices(g.values, array_ops.gather(grad.indices, g.indices), g.dense_shape) def _AccumulatorShape(inputs): shape = tensor_shape.unknown_shape() for i in inputs: if isinstance(i, ops.Tensor): shape = shape.merge_with(i.get_shape()) return shape def _LogOpGradients(op, out_grads, in_grads): """Log the in and out grads of an op.""" logging.vlog(1, "Gradient for '" + op.name + "'") def _FilterGrad(x): if x is None: return False if isinstance(x, (list, tuple)): return bool(x) else: return True logging.vlog(1, " in --> %s", ", ".join([x.name for x in out_grads if _FilterGrad(x)])) logging.vlog(1, " out --> %s", ", ".join([x.name for x in in_grads if _FilterGrad(x)])) def _MultiDeviceAddN(tensor_list): """Adds tensors from potentially multiple devices.""" # Basic function structure comes from control_flow_ops.group(). # Sort tensors according to their devices. tensors_on_device = collections.defaultdict(lambda: []) for tensor in tensor_list: tensors_on_device[tensor.device].append(tensor) # For each device, add the tensors on that device first. # Then gather the partial sums from multiple devices. # TODO(sjhwang): Create hierarchical aggregation tree as pbar's suggestion. # E.g., aggregate per GPU, then per task, and so on. summands = [] def DeviceKey(dev): return "" if dev is None else dev for dev in sorted(six.iterkeys(tensors_on_device), key=DeviceKey): tensors = tensors_on_device[dev] with ops.colocate_with(tensors[0].op, ignore_existing=True): summands.append(math_ops.add_n(tensors)) return math_ops.add_n(summands) class AggregationMethod(object): """A class listing aggregation methods used to combine gradients. Computing partial derivatives can require aggregating gradient contributions. This class lists the various methods that can be used to combine gradients in the graph: * `ADD_N`: All of the gradient terms are summed as part of one operation using the "AddN" op. It has the property that all gradients must be ready before any aggregation is performed. * `DEFAULT`: The system-chosen default aggregation method. """ ADD_N = 0 DEFAULT = ADD_N # The following are experimental and may not be supported in future releases. EXPERIMENTAL_TREE = 1 EXPERIMENTAL_ACCUMULATE_N = 2 def _AggregatedGrads(grads, op, loop_state, aggregation_method=None): """Get the aggregated gradients for op. Args: grads: The map of memoized gradients. op: The op to get gradients for. loop_state: An object for maintaining the state of the while loops in the graph. It is of type ControlFlowState. None if the graph contains no while loops. aggregation_method: Specifies the method used to combine gradient terms. Accepted values are constants defined in the class `AggregationMethod`. Returns: A list of gradients, one per each output of `op`. If the gradients for a particular output is a list, this function aggregates it before returning. Raises: TypeError: if the incoming grads are not Tensors or IndexedSlices. ValueError: if the arguments are invalid. """ if aggregation_method is None: aggregation_method = AggregationMethod.DEFAULT if aggregation_method not in [ AggregationMethod.ADD_N, AggregationMethod.EXPERIMENTAL_TREE, AggregationMethod.EXPERIMENTAL_ACCUMULATE_N ]: raise ValueError("Invalid aggregation_method specified %s." % aggregation_method) out_grads = _GetGrads(grads, op) for i, out_grad in enumerate(out_grads): if loop_state: if isinstance(out_grad, (ops.Tensor, ops.IndexedSlices)): assert control_flow_ops.IsLoopSwitch(op) continue # Grads have to be Tensors or IndexedSlices if (isinstance(out_grad, collections.Sequence) and not all([ isinstance(g, (ops.Tensor, ops.IndexedSlices)) for g in out_grad if g is not None ])): raise TypeError("gradients have to be either all Tensors " "or all IndexedSlices") # Aggregate multiple gradients, and convert [] to None. if out_grad: if len(out_grad) < 2: used = "nop" out_grads[i] = out_grad[0] elif all([isinstance(g, ops.Tensor) for g in out_grad if g is not None]): tensor_shape = _AccumulatorShape(out_grad) if (aggregation_method == AggregationMethod.EXPERIMENTAL_ACCUMULATE_N and len(out_grad) > 2 and tensor_shape.is_fully_defined()): # The benefit of using AccumulateN is that its inputs can be combined # in any order and this can allow the expression to be evaluated with # a smaller memory footprint. When used with gpu_allocator_retry, # it is possible to compute a sum of terms which are much larger than # total GPU memory. # AccumulateN can currently only be used if we know the shape for # an accumulator variable. If this is not known, or if we only have # 2 grads then we fall through to the "tree" case below. used = "accumulate_n" out_grads[i] = math_ops.accumulate_n(out_grad) elif aggregation_method in [ AggregationMethod.EXPERIMENTAL_TREE, AggregationMethod.EXPERIMENTAL_ACCUMULATE_N ]: # Aggregate all gradients by doing pairwise sums: this may # reduce performance, but it can improve memory because the # gradients can be released earlier. # # TODO(vrv): Consider replacing this with a version of # tf.AddN() that eagerly frees its inputs as soon as they are # ready, so the order of this tree does not become a problem. used = "tree" with ops.name_scope(op.name + "_gradient_sum"): running_sum = out_grad[0] for grad in out_grad[1:]: running_sum = math_ops.add_n([running_sum, grad]) out_grads[i] = running_sum else: used = "add_n" out_grads[i] = _MultiDeviceAddN(out_grad) logging.vlog(2, " _AggregatedGrads %d x %s using %s", len(out_grad), tensor_shape, used) else: out_grad = math_ops._as_indexed_slices_list( [g for g in out_grad if g is not None]) out_grad = [_HandleNestedIndexedSlices(x) for x in out_grad] # Form IndexedSlices out of the concatenated values and # indices. out_grads[i] = ops.IndexedSlices( array_ops.concat([x.values for x in out_grad], 0), array_ops.concat([x.indices for x in out_grad], 0), out_grad[0].dense_shape) else: # not out_grad # out_grads[i] is [], thus its aggregation is simply None. out_grads[i] = None return out_grads # TODO(vrv): Make this available when we want to make it public. def _hessian_vector_product(ys, xs, v): """Multiply the Hessian of `ys` wrt `xs` by `v`. This is an efficient construction that uses a backprop-like approach to compute the product between the Hessian and another vector. The Hessian is usually too large to be explicitly computed or even represented, but this method allows us to at least multiply by it for the same big-O cost as backprop. Implicit Hessian-vector products are the main practical, scalable way of using second derivatives with neural networks. They allow us to do things like construct Krylov subspaces and approximate conjugate gradient descent. Example: if `y` = 1/2 `x`^T A `x`, then `hessian_vector_product(y, x, v)` will return an expression that evaluates to the same values as (A + A.T) `v`. Args: ys: A scalar value, or a tensor or list of tensors to be summed to yield a scalar. xs: A list of tensors that we should construct the Hessian over. v: A list of tensors, with the same shapes as xs, that we want to multiply by the Hessian. Returns: A list of tensors (or if the list would be length 1, a single tensor) containing the product between the Hessian and `v`. Raises: ValueError: `xs` and `v` have different length. """ # Validate the input length = len(xs) if len(v) != length: raise ValueError("xs and v must have the same length.") # First backprop grads = gradients(ys, xs) assert len(grads) == length elemwise_products = [ math_ops.multiply(grad_elem, array_ops.stop_gradient(v_elem)) for grad_elem, v_elem in zip(grads, v) if grad_elem is not None ] # Second backprop return gradients(elemwise_products, xs) def hessians(ys, xs, name="hessians", colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None): """Constructs the Hessian of sum of `ys` with respect to `x` in `xs`. `hessians()` adds ops to the graph to output the Hessian matrix of `ys` with respect to `xs`. It returns a list of `Tensor` of length `len(xs)` where each tensor is the Hessian of `sum(ys)`. This function currently only supports evaluating the Hessian with respect to (a list of) one- dimensional tensors. The Hessian is a matrix of second-order partial derivatives of a scalar tensor (see https://en.wikipedia.org/wiki/Hessian_matrix for more details). Args: ys: A `Tensor` or list of tensors to be differentiated. xs: A `Tensor` or list of tensors to be used for differentiation. name: Optional name to use for grouping all the gradient ops together. defaults to 'hessians'. colocate_gradients_with_ops: See `gradients()` documentation for details. gate_gradients: See `gradients()` documentation for details. aggregation_method: See `gradients()` documentation for details. Returns: A list of Hessian matrices of `sum(ys)` for each `x` in `xs`. Raises: LookupError: if one of the operations between `xs` and `ys` does not have a registered gradient function. """ xs = _AsList(xs) kwargs = { 'colocate_gradients_with_ops': colocate_gradients_with_ops, 'gate_gradients': gate_gradients, 'aggregation_method': aggregation_method } # Compute first-order derivatives and iterate for each x in xs. hessians = [] _gradients = gradients(ys, xs, **kwargs) for i, _gradient, x in zip(range(len(xs)), _gradients, xs): # Ensure that x is a vector. check_rank = check_ops.assert_rank( x, 1, message='Cannot compute Hessian because element %d of `xs` does ' 'not have rank one.' % i ) with ops.control_dependencies([check_rank]): # Declare an iterator and tensor array loop variables for the gradients. n = array_ops.size(x) loop_vars = [ array_ops.constant(0, dtypes.int32), tensor_array_ops.TensorArray(x.dtype, n) ] # Iterate over all elements of the gradient and compute second order # derivatives. _, hessian = control_flow_ops.while_loop( lambda j, _: j < n, lambda j, result: (j + 1, result.write(j, gradients(_gradient[j], x)[0])), loop_vars ) hessians.append(hessian.stack()) return hessians
apache-2.0
brentp/vcfanno
scripts/paper/chunk-gap-plot.py
2
2020
import sys import re import numpy as np from collections import defaultdict from matplotlib import pyplot as plt import seaborn as sns sns.set_style("white") colors = sns.set_palette('Set1', 8) colors = sns.color_palette('Set1', 3) f, axes = plt.subplots(1, figsize=(4, 2)) axes = (axes,) # run as python chunk-gap-plot.py 1kg.times-tails.fmt.txt exac.times-tails.txt for i, f in enumerate(sys.argv[1:3]): if i == 0: assert "1kg" in f.lower() else: assert "exac" in f.lower() groups = defaultdict(list) for line in open(f): gap, chunk, procs, info = re.split("\s+", line, 3) if not int(chunk) in (1000, 10000, 100000): continue seconds = re.search("in (.+) seconds", info).groups(0)[0] if gap == '100' or chunk == '100': continue if int(procs) != 4: continue groups[(int(gap), int(chunk))].append(float(seconds)) bychunk = defaultdict(list) for gap, chunk in groups: #if chunk != 5000: continue m = np.mean(groups[(gap, chunk)]) bychunk[chunk].append((gap, m)) label = "ExAC" if i == 1 else "1KG" marker = "o" if label == "ExAC" else "s" for j, (chunk, vals) in enumerate(sorted(bychunk.items())): vals.sort() xs, ys = zip(*vals) plabel = "%d : %s" % (chunk, label) if i == 1: plabel = label axes[0].plot(xs, ys, color=colors[j], ls="--" if label == "ExAC" else "-", label=plabel) #, marker=marker) if i == 0: axes[0].set_xlabel("Gap size") axes[0].set_ylabel("Time (seconds)") sns.despine() plt.legend(ncol=2, markerfirst=False, title="Chunk size", loc=(axes[0].get_position().x1-0.45, axes[0].get_position().y1 - 0.085)) ax = plt.gca() for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(7) for item in ax.get_legend().get_texts(): item.set_fontsize(5) plt.savefig('figure-5.pdf') plt.show()
mit
torbjoernk/easybuild-framework
easybuild/toolchains/linalg/flame.py
9
1496
## # Copyright 2012-2015 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (http://www.herculesstichting.be/in_English) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # http://github.com/hpcugent/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ Support for FLAME as toolchain linear algebra library. @author: Stijn De Weirdt (Ghent University) @author: Kenneth Hoste (Ghent University) """ from easybuild.toolchains.linalg.lapack import Lapack class Flame(Lapack): """Less trivial module, provides FLAME support.""" LAPACK_MODULE_NAME = ['FLAME'] + Lapack.LAPACK_MODULE_NAME # no super() LAPACK_LIB = ['lapack2flame', 'flame'] + Lapack.LAPACK_LIB # no super()
gpl-2.0
TribeMedia/synapse
scripts-dev/tail-synapse.py
2
1711
import requests import collections import sys import time import json Entry = collections.namedtuple("Entry", "name position rows") ROW_TYPES = {} def row_type_for_columns(name, column_names): column_names = tuple(column_names) row_type = ROW_TYPES.get((name, column_names)) if row_type is None: row_type = collections.namedtuple(name, column_names) ROW_TYPES[(name, column_names)] = row_type return row_type def parse_response(content): streams = json.loads(content) result = {} for name, value in streams.items(): row_type = row_type_for_columns(name, value["field_names"]) position = value["position"] rows = [row_type(*row) for row in value["rows"]] result[name] = Entry(name, position, rows) return result def replicate(server, streams): return parse_response(requests.get( server + "/_synapse/replication", verify=False, params=streams ).content) def main(): server = sys.argv[1] streams = None while not streams: try: streams = { row.name: row.position for row in replicate(server, {"streams":"-1"})["streams"].rows } except requests.exceptions.ConnectionError as e: time.sleep(0.1) while True: try: results = replicate(server, streams) except: sys.stdout.write("connection_lost("+ repr(streams) + ")\n") break for update in results.values(): for row in update.rows: sys.stdout.write(repr(row) + "\n") streams[update.name] = update.position if __name__=='__main__': main()
apache-2.0
stimpsonsg/moose
docs/tests/objects/test_object_syntax.py
4
2999
import os import unittest from MooseDocs.testing import MarkdownTestCase class TestMooseObjectSyntax(MarkdownTestCase): """ Test commands in MooseObjectSyntax extension. """ def testDescription(self): md = '!description /Adaptivity/Markers/BoxMarker' self.assertConvert('test_description.html', md) def testDescriptionOptions(self): md = '!description /Adaptivity/Markers/BoxMarker float=right width=42%' self.assertConvert('test_description_options.html', md) def testDescriptionError(self): md = '!description /Not/A/Real/Object' self.assertConvert('test_description_error.html', md) def testParameters(self): md = '!parameters /Adaptivity/Markers/BoxMarker' html = self.convert(md) self.assertIn('<h2 id="input-parameters">Input Parameters</h2>', html) self.assertIn('<h3 id="required-parameters">Required Parameters</h3>', html) self.assertIn('<div class="moose-parameter-description">How to mark elements outside the box.</div>', html) self.assertIn('<div class="moose-parameter-default">Default: None</div>', html) self.assertIn('<div class="moose-parameter-type">Type: <code>MooseEnum</code></div>', html) self.assertIn('<h3 id="advanced-parameters">Advanced Parameters</h3>', html) self.assertIn('<div class="moose-parameter-description">Adds user-defined labels for accessing object parameters via control logic.</div>', html) def testParametersOptions(self): md = '!parameters /Kernels/Diffusion float=right width=42%' html = self.convert(md) self.assertIn('<div style="float:right;width:42%;">', html) def testInputFiles(self): md = '!inputfiles /Adaptivity/Markers/BoxMarker' html = self.convert(md) self.assertIn('<div class="section scrollspy" id="#input-files" style="">', html) self.assertIn('<h2 id="input-files">Input Files</h2>', html) self.assertIn('<h3 id="tests">Tests</h3>', html) self.assertIn('<ul style="max-height:350px;overflow-y:Scroll">', html) self.assertIn('<li><a href="https://github.com/idaholab/moose/blob/master/test/tests/adaptivity/initial_adapt/initial_adapt.i">test/tests/adaptivity/initial_adapt/initial_adapt.i</a></li>', html) def testChildObjects(self): md = '!childobjects /Kernels/Diffusion' html = self.convert(md) self.assertIn('<div class="section scrollspy" id="#child-objects" style="">', html) self.assertIn('<h2 id="child-objects">Child Objects</h2>', html) self.assertIn('<h3 id="tutorials">Tutorials</h3>', html) self.assertIn('<ul style="max-height:350px;overflow-y:Scroll">', html) self.assertIn('<li><a href="https://github.com/idaholab/moose/blob/master/tutorials/darcy_thermo_mech/step02_darcy_pressure/include/kernels/DarcyPressure.h">tutorials/darcy_thermo_mech/step02_darcy_pressure/include/kernels/DarcyPressure.h</a></li>', html)
lgpl-2.1
trabacus-softapps/openerp-8.0-cc
openerp/addons/mass_mailing/wizard/__init__.py
3
1053
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013-today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ############################################################################## import mail_compose_message import mail_mass_mailing_create_segment
agpl-3.0
Dunkas12/BeepBoopBot
lib/youtube_dl/extractor/pokemon.py
51
2317
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( extract_attributes, int_or_none, ) class PokemonIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?pokemon\.com/[a-z]{2}(?:.*?play=(?P<id>[a-z0-9]{32})|/[^/]+/\d+_\d+-(?P<display_id>[^/?#]+))' _TESTS = [{ 'url': 'http://www.pokemon.com/us/pokemon-episodes/19_01-from-a-to-z/?play=true', 'md5': '9fb209ae3a569aac25de0f5afc4ee08f', 'info_dict': { 'id': 'd0436c00c3ce4071ac6cee8130ac54a1', 'ext': 'mp4', 'title': 'From A to Z!', 'description': 'Bonnie makes a new friend, Ash runs into an old friend, and a terrifying premonition begins to unfold!', 'timestamp': 1460478136, 'upload_date': '20160412', }, 'add_id': ['LimelightMedia'] }, { 'url': 'http://www.pokemon.com/uk/pokemon-episodes/?play=2e8b5c761f1d4a9286165d7748c1ece2', 'only_matching': True, }, { 'url': 'http://www.pokemon.com/fr/episodes-pokemon/18_09-un-hiver-inattendu/', 'only_matching': True, }, { 'url': 'http://www.pokemon.com/de/pokemon-folgen/01_20-bye-bye-smettbo/', 'only_matching': True, }] def _real_extract(self, url): video_id, display_id = re.match(self._VALID_URL, url).groups() webpage = self._download_webpage(url, video_id or display_id) video_data = extract_attributes(self._search_regex( r'(<[^>]+data-video-id="%s"[^>]*>)' % (video_id if video_id else '[a-z0-9]{32}'), webpage, 'video data element')) video_id = video_data['data-video-id'] title = video_data['data-video-title'] return { '_type': 'url_transparent', 'id': video_id, 'url': 'limelight:media:%s' % video_id, 'title': title, 'description': video_data.get('data-video-summary'), 'thumbnail': video_data.get('data-video-poster'), 'series': 'Pokémon', 'season_number': int_or_none(video_data.get('data-video-season')), 'episode': title, 'episode_number': int_or_none(video_data.get('data-video-episode')), 'ie_key': 'LimelightMedia', }
gpl-3.0
izgzhen/servo
tests/wpt/web-platform-tests/tools/pytest/_pytest/resultlog.py
208
3536
""" log machine-parseable test session result information in a plain text file. """ import py import os def pytest_addoption(parser): group = parser.getgroup("terminal reporting", "resultlog plugin options") group.addoption('--resultlog', '--result-log', action="store", metavar="path", default=None, help="path for machine-readable result log.") def pytest_configure(config): resultlog = config.option.resultlog # prevent opening resultlog on slave nodes (xdist) if resultlog and not hasattr(config, 'slaveinput'): dirname = os.path.dirname(os.path.abspath(resultlog)) if not os.path.isdir(dirname): os.makedirs(dirname) logfile = open(resultlog, 'w', 1) # line buffered config._resultlog = ResultLog(config, logfile) config.pluginmanager.register(config._resultlog) def pytest_unconfigure(config): resultlog = getattr(config, '_resultlog', None) if resultlog: resultlog.logfile.close() del config._resultlog config.pluginmanager.unregister(resultlog) def generic_path(item): chain = item.listchain() gpath = [chain[0].name] fspath = chain[0].fspath fspart = False for node in chain[1:]: newfspath = node.fspath if newfspath == fspath: if fspart: gpath.append(':') fspart = False else: gpath.append('.') else: gpath.append('/') fspart = True name = node.name if name[0] in '([': gpath.pop() gpath.append(name) fspath = newfspath return ''.join(gpath) class ResultLog(object): def __init__(self, config, logfile): self.config = config self.logfile = logfile # preferably line buffered def write_log_entry(self, testpath, lettercode, longrepr): py.builtin.print_("%s %s" % (lettercode, testpath), file=self.logfile) for line in longrepr.splitlines(): py.builtin.print_(" %s" % line, file=self.logfile) def log_outcome(self, report, lettercode, longrepr): testpath = getattr(report, 'nodeid', None) if testpath is None: testpath = report.fspath self.write_log_entry(testpath, lettercode, longrepr) def pytest_runtest_logreport(self, report): if report.when != "call" and report.passed: return res = self.config.hook.pytest_report_teststatus(report=report) code = res[1] if code == 'x': longrepr = str(report.longrepr) elif code == 'X': longrepr = '' elif report.passed: longrepr = "" elif report.failed: longrepr = str(report.longrepr) elif report.skipped: longrepr = str(report.longrepr[2]) self.log_outcome(report, code, longrepr) def pytest_collectreport(self, report): if not report.passed: if report.failed: code = "F" longrepr = str(report.longrepr) else: assert report.skipped code = "S" longrepr = "%s:%d: %s" % report.longrepr self.log_outcome(report, code, longrepr) def pytest_internalerror(self, excrepr): reprcrash = getattr(excrepr, 'reprcrash', None) path = getattr(reprcrash, "path", None) if path is None: path = "cwd:%s" % py.path.local() self.write_log_entry(path, '!', str(excrepr))
mpl-2.0
obulpathi/cloud
ml/vision/python/label/label.py
1
2368
#!/usr/bin/env python # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This script uses the Vision API's label detection capabilities to find a label based on an image's content. To run the example, install the necessary libraries by running: pip install -r requirements.txt Run the script on an image to get a label, E.g.: ./label.py <path-to-image> """ # [START import_libraries] import argparse import base64 from googleapiclient import discovery from oauth2client.client import GoogleCredentials # [END import_libraries] def main(photo_file): """Run a label request on a single image""" # [START authenticate] credentials = GoogleCredentials.get_application_default() service = discovery.build('vision', 'v1', credentials=credentials) # [END authenticate] # [START construct_request] with open(photo_file, 'rb') as image: image_content = base64.b64encode(image.read()) service_request = service.images().annotate(body={ 'requests': [{ 'image': { 'content': image_content.decode('UTF-8') }, 'features': [{ 'type': 'LABEL_DETECTION', 'maxResults': 1 }] }] }) # [END construct_request] # [START parse_response] response = service_request.execute() label = response['responses'][0]['labelAnnotations'][0]['description'] print('Found label: %s for %s' % (label, photo_file)) # [END parse_response] # [START run_application] if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('image_file', help='The image you\'d like to label.') args = parser.parse_args() main(args.image_file) # [END run_application]
apache-2.0
qq2588258/floweers
libs/external/emscripten/src/relooper/fuzzer.py
3
3123
import random, subprocess, difflib while True: # Random decisions num = random.randint(2, 250) density = random.random() * random.random() decisions = [random.randint(1, num*20) for x in range(num*3)] branches = [0]*num defaults = [0]*num for i in range(num): b = set([]) bs = random.randint(1, max(1, round(density*random.random()*(num-1)))) for j in range(bs): b.add(random.randint(1, num-1)) b = list(b) defaults[i] = random.choice(b) b.remove(defaults[i]) branches[i] = b print num, density for temp in ['fuzz', 'fuzz.fast.js', 'fuzz.slow.js', 'fuzz.cpp']: try: os.unlink(temp) except: pass # parts entry = '''print('entry'); var label; var state; var decisions = %s; var index = 0; function check() { if (index == decisions.length) throw 'HALT'; return decisions[index++] }''' % str(decisions) slow = entry + '\n' for i in range(len(branches[0])): if i > 0: slow += 'else ' b = branches[0] slow += 'if (state %% %d == %d) { label = %d; }\n' % (len(b)+1, i, b[i]) # TODO: split range 1-n into these options if len(branches[0]): slow += 'else ' slow += 'label = %d;\n' % defaults[0] slow += ''' while(1) switch(label) { ''' fast = ''' #include <stdlib.h> #include "Relooper.h" int main() { char *buffer = (char*)malloc(10*1024*1024); Relooper::SetOutputBuffer(buffer, 10*1024*1024); ''' for i in range(1, num): slow += ' case %d: print(%d); state = check(); \n' % (i, i) b = branches[i] for j in range(len(b)): slow += ' if (state %% %d == %d) { label = %d; break }\n' % (len(b)+1, j, b[j]) # TODO: split range 1-n into these options slow += ' label = %d; break\n' % defaults[i] for i in range(num): if i == 0: fast += ''' Block *b%d = new Block("%s"); ''' % (i, entry) else: fast += ''' Block *b%d = new Block("print(%d); state = check();%s"); ''' % (i, i, '// ' + ('.' * int(random.expovariate(0.5/num)))) for i in range(num): b = branches[i] for j in range(len(b)): fast += ''' b%d->AddBranchTo(b%d, "state %% %d == %d"); ''' % (i, b[j], len(b)+1, j) fast += ''' b%d->AddBranchTo(b%d, NULL); ''' % (i, defaults[i]) fast += ''' Relooper r; ''' for i in range(num): fast += ''' r.AddBlock(b%d); ''' % i fast += ''' r.Calculate(b0); printf("\\n\\n"); r.Render(); puts(buffer); return 1; } ''' slow += '}' open('fuzz.slow.js', 'w').write(slow) open('fuzz.cpp', 'w').write(fast) print '_' slow_out = subprocess.Popen(['mozjs', '-m', '-n', 'fuzz.slow.js'], stdout=subprocess.PIPE).communicate()[0] print '.' subprocess.call(['g++', 'fuzz.cpp', 'Relooper.o', '-o', 'fuzz', '-g']) print '*' subprocess.call(['./fuzz'], stdout=open('fuzz.fast.js', 'w')) print '-' fast_out = subprocess.Popen(['mozjs', '-m', '-n', 'fuzz.fast.js'], stdout=subprocess.PIPE).communicate()[0] print if slow_out != fast_out: print ''.join([a.rstrip()+'\n' for a in difflib.unified_diff(slow_out.split('\n'), fast_out.split('\n'), fromfile='slow', tofile='fast')]) assert False #break
mit
Work4Labs/lettuce
tests/integration/lib/Django-1.3/django/db/models/query.py
52
53941
""" The main QuerySet implementation. This provides the public API for the ORM. """ from itertools import izip from django.db import connections, router, transaction, IntegrityError from django.db.models.aggregates import Aggregate from django.db.models.fields import DateField from django.db.models.query_utils import (Q, select_related_descend, deferred_class_factory, InvalidQuery) from django.db.models.deletion import Collector from django.db.models import signals, sql from django.utils.copycompat import deepcopy # Used to control how many objects are worked with at once in some cases (e.g. # when deleting objects). CHUNK_SIZE = 100 ITER_CHUNK_SIZE = CHUNK_SIZE # The maximum number of items to display in a QuerySet.__repr__ REPR_OUTPUT_SIZE = 20 # Pull into this namespace for backwards compatibility. EmptyResultSet = sql.EmptyResultSet class QuerySet(object): """ Represents a lazy database lookup for a set of objects. """ def __init__(self, model=None, query=None, using=None): self.model = model # EmptyQuerySet instantiates QuerySet with model as None self._db = using self.query = query or sql.Query(self.model) self._result_cache = None self._iter = None self._sticky_filter = False self._for_write = False ######################## # PYTHON MAGIC METHODS # ######################## def __deepcopy__(self, memo): """ Deep copy of a QuerySet doesn't populate the cache """ obj = self.__class__() for k,v in self.__dict__.items(): if k in ('_iter','_result_cache'): obj.__dict__[k] = None else: obj.__dict__[k] = deepcopy(v, memo) return obj def __getstate__(self): """ Allows the QuerySet to be pickled. """ # Force the cache to be fully populated. len(self) obj_dict = self.__dict__.copy() obj_dict['_iter'] = None return obj_dict def __repr__(self): data = list(self[:REPR_OUTPUT_SIZE + 1]) if len(data) > REPR_OUTPUT_SIZE: data[-1] = "...(remaining elements truncated)..." return repr(data) def __len__(self): # Since __len__ is called quite frequently (for example, as part of # list(qs), we make some effort here to be as efficient as possible # whilst not messing up any existing iterators against the QuerySet. if self._result_cache is None: if self._iter: self._result_cache = list(self._iter) else: self._result_cache = list(self.iterator()) elif self._iter: self._result_cache.extend(self._iter) return len(self._result_cache) def __iter__(self): if self._result_cache is None: self._iter = self.iterator() self._result_cache = [] if self._iter: return self._result_iter() # Python's list iterator is better than our version when we're just # iterating over the cache. return iter(self._result_cache) def _result_iter(self): pos = 0 while 1: upper = len(self._result_cache) while pos < upper: yield self._result_cache[pos] pos = pos + 1 if not self._iter: raise StopIteration if len(self._result_cache) <= pos: self._fill_cache() def __nonzero__(self): if self._result_cache is not None: return bool(self._result_cache) try: iter(self).next() except StopIteration: return False return True def __contains__(self, val): # The 'in' operator works without this method, due to __iter__. This # implementation exists only to shortcut the creation of Model # instances, by bailing out early if we find a matching element. pos = 0 if self._result_cache is not None: if val in self._result_cache: return True elif self._iter is None: # iterator is exhausted, so we have our answer return False # remember not to check these again: pos = len(self._result_cache) else: # We need to start filling the result cache out. The following # ensures that self._iter is not None and self._result_cache is not # None it = iter(self) # Carry on, one result at a time. while True: if len(self._result_cache) <= pos: self._fill_cache(num=1) if self._iter is None: # we ran out of items return False if self._result_cache[pos] == val: return True pos += 1 def __getitem__(self, k): """ Retrieves an item or slice from the set of results. """ if not isinstance(k, (slice, int, long)): raise TypeError assert ((not isinstance(k, slice) and (k >= 0)) or (isinstance(k, slice) and (k.start is None or k.start >= 0) and (k.stop is None or k.stop >= 0))), \ "Negative indexing is not supported." if self._result_cache is not None: if self._iter is not None: # The result cache has only been partially populated, so we may # need to fill it out a bit more. if isinstance(k, slice): if k.stop is not None: # Some people insist on passing in strings here. bound = int(k.stop) else: bound = None else: bound = k + 1 if len(self._result_cache) < bound: self._fill_cache(bound - len(self._result_cache)) return self._result_cache[k] if isinstance(k, slice): qs = self._clone() if k.start is not None: start = int(k.start) else: start = None if k.stop is not None: stop = int(k.stop) else: stop = None qs.query.set_limits(start, stop) return k.step and list(qs)[::k.step] or qs try: qs = self._clone() qs.query.set_limits(k, k + 1) return list(qs)[0] except self.model.DoesNotExist, e: raise IndexError(e.args) def __and__(self, other): self._merge_sanity_check(other) if isinstance(other, EmptyQuerySet): return other._clone() combined = self._clone() combined.query.combine(other.query, sql.AND) return combined def __or__(self, other): self._merge_sanity_check(other) combined = self._clone() if isinstance(other, EmptyQuerySet): return combined combined.query.combine(other.query, sql.OR) return combined #################################### # METHODS THAT DO DATABASE QUERIES # #################################### def iterator(self): """ An iterator over the results from applying this QuerySet to the database. """ fill_cache = self.query.select_related if isinstance(fill_cache, dict): requested = fill_cache else: requested = None max_depth = self.query.max_depth extra_select = self.query.extra_select.keys() aggregate_select = self.query.aggregate_select.keys() only_load = self.query.get_loaded_field_names() if not fill_cache: fields = self.model._meta.fields pk_idx = self.model._meta.pk_index() index_start = len(extra_select) aggregate_start = index_start + len(self.model._meta.fields) load_fields = [] # If only/defer clauses have been specified, # build the list of fields that are to be loaded. if only_load: for field, model in self.model._meta.get_fields_with_model(): if model is None: model = self.model if field == self.model._meta.pk: # Record the index of the primary key when it is found pk_idx = len(load_fields) try: if field.name in only_load[model]: # Add a field that has been explicitly included load_fields.append(field.name) except KeyError: # Model wasn't explicitly listed in the only_load table # Therefore, we need to load all fields from this model load_fields.append(field.name) skip = None if load_fields and not fill_cache: # Some fields have been deferred, so we have to initialise # via keyword arguments. skip = set() init_list = [] for field in fields: if field.name not in load_fields: skip.add(field.attname) else: init_list.append(field.attname) model_cls = deferred_class_factory(self.model, skip) # Cache db and model outside the loop db = self.db model = self.model compiler = self.query.get_compiler(using=db) for row in compiler.results_iter(): if fill_cache: obj, _ = get_cached_row(model, row, index_start, using=db, max_depth=max_depth, requested=requested, offset=len(aggregate_select), only_load=only_load) else: if skip: row_data = row[index_start:aggregate_start] pk_val = row_data[pk_idx] obj = model_cls(**dict(zip(init_list, row_data))) else: # Omit aggregates in object creation. obj = model(*row[index_start:aggregate_start]) # Store the source database of the object obj._state.db = db # This object came from the database; it's not being added. obj._state.adding = False if extra_select: for i, k in enumerate(extra_select): setattr(obj, k, row[i]) # Add the aggregates to the model if aggregate_select: for i, aggregate in enumerate(aggregate_select): setattr(obj, aggregate, row[i+aggregate_start]) yield obj def aggregate(self, *args, **kwargs): """ Returns a dictionary containing the calculations (aggregation) over the current queryset If args is present the expression is passed as a kwarg using the Aggregate object's default alias. """ for arg in args: kwargs[arg.default_alias] = arg query = self.query.clone() for (alias, aggregate_expr) in kwargs.items(): query.add_aggregate(aggregate_expr, self.model, alias, is_summary=True) return query.get_aggregation(using=self.db) def count(self): """ Performs a SELECT COUNT() and returns the number of records as an integer. If the QuerySet is already fully cached this simply returns the length of the cached results set to avoid multiple SELECT COUNT(*) calls. """ if self._result_cache is not None and not self._iter: return len(self._result_cache) return self.query.get_count(using=self.db) def get(self, *args, **kwargs): """ Performs the query and returns a single object matching the given keyword arguments. """ clone = self.filter(*args, **kwargs) if self.query.can_filter(): clone = clone.order_by() num = len(clone) if num == 1: return clone._result_cache[0] if not num: raise self.model.DoesNotExist("%s matching query does not exist." % self.model._meta.object_name) raise self.model.MultipleObjectsReturned("get() returned more than one %s -- it returned %s! Lookup parameters were %s" % (self.model._meta.object_name, num, kwargs)) def create(self, **kwargs): """ Creates a new object with the given kwargs, saving it to the database and returning the created object. """ obj = self.model(**kwargs) self._for_write = True obj.save(force_insert=True, using=self.db) return obj def get_or_create(self, **kwargs): """ Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created. """ assert kwargs, \ 'get_or_create() must be passed at least one keyword argument' defaults = kwargs.pop('defaults', {}) lookup = kwargs.copy() for f in self.model._meta.fields: if f.attname in lookup: lookup[f.name] = lookup.pop(f.attname) try: self._for_write = True return self.get(**lookup), False except self.model.DoesNotExist: try: params = dict([(k, v) for k, v in kwargs.items() if '__' not in k]) params.update(defaults) obj = self.model(**params) sid = transaction.savepoint(using=self.db) obj.save(force_insert=True, using=self.db) transaction.savepoint_commit(sid, using=self.db) return obj, True except IntegrityError, e: transaction.savepoint_rollback(sid, using=self.db) try: return self.get(**lookup), False except self.model.DoesNotExist: raise e def latest(self, field_name=None): """ Returns the latest object, according to the model's 'get_latest_by' option or optional given field_name. """ latest_by = field_name or self.model._meta.get_latest_by assert bool(latest_by), "latest() requires either a field_name parameter or 'get_latest_by' in the model" assert self.query.can_filter(), \ "Cannot change a query once a slice has been taken." obj = self._clone() obj.query.set_limits(high=1) obj.query.add_ordering('-%s' % latest_by) return obj.get() def in_bulk(self, id_list): """ Returns a dictionary mapping each of the given IDs to the object with that ID. """ assert self.query.can_filter(), \ "Cannot use 'limit' or 'offset' with in_bulk" assert isinstance(id_list, (tuple, list, set, frozenset)), \ "in_bulk() must be provided with a list of IDs." if not id_list: return {} qs = self._clone() qs.query.add_filter(('pk__in', id_list)) qs.query.clear_ordering(force_empty=True) return dict([(obj._get_pk_val(), obj) for obj in qs.iterator()]) def delete(self): """ Deletes the records in the current QuerySet. """ assert self.query.can_filter(), \ "Cannot use 'limit' or 'offset' with delete." del_query = self._clone() # The delete is actually 2 queries - one to find related objects, # and one to delete. Make sure that the discovery of related # objects is performed on the same database as the deletion. del_query._for_write = True # Disable non-supported fields. del_query.query.select_related = False del_query.query.clear_ordering() collector = Collector(using=del_query.db) collector.collect(del_query) collector.delete() # Clear the result cache, in case this QuerySet gets reused. self._result_cache = None delete.alters_data = True def update(self, **kwargs): """ Updates all elements in the current QuerySet, setting all the given fields to the appropriate values. """ assert self.query.can_filter(), \ "Cannot update a query once a slice has been taken." self._for_write = True query = self.query.clone(sql.UpdateQuery) query.add_update_values(kwargs) if not transaction.is_managed(using=self.db): transaction.enter_transaction_management(using=self.db) forced_managed = True else: forced_managed = False try: rows = query.get_compiler(self.db).execute_sql(None) if forced_managed: transaction.commit(using=self.db) else: transaction.commit_unless_managed(using=self.db) finally: if forced_managed: transaction.leave_transaction_management(using=self.db) self._result_cache = None return rows update.alters_data = True def _update(self, values): """ A version of update that accepts field objects instead of field names. Used primarily for model saving and not intended for use by general code (it requires too much poking around at model internals to be useful at that level). """ assert self.query.can_filter(), \ "Cannot update a query once a slice has been taken." query = self.query.clone(sql.UpdateQuery) query.add_update_fields(values) self._result_cache = None return query.get_compiler(self.db).execute_sql(None) _update.alters_data = True def exists(self): if self._result_cache is None: return self.query.has_results(using=self.db) return bool(self._result_cache) ################################################## # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS # ################################################## def values(self, *fields): return self._clone(klass=ValuesQuerySet, setup=True, _fields=fields) def values_list(self, *fields, **kwargs): flat = kwargs.pop('flat', False) if kwargs: raise TypeError('Unexpected keyword arguments to values_list: %s' % (kwargs.keys(),)) if flat and len(fields) > 1: raise TypeError("'flat' is not valid when values_list is called with more than one field.") return self._clone(klass=ValuesListQuerySet, setup=True, flat=flat, _fields=fields) def dates(self, field_name, kind, order='ASC'): """ Returns a list of datetime objects representing all available dates for the given field_name, scoped to 'kind'. """ assert kind in ("month", "year", "day"), \ "'kind' must be one of 'year', 'month' or 'day'." assert order in ('ASC', 'DESC'), \ "'order' must be either 'ASC' or 'DESC'." return self._clone(klass=DateQuerySet, setup=True, _field_name=field_name, _kind=kind, _order=order) def none(self): """ Returns an empty QuerySet. """ return self._clone(klass=EmptyQuerySet) ################################################################## # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET # ################################################################## def all(self): """ Returns a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases. """ return self._clone() def filter(self, *args, **kwargs): """ Returns a new QuerySet instance with the args ANDed to the existing set. """ return self._filter_or_exclude(False, *args, **kwargs) def exclude(self, *args, **kwargs): """ Returns a new QuerySet instance with NOT (args) ANDed to the existing set. """ return self._filter_or_exclude(True, *args, **kwargs) def _filter_or_exclude(self, negate, *args, **kwargs): if args or kwargs: assert self.query.can_filter(), \ "Cannot filter a query once a slice has been taken." clone = self._clone() if negate: clone.query.add_q(~Q(*args, **kwargs)) else: clone.query.add_q(Q(*args, **kwargs)) return clone def complex_filter(self, filter_obj): """ Returns a new QuerySet instance with filter_obj added to the filters. filter_obj can be a Q object (or anything with an add_to_query() method) or a dictionary of keyword lookup arguments. This exists to support framework features such as 'limit_choices_to', and usually it will be more natural to use other methods. """ if isinstance(filter_obj, Q) or hasattr(filter_obj, 'add_to_query'): clone = self._clone() clone.query.add_q(filter_obj) return clone else: return self._filter_or_exclude(None, **filter_obj) def select_related(self, *fields, **kwargs): """ Returns a new QuerySet instance that will select related objects. If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection. """ depth = kwargs.pop('depth', 0) if kwargs: raise TypeError('Unexpected keyword arguments to select_related: %s' % (kwargs.keys(),)) obj = self._clone() if fields: if depth: raise TypeError('Cannot pass both "depth" and fields to select_related()') obj.query.add_select_related(fields) else: obj.query.select_related = True if depth: obj.query.max_depth = depth return obj def dup_select_related(self, other): """ Copies the related selection status from the QuerySet 'other' to the current QuerySet. """ self.query.select_related = other.query.select_related def annotate(self, *args, **kwargs): """ Return a query set in which the returned objects have been annotated with data aggregated from related fields. """ for arg in args: if arg.default_alias in kwargs: raise ValueError("The named annotation '%s' conflicts with the " "default name for another annotation." % arg.default_alias) kwargs[arg.default_alias] = arg names = getattr(self, '_fields', None) if names is None: names = set(self.model._meta.get_all_field_names()) for aggregate in kwargs: if aggregate in names: raise ValueError("The annotation '%s' conflicts with a field on " "the model." % aggregate) obj = self._clone() obj._setup_aggregate_query(kwargs.keys()) # Add the aggregates to the query for (alias, aggregate_expr) in kwargs.items(): obj.query.add_aggregate(aggregate_expr, self.model, alias, is_summary=False) return obj def order_by(self, *field_names): """ Returns a new QuerySet instance with the ordering changed. """ assert self.query.can_filter(), \ "Cannot reorder a query once a slice has been taken." obj = self._clone() obj.query.clear_ordering() obj.query.add_ordering(*field_names) return obj def distinct(self, true_or_false=True): """ Returns a new QuerySet instance that will select only distinct results. """ obj = self._clone() obj.query.distinct = true_or_false return obj def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None): """ Adds extra SQL fragments to the query. """ assert self.query.can_filter(), \ "Cannot change a query once a slice has been taken" clone = self._clone() clone.query.add_extra(select, select_params, where, params, tables, order_by) return clone def reverse(self): """ Reverses the ordering of the QuerySet. """ clone = self._clone() clone.query.standard_ordering = not clone.query.standard_ordering return clone def defer(self, *fields): """ Defers the loading of data for certain fields until they are accessed. The set of fields to defer is added to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case all deferrals are removed (None acts as a reset option). """ clone = self._clone() if fields == (None,): clone.query.clear_deferred_loading() else: clone.query.add_deferred_loading(fields) return clone def only(self, *fields): """ Essentially, the opposite of defer. Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated. """ if fields == (None,): # Can only pass None to defer(), not only(), as the rest option. # That won't stop people trying to do this, so let's be explicit. raise TypeError("Cannot pass None as an argument to only().") clone = self._clone() clone.query.add_immediate_loading(fields) return clone def using(self, alias): """ Selects which database this QuerySet should excecute it's query against. """ clone = self._clone() clone._db = alias return clone ################################### # PUBLIC INTROSPECTION ATTRIBUTES # ################################### def ordered(self): """ Returns True if the QuerySet is ordered -- i.e. has an order_by() clause or a default ordering on the model. """ if self.query.extra_order_by or self.query.order_by: return True elif self.query.default_ordering and self.query.model._meta.ordering: return True else: return False ordered = property(ordered) @property def db(self): "Return the database that will be used if this query is executed now" if self._for_write: return self._db or router.db_for_write(self.model) return self._db or router.db_for_read(self.model) ################### # PRIVATE METHODS # ################### def _clone(self, klass=None, setup=False, **kwargs): if klass is None: klass = self.__class__ query = self.query.clone() if self._sticky_filter: query.filter_is_sticky = True c = klass(model=self.model, query=query, using=self._db) c._for_write = self._for_write c.__dict__.update(kwargs) if setup and hasattr(c, '_setup_query'): c._setup_query() return c def _fill_cache(self, num=None): """ Fills the result cache with 'num' more entries (or until the results iterator is exhausted). """ if self._iter: try: for i in range(num or ITER_CHUNK_SIZE): self._result_cache.append(self._iter.next()) except StopIteration: self._iter = None def _next_is_sticky(self): """ Indicates that the next filter call and the one following that should be treated as a single filter. This is only important when it comes to determining when to reuse tables for many-to-many filters. Required so that we can filter naturally on the results of related managers. This doesn't return a clone of the current QuerySet (it returns "self"). The method is only used internally and should be immediately followed by a filter() that does create a clone. """ self._sticky_filter = True return self def _merge_sanity_check(self, other): """ Checks that we are merging two comparable QuerySet classes. By default this does nothing, but see the ValuesQuerySet for an example of where it's useful. """ pass def _setup_aggregate_query(self, aggregates): """ Prepare the query for computing a result that contains aggregate annotations. """ opts = self.model._meta if self.query.group_by is None: field_names = [f.attname for f in opts.fields] self.query.add_fields(field_names, False) self.query.set_group_by() def _prepare(self): return self def _as_sql(self, connection): """ Returns the internal query's SQL and parameters (as a tuple). """ obj = self.values("pk") if obj._db is None or connection == connections[obj._db]: return obj.query.get_compiler(connection=connection).as_nested_sql() raise ValueError("Can't do subqueries with queries on different DBs.") # When used as part of a nested query, a queryset will never be an "always # empty" result. value_annotation = True class ValuesQuerySet(QuerySet): def __init__(self, *args, **kwargs): super(ValuesQuerySet, self).__init__(*args, **kwargs) # select_related isn't supported in values(). (FIXME -#3358) self.query.select_related = False # QuerySet.clone() will also set up the _fields attribute with the # names of the model fields to select. def iterator(self): # Purge any extra columns that haven't been explicitly asked for extra_names = self.query.extra_select.keys() field_names = self.field_names aggregate_names = self.query.aggregate_select.keys() names = extra_names + field_names + aggregate_names for row in self.query.get_compiler(self.db).results_iter(): yield dict(zip(names, row)) def _setup_query(self): """ Constructs the field_names list that the values query will be retrieving. Called by the _clone() method after initializing the rest of the instance. """ self.query.clear_deferred_loading() self.query.clear_select_fields() if self._fields: self.extra_names = [] self.aggregate_names = [] if not self.query.extra and not self.query.aggregates: # Short cut - if there are no extra or aggregates, then # the values() clause must be just field names. self.field_names = list(self._fields) else: self.query.default_cols = False self.field_names = [] for f in self._fields: # we inspect the full extra_select list since we might # be adding back an extra select item that we hadn't # had selected previously. if f in self.query.extra: self.extra_names.append(f) elif f in self.query.aggregate_select: self.aggregate_names.append(f) else: self.field_names.append(f) else: # Default to all fields. self.extra_names = None self.field_names = [f.attname for f in self.model._meta.fields] self.aggregate_names = None self.query.select = [] if self.extra_names is not None: self.query.set_extra_mask(self.extra_names) self.query.add_fields(self.field_names, True) if self.aggregate_names is not None: self.query.set_aggregate_mask(self.aggregate_names) def _clone(self, klass=None, setup=False, **kwargs): """ Cloning a ValuesQuerySet preserves the current fields. """ c = super(ValuesQuerySet, self)._clone(klass, **kwargs) if not hasattr(c, '_fields'): # Only clone self._fields if _fields wasn't passed into the cloning # call directly. c._fields = self._fields[:] c.field_names = self.field_names c.extra_names = self.extra_names c.aggregate_names = self.aggregate_names if setup and hasattr(c, '_setup_query'): c._setup_query() return c def _merge_sanity_check(self, other): super(ValuesQuerySet, self)._merge_sanity_check(other) if (set(self.extra_names) != set(other.extra_names) or set(self.field_names) != set(other.field_names) or self.aggregate_names != other.aggregate_names): raise TypeError("Merging '%s' classes must involve the same values in each case." % self.__class__.__name__) def _setup_aggregate_query(self, aggregates): """ Prepare the query for computing a result that contains aggregate annotations. """ self.query.set_group_by() if self.aggregate_names is not None: self.aggregate_names.extend(aggregates) self.query.set_aggregate_mask(self.aggregate_names) super(ValuesQuerySet, self)._setup_aggregate_query(aggregates) def _as_sql(self, connection): """ For ValueQuerySet (and subclasses like ValuesListQuerySet), they can only be used as nested queries if they're already set up to select only a single field (in which case, that is the field column that is returned). This differs from QuerySet.as_sql(), where the column to select is set up by Django. """ if ((self._fields and len(self._fields) > 1) or (not self._fields and len(self.model._meta.fields) > 1)): raise TypeError('Cannot use a multi-field %s as a filter value.' % self.__class__.__name__) obj = self._clone() if obj._db is None or connection == connections[obj._db]: return obj.query.get_compiler(connection=connection).as_nested_sql() raise ValueError("Can't do subqueries with queries on different DBs.") def _prepare(self): """ Validates that we aren't trying to do a query like value__in=qs.values('value1', 'value2'), which isn't valid. """ if ((self._fields and len(self._fields) > 1) or (not self._fields and len(self.model._meta.fields) > 1)): raise TypeError('Cannot use a multi-field %s as a filter value.' % self.__class__.__name__) return self class ValuesListQuerySet(ValuesQuerySet): def iterator(self): if self.flat and len(self._fields) == 1: for row in self.query.get_compiler(self.db).results_iter(): yield row[0] elif not self.query.extra_select and not self.query.aggregate_select: for row in self.query.get_compiler(self.db).results_iter(): yield tuple(row) else: # When extra(select=...) or an annotation is involved, the extra # cols are always at the start of the row, and we need to reorder # the fields to match the order in self._fields. extra_names = self.query.extra_select.keys() field_names = self.field_names aggregate_names = self.query.aggregate_select.keys() names = extra_names + field_names + aggregate_names # If a field list has been specified, use it. Otherwise, use the # full list of fields, including extras and aggregates. if self._fields: fields = list(self._fields) + filter(lambda f: f not in self._fields, aggregate_names) else: fields = names for row in self.query.get_compiler(self.db).results_iter(): data = dict(zip(names, row)) yield tuple([data[f] for f in fields]) def _clone(self, *args, **kwargs): clone = super(ValuesListQuerySet, self)._clone(*args, **kwargs) if not hasattr(clone, "flat"): # Only assign flat if the clone didn't already get it from kwargs clone.flat = self.flat return clone class DateQuerySet(QuerySet): def iterator(self): return self.query.get_compiler(self.db).results_iter() def _setup_query(self): """ Sets up any special features of the query attribute. Called by the _clone() method after initializing the rest of the instance. """ self.query.clear_deferred_loading() self.query = self.query.clone(klass=sql.DateQuery, setup=True) self.query.select = [] self.query.add_date_select(self._field_name, self._kind, self._order) def _clone(self, klass=None, setup=False, **kwargs): c = super(DateQuerySet, self)._clone(klass, False, **kwargs) c._field_name = self._field_name c._kind = self._kind if setup and hasattr(c, '_setup_query'): c._setup_query() return c class EmptyQuerySet(QuerySet): def __init__(self, model=None, query=None, using=None): super(EmptyQuerySet, self).__init__(model, query, using) self._result_cache = [] def __and__(self, other): return self._clone() def __or__(self, other): return other._clone() def count(self): return 0 def delete(self): pass def _clone(self, klass=None, setup=False, **kwargs): c = super(EmptyQuerySet, self)._clone(klass, setup=setup, **kwargs) c._result_cache = [] return c def iterator(self): # This slightly odd construction is because we need an empty generator # (it raises StopIteration immediately). yield iter([]).next() def all(self): """ Always returns EmptyQuerySet. """ return self def filter(self, *args, **kwargs): """ Always returns EmptyQuerySet. """ return self def exclude(self, *args, **kwargs): """ Always returns EmptyQuerySet. """ return self def complex_filter(self, filter_obj): """ Always returns EmptyQuerySet. """ return self def select_related(self, *fields, **kwargs): """ Always returns EmptyQuerySet. """ return self def annotate(self, *args, **kwargs): """ Always returns EmptyQuerySet. """ return self def order_by(self, *field_names): """ Always returns EmptyQuerySet. """ return self def distinct(self, true_or_false=True): """ Always returns EmptyQuerySet. """ return self def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None): """ Always returns EmptyQuerySet. """ assert self.query.can_filter(), \ "Cannot change a query once a slice has been taken" return self def reverse(self): """ Always returns EmptyQuerySet. """ return self def defer(self, *fields): """ Always returns EmptyQuerySet. """ return self def only(self, *fields): """ Always returns EmptyQuerySet. """ return self def update(self, **kwargs): """ Don't update anything. """ return 0 # EmptyQuerySet is always an empty result in where-clauses (and similar # situations). value_annotation = False def get_cached_row(klass, row, index_start, using, max_depth=0, cur_depth=0, requested=None, offset=0, only_load=None, local_only=False): """ Helper function that recursively returns an object with the specified related attributes already populated. This method may be called recursively to populate deep select_related() clauses. Arguments: * klass - the class to retrieve (and instantiate) * row - the row of data returned by the database cursor * index_start - the index of the row at which data for this object is known to start * using - the database alias on which the query is being executed. * max_depth - the maximum depth to which a select_related() relationship should be explored. * cur_depth - the current depth in the select_related() tree. Used in recursive calls to determin if we should dig deeper. * requested - A dictionary describing the select_related() tree that is to be retrieved. keys are field names; values are dictionaries describing the keys on that related object that are themselves to be select_related(). * offset - the number of additional fields that are known to exist in `row` for `klass`. This usually means the number of annotated results on `klass`. * only_load - if the query has had only() or defer() applied, this is the list of field names that will be returned. If None, the full field list for `klass` can be assumed. * local_only - Only populate local fields. This is used when building following reverse select-related relations """ if max_depth and requested is None and cur_depth > max_depth: # We've recursed deeply enough; stop now. return None restricted = requested is not None if only_load: load_fields = only_load.get(klass) # When we create the object, we will also be creating populating # all the parent classes, so traverse the parent classes looking # for fields that must be included on load. for parent in klass._meta.get_parent_list(): fields = only_load.get(parent) if fields: load_fields.update(fields) else: load_fields = None if load_fields: # Handle deferred fields. skip = set() init_list = [] # Build the list of fields that *haven't* been requested for field, model in klass._meta.get_fields_with_model(): if field.name not in load_fields: skip.add(field.name) elif local_only and model is not None: continue else: init_list.append(field.attname) # Retrieve all the requested fields field_count = len(init_list) fields = row[index_start : index_start + field_count] # If all the select_related columns are None, then the related # object must be non-existent - set the relation to None. # Otherwise, construct the related object. if fields == (None,) * field_count: obj = None elif skip: klass = deferred_class_factory(klass, skip) obj = klass(**dict(zip(init_list, fields))) else: obj = klass(*fields) else: # Load all fields on klass if local_only: field_names = [f.attname for f in klass._meta.local_fields] else: field_names = [f.attname for f in klass._meta.fields] field_count = len(field_names) fields = row[index_start : index_start + field_count] # If all the select_related columns are None, then the related # object must be non-existent - set the relation to None. # Otherwise, construct the related object. if fields == (None,) * field_count: obj = None else: obj = klass(**dict(zip(field_names, fields))) # If an object was retrieved, set the database state. if obj: obj._state.db = using obj._state.adding = False index_end = index_start + field_count + offset # Iterate over each related object, populating any # select_related() fields for f in klass._meta.fields: if not select_related_descend(f, restricted, requested): continue if restricted: next = requested[f.name] else: next = None # Recursively retrieve the data for the related object cached_row = get_cached_row(f.rel.to, row, index_end, using, max_depth, cur_depth+1, next, only_load=only_load) # If the recursive descent found an object, populate the # descriptor caches relevant to the object if cached_row: rel_obj, index_end = cached_row if obj is not None: # If the base object exists, populate the # descriptor cache setattr(obj, f.get_cache_name(), rel_obj) if f.unique and rel_obj is not None: # If the field is unique, populate the # reverse descriptor cache on the related object setattr(rel_obj, f.related.get_cache_name(), obj) # Now do the same, but for reverse related objects. # Only handle the restricted case - i.e., don't do a depth # descent into reverse relations unless explicitly requested if restricted: related_fields = [ (o.field, o.model) for o in klass._meta.get_all_related_objects() if o.field.unique ] for f, model in related_fields: if not select_related_descend(f, restricted, requested, reverse=True): continue next = requested[f.related_query_name()] # Recursively retrieve the data for the related object cached_row = get_cached_row(model, row, index_end, using, max_depth, cur_depth+1, next, only_load=only_load, local_only=True) # If the recursive descent found an object, populate the # descriptor caches relevant to the object if cached_row: rel_obj, index_end = cached_row if obj is not None: # If the field is unique, populate the # reverse descriptor cache setattr(obj, f.related.get_cache_name(), rel_obj) if rel_obj is not None: # If the related object exists, populate # the descriptor cache. setattr(rel_obj, f.get_cache_name(), obj) # Now populate all the non-local field values # on the related object for rel_field,rel_model in rel_obj._meta.get_fields_with_model(): if rel_model is not None: setattr(rel_obj, rel_field.attname, getattr(obj, rel_field.attname)) # populate the field cache for any related object # that has already been retrieved if rel_field.rel: try: cached_obj = getattr(obj, rel_field.get_cache_name()) setattr(rel_obj, rel_field.get_cache_name(), cached_obj) except AttributeError: # Related object hasn't been cached yet pass return obj, index_end class RawQuerySet(object): """ Provides an iterator which converts the results of raw SQL queries into annotated model instances. """ def __init__(self, raw_query, model=None, query=None, params=None, translations=None, using=None): self.raw_query = raw_query self.model = model self._db = using self.query = query or sql.RawQuery(sql=raw_query, using=self.db, params=params) self.params = params or () self.translations = translations or {} def __iter__(self): # Mapping of attrnames to row column positions. Used for constructing # the model using kwargs, needed when not all model's fields are present # in the query. model_init_field_names = {} # A list of tuples of (column name, column position). Used for # annotation fields. annotation_fields = [] # Cache some things for performance reasons outside the loop. db = self.db compiler = connections[db].ops.compiler('SQLCompiler')( self.query, connections[db], db ) need_resolv_columns = hasattr(compiler, 'resolve_columns') query = iter(self.query) # Find out which columns are model's fields, and which ones should be # annotated to the model. for pos, column in enumerate(self.columns): if column in self.model_fields: model_init_field_names[self.model_fields[column].attname] = pos else: annotation_fields.append((column, pos)) # Find out which model's fields are not present in the query. skip = set() for field in self.model._meta.fields: if field.attname not in model_init_field_names: skip.add(field.attname) if skip: if self.model._meta.pk.attname in skip: raise InvalidQuery('Raw query must include the primary key') model_cls = deferred_class_factory(self.model, skip) else: model_cls = self.model # All model's fields are present in the query. So, it is possible # to use *args based model instantation. For each field of the model, # record the query column position matching that field. model_init_field_pos = [] for field in self.model._meta.fields: model_init_field_pos.append(model_init_field_names[field.attname]) if need_resolv_columns: fields = [self.model_fields.get(c, None) for c in self.columns] # Begin looping through the query values. for values in query: if need_resolv_columns: values = compiler.resolve_columns(values, fields) # Associate fields to values if skip: model_init_kwargs = {} for attname, pos in model_init_field_names.iteritems(): model_init_kwargs[attname] = values[pos] instance = model_cls(**model_init_kwargs) else: model_init_args = [values[pos] for pos in model_init_field_pos] instance = model_cls(*model_init_args) if annotation_fields: for column, pos in annotation_fields: setattr(instance, column, values[pos]) instance._state.db = db instance._state.adding = False yield instance def __repr__(self): return "<RawQuerySet: %r>" % (self.raw_query % self.params) def __getitem__(self, k): return list(self)[k] @property def db(self): "Return the database that will be used if this query is executed now" return self._db or router.db_for_read(self.model) def using(self, alias): """ Selects which database this Raw QuerySet should excecute it's query against. """ return RawQuerySet(self.raw_query, model=self.model, query=self.query.clone(using=alias), params=self.params, translations=self.translations, using=alias) @property def columns(self): """ A list of model field names in the order they'll appear in the query results. """ if not hasattr(self, '_columns'): self._columns = self.query.get_columns() # Adjust any column names which don't match field names for (query_name, model_name) in self.translations.items(): try: index = self._columns.index(query_name) self._columns[index] = model_name except ValueError: # Ignore translations for non-existant column names pass return self._columns @property def model_fields(self): """ A dict mapping column names to model field names. """ if not hasattr(self, '_model_fields'): converter = connections[self.db].introspection.table_name_converter self._model_fields = {} for field in self.model._meta.fields: name, column = field.get_attname_column() self._model_fields[converter(column)] = field return self._model_fields def insert_query(model, values, return_id=False, raw_values=False, using=None): """ Inserts a new record for the given model. This provides an interface to the InsertQuery class and is how Model.save() is implemented. It is not part of the public API. """ query = sql.InsertQuery(model) query.insert_values(values, raw_values) return query.get_compiler(using=using).execute_sql(return_id)
gpl-3.0
markgw/jazzparser
src/jazzparser/utils/config.py
1
14444
"""Config file parsing All of the scripts in this project use the optparse package to handle command line options. This module provides a very simple mechanism for taking config files as input instead of specifying options on the command line. This is convenient, for example, for running experiments repeatedly where a whole load of options need to be given to set parameters. The options in the file are stored in the following format:: optname=value - The files may contain comments beginning with a '#'. - To specify arguments, just put the argument on a line of its own. - To specify flags, put the flag name on a line of its own preceded by a +. You can only use long option names currently. This is best practice anyway, as it makes the file more readable. The config options are simply transformed into a string of command-line-like options and added to the actual command-line options. Don't forget to put a comment in the file so you know what script it's for! Additionally, lines beginning with '%%' are treated as directives. - C{%% INCLUDE filename}: includes another config file. - C{%% ARG i value}: treats C{value} as the ith argument. If you specify any arguments in this way, you should specify them all like this. Allows the arguments not to be given in order. - C{%% DEF name value}: defines or defines the value of the variable C{name}. This value may subsequently be used with a %{name} substitution. - C{%% ABSTRACT}: declares the whole file to be abstract, i.e. it cannot be used directly, but only as an include in another file. You should put this in any file that relies on including files to supply required options/arguments. - C{%% REQUIRE option}: requires the user to specify the named option on the command line when using this config file. You may use certain substitutions in the options. %{X} will be replaced by a value if one can be found. The following sources are consulted (in this order): - a variable X defined with a DEF directive; - a constant X from the settings file. One purpose of this is to allow you to specify paths relative to the project root, etc, rather than where the script is run. A linebreak preceded by a \ will be ignored. Whitespace at the start of the subsequent line will be ignored (but not whitespace before the \). """ """ ============================== License ======================================== Copyright (C) 2008, 2010-12 University of Edinburgh, Mark Granroth-Wilding This file is part of The Jazz Parser. The Jazz Parser 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. The Jazz Parser 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 The Jazz Parser. If not, see <http://www.gnu.org/licenses/>. ============================ End license ====================================== """ __author__ = "Mark Granroth-Wilding <mark.granroth-wilding@ed.ac.uk>" import sys class ConfigFile(object): """ A really simple interface to options stored in config files. Can also process a string as if read from the contents of a file. """ def __init__(self, filename, string=False): self.options = [] self.flags = [] self.arguments = [] self.required_options = [] if string: # Take the config lines as a string directly self.filename = None self.lines = filename.split("\n") else: # Read config lines from a file self.filename = filename with open(self.filename, 'r') as cfile: self.lines = cfile.readlines() self.parse_lines() @staticmethod def from_string(string): return ConfigFile(string, string=True) def parse_lines(self): """ Parses the lines stored in self.lines. Called by initialization. You can call this straight off if you've instantiated with a string. """ from jazzparser import settings import os conf_lines = self.lines numbered_args = {} defined_variables = {} def _do_substitutions(value, full_line): # Look for any placeholders in the value and perform the # appropriate substitution while "%{" in value: opener = value.index("%{") closer = value.find("}", opener) if closer == -1: # No matching close brace raise ConfigFileReadError, "no matching close brace (}) found in %s" % full_line const_name = value[opener+2:closer] if const_name in defined_variables: # First check whether a value is defined for this name sub_value = defined_variables[const_name] elif hasattr(settings, const_name): # Try getting a constant from the settings file sub_value = getattr(settings, const_name) else: raise ConfigFileReadError, "no setting or variable "\ "'%s' found to make substitution in: %s" % \ (const_name, full_line.strip()) # Replace every occurrence of this placeholder with the value value = value.replace("%{"+const_name+"}", sub_value) return value # Preprocess the lines def _preprocess_lines(lines, included=False): _proc_lines = [] # Remove line breaks from the end lines = [l.rstrip("\n") for l in lines] # Concatenate lines where a \ precedes the line break joined_lines = [] to_join = [] for line in lines: if line.endswith("\\"): to_join.append(line[:-1].lstrip()) else: if len(to_join) > 0: to_join.append(line.lstrip()) joined_lines.append("".join(to_join)) to_join = [] else: joined_lines.append(line) for line in joined_lines: use_line = True # Ignore anything after a # if "#" in line: line = line[:line.index("#")] line = line.strip() # Check for directives if line.startswith("%%"): # Eliminate this line from the preprocessed set use_line = False line = _do_substitutions(line[2:], line) # Pull out the first word and make it case insensitive directive = line.split()[0].strip().lower() args = line.split()[1:] # Check what the directive is a process the lines accordingly if directive == "include": if len(args) != 1: raise ConfigFileReadError, "INCLUDE directive "\ "requires a filename argument" # Include another config file if self.filename is None: # Can't make paths relative to filename filename = args[0] else: filename = os.path.join( os.path.dirname(self.filename), args[0]) filename = os.path.abspath(filename) try: file = open(filename, 'r') except IOError: raise ConfigFileReadError, "could not open "\ "included config file %s" % filename try: # Replace this line with the lines of the other file file_lines = _preprocess_lines(file.readlines(), included=True) _proc_lines.extend(file_lines) finally: file.close() elif directive == "arg": if len(args) != 2: raise ConfigFileReadError, "ARG directive "\ "requires an argument number and a value" arg_num = int(args[0]) numbered_args[arg_num] = args[1] elif directive == "def": if len(args) != 2: raise ConfigFileReadError, "DEF directive "\ "requires a variable name and a value" defined_variables[args[0]] = args[1] elif directive == "abstract": if not included: # The file isn't being read because it's included # in another, but it's marked as abstract, so # shouldn't be used directly raise ConfigFileReadError, "encountered ABSTRACT "\ "directive in a non-included file. You should "\ "not use this file directly, but as an include "\ "in another config file." elif directive == "require": if len(args) != 1: raise ConfigFileReadError, "REQUIRE directive "\ "needs an option name" self.required_options.append(args[0]) # Define any more directives here else: raise ConfigFileReadError, "unknown directive: %s" % directive if use_line and len(line) > 0: _proc_lines.append(line) return _proc_lines proc_lines = _preprocess_lines(conf_lines) if len(numbered_args) > 0: # Check that the numbered args make sense num_args = max(numbered_args.keys()) for i in range(num_args+1): if i not in numbered_args: raise ConfigFileReadError, "missing argument: "\ "arg number %s was given but %s was not" % \ (num_args, i) # Transform these into ordinary ordered args self.arguments = [numbered_args[i] for i in range(num_args+1)] for line in proc_lines: if line.startswith("+"): # Take the + off and store this as a flag self.flags.append(line[1:]) elif "=" in line: # Split the optname=val into optname and val opt, __, val = line.partition("=") self.options.append((opt.strip(), _do_substitutions(val.strip(), line))) else: # Just a plain argument if len(numbered_args) > 0: raise ConfigFileReadError, "cannot mix numbered args "\ "and non-numbered args: %s" % line self.arguments.append(_do_substitutions(line.strip(), line)) def get_strings(self): """ Get a list of strings containing all the config options in a form ready to be passed to optparse as if they were command-line options. """ return sum([["--%s" % opt, "%s" % val] for (opt,val) in self.options], []) \ + ["--%s" % flag for flag in self.flags] \ + self.arguments def parse_args_with_config(parser, option_name="config"): """ An alternative to calling parser.parse_args() which adds a --config option to the parser's options and uses it to read in a config file if it's given. The args will potentially get parsed twice: once to get the config file and then again to incorporate options from the file. @return: (options, arguments) tuple, as given by parser.parse_args(). """ import sys # Add the config file option parser.add_option("--%s" % option_name, dest="%s" % option_name, action="store", help="read options in from a config file.") # Do the initial (standard) parse options,arguments = parser.parse_args() conf_file = getattr(options, option_name) if conf_file is not None: # Read in options from the config file conf = ConfigFile(conf_file) # Check that any options the file requires the user to give are there for required in conf.required_options: if not hasattr(options, required): raise ConfigFileReadError, "config file requires non-existent "\ "command line option '%s'" % required elif getattr(options, required) is None: print "Error: config file requires that you "\ "give the option '%s' on the command line" % required sys.exit(1) # Produce arguments that incorporate the file and cmd-line opts conf_strings = conf.get_strings() if len(conf_strings) > 0: # Parse the opts and args from the config file first options, file_arguments = parser.parse_args(args=conf_strings) # Reparse the command line options so that values given there # override those in the file options, cl_arguments = parser.parse_args(values=options) # Include arguments from both sources, file first arguments = file_arguments + cl_arguments return options,arguments class ConfigFileReadError(Exception): pass
gpl-3.0
xodus7/tensorflow
tensorflow/python/summary/text_summary_test.py
9
1932
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.platform import googletest from tensorflow.python.summary import text_summary class TextPluginTest(test_util.TensorFlowTestCase): """Test the Text Summary API. These tests are focused on testing the API design of the text_summary method. It doesn't test the PluginAsset and tensors registry functionality, because that is better tested by the text_plugin test that actually consumes that metadata. """ def testTextSummaryAPI(self): with self.cached_session(): with self.assertRaises(ValueError): num = array_ops.constant(1) text_summary.text_summary("foo", num) # The API accepts vectors. arr = array_ops.constant(["one", "two", "three"]) summ = text_summary.text_summary("foo", arr) self.assertEqual(summ.op.type, "TensorSummaryV2") # the API accepts scalars summ = text_summary.text_summary("foo", array_ops.constant("one")) self.assertEqual(summ.op.type, "TensorSummaryV2") if __name__ == "__main__": googletest.main()
apache-2.0
OpenHydrology/StatisticalFloodEstimationTool
floodestimationgui/CatchmentDescriptors.py
1
18940
''' Created on 27 Apr 2014 @author: Neil Nutt, neilnutt[at]googlemail[dot]com Tab used to store/collect catchment descriptors Statistical Flood Estimation Tool Copyright (C) 2014 Neil Nutt, neilnutt[at]googlemail[dot]com https://github.com/OpenHydrology/StatisticalFloodEstimationTool 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. ''' import wx,os,time import config from floodestimation.loaders import load_catchment from floodestimation.entities import Point class Fpanel(wx.Panel): def __init__(self, parent,p): wx.Panel.__init__(self, parent) self.inside_load=False self.parent =parent self.p=p #self.title_label = wx.StaticText(self, -1, "-") outlet_label = wx.StaticText(self, -1, "Outlet grid ref") centroid_label = wx.StaticText(self, -1, "Centroid grid ref" ) carea_label = wx.StaticText(self, -1, "AREA") altbar_label = wx.StaticText(self, -1, "ALTBAR") aspbar_label = wx.StaticText(self, -1, "ASPBAR") aspvar_label = wx.StaticText(self, -1, "ASPVAR") bfihost_label = wx.StaticText(self, -1, "BFIHOST") dplbar_label = wx.StaticText(self, -1, "DPLBAR") dpsbar_label = wx.StaticText(self, -1, "DPSBAR") farl_label = wx.StaticText(self, -1, "FARL") fpext_label = wx.StaticText(self, -1, "FPEXT") ldp_label = wx.StaticText(self, -1, "LDP") propwet_label = wx.StaticText(self, -1, "PROPWET") saar_label = wx.StaticText(self, -1, "SAAR") sprhost_label = wx.StaticText(self, -1, "SPRHOST") urbconc1990_label = wx.StaticText(self, -1, "URBCONC1990") urbconc2000_label = wx.StaticText(self, -1, "URBCONC2000") urbext1990_label = wx.StaticText(self, -1, "URBEXT1990") urbext2000_label = wx.StaticText(self, -1, "URBEXT2000") urbloc1990_label = wx.StaticText(self, -1, "URBLOC1990") urbloc2000_label = wx.StaticText(self, -1, "URBLOC2000") chnl_width_label = wx.StaticText(self, -1, "Channel width") assessment_year_label = wx.StaticText(self, -1, "Assessment year") self.outlet_grid = wx.TextCtrl(self, -1, "GB") self.outlet_x = wx.TextCtrl(self, -1, "0") self.outlet_y = wx.TextCtrl(self, -1, "0") self.centroid_grid = wx.TextCtrl(self, -1, "GB") self.centroid_x = wx.TextCtrl(self, -1, "0") self.centroid_y = wx.TextCtrl(self, -1, "0") self.carea = wx.TextCtrl(self, -1, "0") self.altbar = wx.TextCtrl(self, -1, "0") self.aspbar = wx.TextCtrl(self, -1, "0") self.aspvar = wx.TextCtrl(self, -1, "0") self.bfihost = wx.TextCtrl(self, -1, "0") self.dplbar = wx.TextCtrl(self, -1, "0") self.dpsbar = wx.TextCtrl(self, -1, "0") self.farl = wx.TextCtrl(self, -1, "0") self.fpext = wx.TextCtrl(self, -1, "0") self.ldp = wx.TextCtrl(self, -1, "0") self.propwet = wx.TextCtrl(self, -1, "0") self.saar = wx.TextCtrl(self, -1, "0") self.sprhost = wx.TextCtrl(self, -1, "0") self.urbconc1990 = wx.TextCtrl(self, -1, "0") self.urbconc2000 = wx.TextCtrl(self, -1, "0") self.urbext1990 = wx.TextCtrl(self, -1, "0") self.urbext2000 = wx.TextCtrl(self, -1, "0") self.urbloc1990 = wx.TextCtrl(self, -1, "0") self.urbloc2000 = wx.TextCtrl(self, -1, "0") self.chnl_width = wx.TextCtrl(self, -1, "None") self.assessment_year = wx.TextCtrl(self, -1, time.asctime(time.localtime())[-4:]) self.outlet_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.centroid_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.carea_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.altbar_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.aspbar_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.aspvar_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.bfihost_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.dplbar_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.dpsbar_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.farl_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.fpext_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.ldp_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.propwet_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.saar_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.sprhost_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.urbconc1990_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.urbconc2000_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.urbext1990_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.urbext2000_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.urbloc1990_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.urbloc2000_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.chnl_width_note = wx.TextCtrl(self, -1, "",size=(200,25)) self.load_btn = wx.Button(self, -1, ' Load cds ') self.cds_notes = wx.TextCtrl(self, -1, "Your notes", size=(500, 100), style=wx.TE_MULTILINE) # Assign actions to buttons self.load_btn.Bind(wx.EVT_BUTTON, self.onLoadCds) # Assign actions to update of cds fields self.outlet_grid.Bind(wx.EVT_TEXT,self.onChangeCds) self.outlet_x.Bind(wx.EVT_TEXT,self.onChangeCds) self.outlet_y.Bind(wx.EVT_TEXT,self.onChangeCds) self.centroid_grid.Bind(wx.EVT_TEXT,self.onChangeCds) self.centroid_x.Bind(wx.EVT_TEXT,self.onChangeCds) self.centroid_y.Bind(wx.EVT_TEXT,self.onChangeCds) self.carea.Bind(wx.EVT_TEXT,self.onChangeCds) self.altbar.Bind(wx.EVT_TEXT,self.onChangeCds) self.aspbar.Bind(wx.EVT_TEXT,self.onChangeCds) self.aspvar.Bind(wx.EVT_TEXT,self.onChangeCds) self.bfihost.Bind(wx.EVT_TEXT,self.onChangeCds) self.dplbar.Bind(wx.EVT_TEXT,self.onChangeCds) self.dpsbar.Bind(wx.EVT_TEXT,self.onChangeCds) self.farl.Bind(wx.EVT_TEXT,self.onChangeCds) self.fpext.Bind(wx.EVT_TEXT,self.onChangeCds) self.ldp.Bind(wx.EVT_TEXT,self.onChangeCds) self.propwet.Bind(wx.EVT_TEXT,self.onChangeCds) self.saar.Bind(wx.EVT_TEXT,self.onChangeCds) self.sprhost.Bind(wx.EVT_TEXT,self.onChangeCds) self.urbconc1990.Bind(wx.EVT_TEXT,self.onChangeCds) self.urbconc2000.Bind(wx.EVT_TEXT,self.onChangeCds) self.urbext1990.Bind(wx.EVT_TEXT,self.onChangeCds) self.urbext2000.Bind(wx.EVT_TEXT,self.onChangeCds) self.urbloc1990.Bind(wx.EVT_TEXT,self.onChangeCds) self.urbloc2000.Bind(wx.EVT_TEXT,self.onChangeCds) self.chnl_width.Bind(wx.EVT_TEXT,self.onChangeCds) # use gridbagsizer for layout of widgets sizer = wx.GridBagSizer(vgap=1, hgap=10) #sizer.Add(self.title_label,pos=(0,0)) sizer.Add(outlet_label, pos=(1, 0)) sizer.Add(centroid_label, pos=(2, 0)) sizer.Add(carea_label, pos=(3, 0)) sizer.Add(altbar_label, pos=(4, 0)) sizer.Add(aspbar_label, pos=(5, 0)) sizer.Add(aspvar_label, pos=(6, 0)) sizer.Add(bfihost_label, pos=(7,0)) sizer.Add(dplbar_label, pos=(8, 0)) sizer.Add(dpsbar_label, pos=(9, 0)) sizer.Add(farl_label, pos=(10, 0)) sizer.Add(fpext_label, pos=(11, 0)) sizer.Add(ldp_label, pos=(12, 0)) sizer.Add(propwet_label, pos=(13, 0)) sizer.Add(saar_label, pos=(14, 0)) sizer.Add(sprhost_label, pos=(15, 0)) sizer.Add(urbconc1990_label, pos=(16, 0)) sizer.Add(urbconc2000_label, pos=(17, 0)) sizer.Add(urbext1990_label, pos=(18, 0)) sizer.Add(urbext2000_label, pos=(19, 0)) sizer.Add(urbloc1990_label, pos=(20, 0)) sizer.Add(urbloc2000_label, pos=(21, 0)) sizer.Add(chnl_width_label, pos=(22, 0)) sizer.Add(assessment_year_label, pos=(23, 0)) sizer.Add(self.outlet_grid, pos=(1, 1)) sizer.Add(self.outlet_x, pos=(1, 2)) sizer.Add(self.outlet_y, pos=(1, 3)) sizer.Add(self.centroid_grid, pos=(2, 1)) sizer.Add(self.centroid_x, pos=(2, 2)) sizer.Add(self.centroid_y, pos=(2, 3)) sizer.Add(self.carea, pos=(3, 1)) sizer.Add(self.altbar, pos=(4, 1)) sizer.Add(self.aspbar, pos=(5, 1)) sizer.Add(self.aspvar, pos=(6, 1)) sizer.Add(self.bfihost, pos=(7,1)) sizer.Add(self.dplbar, pos=(8, 1)) sizer.Add(self.dpsbar, pos=(9, 1)) sizer.Add(self.farl, pos=(10, 1)) sizer.Add(self.fpext, pos=(11, 1)) sizer.Add(self.ldp, pos=(12, 1)) sizer.Add(self.propwet, pos=(13, 1)) sizer.Add(self.saar, pos=(14, 1)) sizer.Add(self.sprhost, pos=(15, 1)) sizer.Add(self.urbconc1990, pos=(16, 1)) sizer.Add(self.urbconc2000, pos=(17, 1)) sizer.Add(self.urbext1990, pos=(18, 1)) sizer.Add(self.urbext2000, pos=(19, 1)) sizer.Add(self.urbloc1990, pos=(20, 1)) sizer.Add(self.urbloc2000, pos=(21, 1)) sizer.Add(self.chnl_width, pos=(22, 1)) sizer.Add(self.assessment_year, pos=(23, 1)) sizer.Add(self.outlet_note, pos=(1, 4)) sizer.Add(self.centroid_note, pos=(2, 4)) sizer.Add(self.carea_note, pos=(3, 4)) sizer.Add(self.altbar_note, pos=(4, 4)) sizer.Add(self.aspbar_note, pos=(5, 4)) sizer.Add(self.aspvar_note, pos=(6, 4)) sizer.Add(self.bfihost_note, pos=(7,4)) sizer.Add(self.dplbar_note, pos=(8, 4)) sizer.Add(self.dpsbar_note, pos=(9, 4)) sizer.Add(self.farl_note, pos=(10, 4)) sizer.Add(self.fpext_note, pos=(11, 4)) sizer.Add(self.ldp_note, pos=(12, 4)) sizer.Add(self.propwet_note, pos=(13, 4)) sizer.Add(self.saar_note, pos=(14, 4)) sizer.Add(self.sprhost_note, pos=(15, 4)) sizer.Add(self.urbconc1990_note, pos=(16, 4)) sizer.Add(self.urbconc2000_note, pos=(17, 4)) sizer.Add(self.urbext1990_note, pos=(18, 4)) sizer.Add(self.urbext2000_note, pos=(19, 4)) sizer.Add(self.urbloc1990_note, pos=(20, 4)) sizer.Add(self.urbloc2000_note, pos=(21, 4)) sizer.Add(self.chnl_width_note, pos=(22, 4)) sizer.Add(self.load_btn, pos=(24, 1), span=(1, 1)) sizer.Add(self.cds_notes, pos=(25, 0), span=(1,5)) # use boxsizer to add border around sizer border = wx.BoxSizer() border.Add(sizer, 0, wx.ALL, 20) self.SetSizerAndFit(border) self.Fit() def onLoadCds(self,event): loadBox = wx.FileDialog(self,"Open cds file", "", "", "Catchment descriptor files (*.csv;*.cd3)|*.csv;*.cd3", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if loadBox.ShowModal() == wx.ID_OK: filePath = loadBox.GetPath() self.inside_load = True self.syncCdsTab(filePath) try: test = config.analysis.catchment.pot_records except AttributeError: config.analysis.catchment.pot_records = None loadBox.Destroy() self.inside_load=False self.Refresh() self.Update() def onChangeCds(self,event): if self.inside_load is False: try: config.analysis.catchment.country = str(self.outlet_grid.GetValue()) except: pass try: config.analysis.catchment.descriptors.ihdtm_ngr.x = int(self.outlet_x.GetValue()) except: pass try: config.analysis.catchment.descriptors.ihdtm_ngr.y = int(self.outlet_y.GetValue()) except: pass try: config.analysis.catchment.descriptors.centroid_ngr.x = int(self.centroid_x.GetValue()) except: pass try: config.analysis.catchment.descriptors.centroid_ngr.y = int(self.centroid_y.GetValue()) except: pass try: config.analysis.catchment.descriptors.centroid_ngr = Point(int(self.centroid_x.GetValue()), int(self.centroid_y.GetValue())) except: pass try: config.analysis.catchment.descriptors.dtm_area = float(self.carea.GetValue()) except: pass try: config.analysis.catchment.descriptors.altbar = float(self.altbar.GetValue()) except: pass try: config.analysis.catchment.descriptors.aspbar = float(self.aspbar.GetValue()) except: pass try: config.analysis.catchment.descriptors.aspvar = float(self.aspvar.GetValue()) except: pass try: config.analysis.catchment.descriptors.bfihost = float(self.bfihost.GetValue()) except: pass try: config.analysis.catchment.descriptors.dplbar = float(self.dplbar.GetValue()) except: pass try: config.analysis.catchment.descriptors.dpsbar = float(self.dpsbar.GetValue()) except: pass try: config.analysis.catchment.descriptors.farl = float(self.farl.GetValue()) except: pass try: config.analysis.catchment.descriptors.ldp = float(self.ldp.GetValue()) except: pass try: config.analysis.catchment.descriptors.propwet = float(self.propwet.GetValue()) except: pass try: config.analysis.catchment.descriptors.saar = float(self.saar.GetValue()) except: pass try: config.analysis.catchment.descriptors.sprhost = float(self.sprhost.GetValue()) except: pass try: config.analysis.catchment.descriptors.fpext = float(self.fpext.GetValue()) except: pass try: config.analysis.catchment.descriptors.urbconc1990 = float(self.urbconc1990.GetValue()) except: pass try: config.analysis.catchment.descriptors.urbext1990 = float(self.urbext1990.GetValue()) except: pass try: config.analysis.catchment.descriptors.urbloc1990 = float(self.urbloc1990.GetValue()) except: pass try: config.analysis.catchment.descriptors.urbloc2000 = float(self.urbloc2000.GetValue()) except: pass try: config.analysis.catchment.descriptors.urbconc2000 = float(self.urbconc2000.GetValue()) except: pass try: config.analysis.catchment.descriptors.urbext2000 = float(self.urbext2000.GetValue()) except: pass try: config.analysis.catchment.channel_width = float(self.chnl_width.GetValue()) except: pass def syncCdsTab(self,filePath): config.analysis.cd3_file_path = filePath config.analysis.catchment = load_catchment(filePath) self.outlet_grid.SetLabel(str(config.analysis.catchment.country)) self.outlet_x.SetLabel(str(config.analysis.catchment.descriptors.ihdtm_ngr.x)) self.outlet_y.SetLabel(str(config.analysis.catchment.descriptors.ihdtm_ngr.y)) try: self.centroid_grid.SetLabel(str(config.analysis.catchment.country)) self.centroid_x.SetLabel(str(config.analysis.catchment.descriptors.centroid_ngr.x)) self.centroid_y.SetLabel(str(config.analysis.catchment.descriptors.centroid_ngr.y)) except: self.centroid_grid.SetLabel(str('-')) self.centroid_x.SetLabel(str('-')) self.centroid_y.SetLabel(str('-')) self.carea.SetLabel(str(config.analysis.catchment.descriptors.dtm_area)) self.altbar.SetLabel(str(config.analysis.catchment.descriptors.altbar)) self.aspbar.SetLabel(str(config.analysis.catchment.descriptors.aspbar)) self.aspvar.SetLabel(str(config.analysis.catchment.descriptors.aspvar)) self.bfihost.SetLabel(str(config.analysis.catchment.descriptors.bfihost)) self.dplbar.SetLabel(str(config.analysis.catchment.descriptors.dplbar)) self.dpsbar.SetLabel(str(config.analysis.catchment.descriptors.dpsbar)) self.farl.SetLabel(str(config.analysis.catchment.descriptors.farl)) self.ldp.SetLabel(str(config.analysis.catchment.descriptors.ldp)) self.propwet.SetLabel(str(config.analysis.catchment.descriptors.propwet)) self.saar.SetLabel(str(config.analysis.catchment.descriptors.saar)) self.sprhost.SetLabel(str(config.analysis.catchment.descriptors.sprhost)) try: self.fpext.SetLabel(str(config.analysis.catchment.descriptors.fpext)) except: self.fpext.SetLabel(str('-')) try: self.urbconc1990.SetLabel(str(config.analysis.catchment.descriptors.urbconc1990)) self.urbext1990.SetLabel(str(config.analysis.catchment.descriptors.urbext1990)) self.urbloc1990.SetLabel(str(config.analysis.catchment.descriptors.urbloc1990)) except: self.urbconc1990.SetLabel(str('-')) self.urbext1990.SetLabel(str('-')) self.urbloc1990.SetLabel(str('-')) try: self.urbloc2000.SetLabel(str(config.analysis.catchment.descriptors.urbloc2000)) self.urbconc2000.SetLabel(str(config.analysis.catchment.descriptors.urbconc2000)) self.urbext2000.SetLabel(str(config.analysis.catchment.descriptors.urbext2000)) except: self.urbloc2000.SetLabel(str('-')) self.urbconc2000.SetLabel(str('-')) self.urbext2000.SetLabel(str('-'))
gpl-3.0
mlhenderson/data_api
lib/doekbase/data_api/tests/test_memory_monitor.py
2
3276
import logging import sys import time import unittest from doekbase.data_api.util import MonitorMemory, get_logger, basic_config _log = get_logger(__name__) alerted = {} MB = 1024 * 1024 def icanhaz_alert(mm, avail, thresh, name): assert avail < thresh alerted[name] = avail _log.debug('\nalerted: {:d} MB'.format(thresh / MB)) def memory_hog(name): _log.debug('run memory hog until alert {}'.format(name)) a, i = [], 0 while 1: a.append(['x'] * 1000000) if _log.isEnabledFor(logging.DEBUG): sys.stdout.write('{:12d} MB\r'.format(len(a))) sys.stdout.flush() if alerted.get(name, False): break # allow other threads in, once in a while i += 1 if i == 100: i = 0 time.sleep(0.1) class MyTestCase(unittest.TestCase): def test_anyalert(self): """test that alerting for memory works at all""" num_mb = 1000000 mm = MonitorMemory() # call 'alert' when memory goes below a really high amount mm.add_alert(num_mb, icanhaz_alert, 'key') # run in a thread mm.start() while 1: time.sleep(0.5) if alerted.get('key', False): break # print('stopping..') mm.stop() mm.join() # check that memory is at the right level self.assertLess(alerted['key'], num_mb * MB) # print('stopped. avail: {} MB'.format(alerted['key']/1024/1024)) @unittest.skipIf(True, "skip memory test") def test_basic(self): """one memory alert""" num_mb = 10000 mm = MonitorMemory() # call 'alert' when memory goes below 10GB mm.add_alert(num_mb, icanhaz_alert, 'key') # run in a thread mm.start() memory_hog('key') # print('stopping..') mm.stop() mm.join() # check that memory is at the right level self.assertLess(alerted['key'], num_mb * MB) # print('stopped. avail: {} MB'.format(alerted['key']/1024/1024)) @unittest.skipIf(True, "skip memory test") def test_multi(self): """multiple memory alerts""" num_mb = [10000, 9000, 8000] mm = MonitorMemory() # add multiple alerts for mb in num_mb: _log.debug('add alert for {} MB'.format(mb)) mm.add_alert(mb, icanhaz_alert, 'a{}'.format(mb)) # run in a thread mm.start() min_key = 'a{}'.format(min(num_mb)) memory_hog(min_key) _log.debug('stopping..') mm.stop() mm.join() # check that all alerts fired for mb in num_mb: self.assertIn('a{}'.format(mb), alerted, 'missing key') # check that memory is at the right level self.assertLess(alerted[min_key], min(num_mb) * MB) _log.debug('stopped. avail: {} MB'.format(alerted[min_key] / MB)) if __name__ == '__main__': # set DEBUG if number of '-v' options is 2 or more num_vb = sum([sum([1 if c == 'v' else 0 for c in list(opt)]) for opt in sys.argv if opt.startswith('-v')]) if num_vb > 1: basic_config(logging.DEBUG) _log.setLevel(logging.DEBUG) # run unittest.main()
mit
killerstorm/ngcccbase
ngcccbase/txdb.py
4
10324
from time import time from urllib2 import HTTPError import threading import os from pycoin.encoding import double_sha256 from coloredcoinlib.store import DataStore, DataStoreConnection, PersistentDictStore, unwrap1 from ngcccbase.services.blockchain import BlockchainInfoInterface from txcons import RawTxSpec from blockchain import VerifiedBlockchainState TX_STATUS_UNKNOWN = 0 TX_STATUS_UNCONFIRMED = 1 TX_STATUS_CONFIRMED = 2 TX_STATUS_INVALID = 3 create_transaction_table = """\ CREATE TABLE tx_data ( id INTEGER PRIMARY KEY AUTOINCREMENT, txhash TEXT, data TEXT, status INTEGER, block_height INTEGER ); """ class TxDataStore(DataStore): def __init__(self, conn): super(TxDataStore, self).__init__(conn) if not self.table_exists('tx_data'): self.execute(create_transaction_table) self.execute( "CREATE UNIQUE INDEX tx_data_txhash ON tx_data (txhash)") if not self.column_exists('tx_data', 'block_height'): self.execute( "ALTER TABLE tx_data ADD COLUMN block_height INTEGER") def purge_tx_data(self): self.execute("DELETE FROM tx_data") def add_tx(self, txhash, txdata, status=TX_STATUS_UNKNOWN): return self.execute( "INSERT INTO tx_data (txhash, data, status) VALUES (?, ?, ?)", (txhash, txdata, status)) def set_tx_status(self, txhash, status): self.execute("UPDATE tx_data SET status = ? WHERE txhash = ?", (status, txhash)) def get_tx_status(self, txhash): return unwrap1(self.execute("SELECT status FROM tx_data WHERE txhash = ?", (txhash, )).fetchone()) def get_tx_by_hash(self, txhash): return self.execute("SELECT * FROM tx_data WHERE txhash = ?", (txhash, )).fetchone() def get_all_tx_hashes(self): return map(unwrap1, self.execute("SELECT txhash FROM tx_data").fetchall()) def set_block_height(self, txhash, height): self.execute("UPDATE tx_data SET block_height = ? WHERE txhash = ?", (height, txhash)) def reset_from_height(self, height): self.execute("UPDATE tx_data SET status = 0 \ WHERE (block_height >= ?) OR (block_height IS NULL)", (height,)) class BaseTxDb(object): def __init__(self, model, config): self.model = model self.store = TxDataStore(self.model.store_conn.conn) self.last_status_check = dict() self.recheck_interval = 60 self.bs = self.model.get_blockchain_state() def purge_tx_db(self): self.store.purge_tx_data() def get_all_tx_hashes(self): return self.store.get_all_tx_hashes() def get_tx_by_hash(self, txhash): return self.store.get_tx_by_hash(txhash) def update_tx_block_height(self, txhash, status): if status == TX_STATUS_CONFIRMED: try: block_hash, _ = self.bs.get_tx_blockhash(txhash) height = self.bs.get_block_height(block_hash) except: return self.store.set_block_height(txhash, height) def add_raw_tx(self, raw_tx, status=TX_STATUS_UNCONFIRMED): return self.add_tx(raw_tx.get_hex_txhash(), raw_tx.get_hex_tx_data(), raw_tx, status) def add_tx_by_hash(self, txhash, status=None): bs = self.model.get_blockchain_state() txdata = bs.get_raw(txhash) raw_tx = RawTxSpec.from_tx_data(self.model, txdata.decode('hex')) return self.add_tx(txhash, txdata, raw_tx, status) def add_tx(self, txhash, txdata, raw_tx, status=None): entries = self.model.tx_history.entries if (txhash not in entries or # new transaction not entries[txhash]['txtime']): # update unconfirmed self.model.tx_history.add_entry_from_tx(raw_tx) if not self.store.get_tx_by_hash(txhash): if not status: status = self.identify_tx_status(txhash) self.store.add_tx(txhash, txdata, status) self.update_tx_block_height(txhash, status) self.last_status_check[txhash] = time() self.model.get_coin_manager().apply_tx(txhash, raw_tx) return True else: old_status = self.store.get_tx_status(txhash) new_status = self.maybe_recheck_tx_status(txhash, old_status) return old_status != new_status def recheck_tx_status(self, txhash): status = self.identify_tx_status(txhash) self.store.set_tx_status(txhash, status) self.update_tx_block_height(txhash, status) return status def maybe_recheck_tx_status(self, txhash, status): if status == TX_STATUS_CONFIRMED: # do not recheck those which are already confirmed return status if (time() - self.last_status_check.get(txhash, 0)) < self.recheck_interval: return status status = self.recheck_tx_status(txhash) self.last_status_check[txhash] = time() return status def is_tx_valid(self, txhash): status = self.store.get_tx_status(txhash) if status == TX_STATUS_CONFIRMED: return True status = self.maybe_recheck_tx_status(txhash, status) return status != TX_STATUS_INVALID def is_tx_confirmed(self, txhash): status = self.store.get_tx_status(txhash) if status != TX_STATUS_CONFIRMED: status = self.maybe_recheck_tx_status(txhash, status) return status == TX_STATUS_CONFIRMED class NaiveTxDb(BaseTxDb): """Native TxDb trusts results of get_blockchain_state""" def identify_tx_status(self, txhash): block_hash, in_mempool = self.model.get_blockchain_state().\ get_tx_blockhash(txhash) if block_hash: return TX_STATUS_CONFIRMED elif in_mempool: return TX_STATUS_UNCONFIRMED else: return TX_STATUS_INVALID class TrustingTxDb(BaseTxDb): """TxDb which trusts confirmation data it gets from an external source""" def __init__(self, model, config, get_tx_confirmations): super(TrustingTxDb, self).__init__(model, config) self.confirmed_txs = set() self.get_tx_confirmations = get_tx_confirmations def identify_tx_status(self, txhash): if txhash in self.confirmed_txs: return TX_STATUS_CONFIRMED confirmations = self.get_tx_confirmations(txhash) if confirmations > 0: self.confirmed_txs.add(txhash) return TX_STATUS_CONFIRMED elif confirmations == 0: return TX_STATUS_UNCONFIRMED else: # check if BlockchainState is aware of it block_hash, in_mempool = self.model.get_blockchain_state().\ get_tx_blockhash(txhash) if block_hash or in_mempool: return TX_STATUS_UNCONFIRMED else: return TX_STATUS_INVALID class VerifiedTxDb(BaseTxDb): def __init__(self, model, config): super(VerifiedTxDb, self).__init__(model, config) self.bs = self.model.get_blockchain_state() self.vbs = VerifiedBlockchainState( self.bs, self, config.get('testnet', False), os.path.dirname(self.model.store_conn.path) ) self.vbs.start() self.lock = threading.Lock() self.verified_tx = {} def __del__(self): if self.vbs: self.vbs.stop() def _get_merkle_root(self, merkle_s, start_hash, pos): hash_decode = lambda x: x.decode('hex')[::-1] hash_encode = lambda x: x[::-1].encode('hex') h = hash_decode(start_hash) # i is the "level" or depth of the binary merkle tree. # item is the complementary hash on the merkle tree at this level for i, item in enumerate(merkle_s): # figure out if it's the left item or right item at this level if pos >> i & 1: # right item (odd at this level) h = double_sha256(hash_decode(item) + h) else: # left item (even at this level) h = double_sha256(h + hash_decode(item)) return hash_encode(h) def _verify_merkle(self, txhash): result = self.bs.get_merkle(txhash) merkle, tx_height, pos = result.get('merkle'), \ result.get('block_height'), result.get('pos') merkle_root = self._get_merkle_root(merkle, txhash, pos) header = self.vbs.get_header(tx_height) if header is None: return False if header.get('merkle_root') != merkle_root: return False with self.lock: self.verified_tx[txhash] = tx_height return True def update_tx_block_height(self, txhash, status): with self.lock: if txhash in self.verified_tx: self.store.set_block_height(txhash, self.verified_tx[txhash]) def drop_from_height(self, height): with self.lock: self.verified_tx = {key: value for key, value in self.verified_tx.items() if value < height} def get_confirmations(self, txhash): with self.lock: if txhash in self.verified_tx: height = self.verified_tx[txhash] return self.vbs.height - height + 1 else: return None def identify_tx_status(self, txhash): block_hash, in_mempool = self.bs.get_tx_blockhash(txhash) if (not block_hash) and (not in_mempool): return TX_STATUS_INVALID if not block_hash: return TX_STATUS_UNCONFIRMED confirmations = self.get_confirmations(txhash) if confirmations is None: verified = self._verify_merkle(txhash) if verified: return self.identify_tx_status(txhash) else: return TX_STATUS_UNCONFIRMED if confirmations == 0: return TX_STATUS_UNCONFIRMED return TX_STATUS_CONFIRMED
mit
rmeertens/paparazzi
sw/tools/parrot/parrot_utils.py
11
3082
# # Copyright (C) 2012-2014 The Paparazzi Team # # This file is part of Paparazzi. # # Paparazzi is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # Paparazzi 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 paparazzi; see the file COPYING. If not, see # <http://www.gnu.org/licenses/>. # from __future__ import print_function import socket import telnetlib import sys from ftplib import FTP import ftplib # Check if IP is valid def is_ip(address): try: socket.inet_aton(address) ip = True except socket.error: ip = False return ip # Helper function def split_into_path_and_file(name): if name.count('/') <= 0: return ["./", name] return name.rsplit('/', 1) # Execute a command def execute_command(tn, command): tn.write(command + '\n') return tn.read_until('# ')[len(command) + 2:-4] # Check the version def check_version(tn, directory): return execute_command(tn, 'cat ' + directory + '/version.txt') # Check what currently is running on the drone def check_running(tn): ps_aux = execute_command(tn, 'ps') running = "" if 'dragon-prog' in ps_aux: running += ' Native (dragon-prog),' if 'ap.elf' in ps_aux: running += ' Paparazzi (ap.elf),' if 'program.elf' in ps_aux: running += ' Native (program.elf),' if 'gst-launch' in ps_aux: running += ' GStreamer (gst-launch)' return running[1:] # Check the filesystem def check_filesystem(tn): return execute_command(tn, 'df -h') # Reboot the drone def reboot(tn): execute_command(tn, 'reboot') # Upload ftp and catch memory-full error def uploadfile(ftp, filename, content): try: ftp.storbinary("STOR " + filename, content) except ftplib.error_temp: print("FTP UPLOAD ERROR: Uploading FAILED: Probably your drone onboard storage memory is full. Remove old JPG or other data?") sys.exit() except: print("FTP UPLOAD ERROR: Maybe your drone onboard storage memory is full? Remove old JPG or other data?)", sys.exc_info()[0]) sys.exit() # Connect with telnet and ftp, wait until login def connect(host): try: tn = telnetlib.Telnet(host, timeout=3) ftp = FTP(host) ftp.login() tn.read_until('# ') return tn, ftp except: print('Could not connect to Parrot UAV (host: ' + host + ')') if host == '192.168.42.1': print("Check whether your WiFi is connected and don't forget pressing the power button 4 times after the Bebop has booted!") exit(2) # Close the telnet and ftp def disconnect(tn, ftp): tn.close() ftp.close()
gpl-2.0
KAsante95/osf.io
website/addons/base/logger.py
13
2120
import abc class AddonNodeLogger(object): """Helper class for adding correctly-formatted addon logs to nodes. :param Node node: The node to add logs to :param Auth auth: Authorization of the person who did the action. """ __metaclass__ = abc.ABCMeta @abc.abstractproperty def addon_short_name(self): pass def _log_params(self): node_settings = self.node.get_addon(self.addon_short_name, deleted=True) return { 'project': self.node.parent_id, 'node': self.node._primary_key, 'folder_id': node_settings.folder_id, 'folder_name': node_settings.folder_name, 'folder': node_settings.folder_path } def __init__(self, node, auth, path=None): self.node = node self.auth = auth self.path = path def log(self, action, extra=None, save=False): """Log an event. Wraps the Node#add_log method, automatically adding relevant parameters and prefixing log events with addon_short_name. :param str action: Log action. Should be a class constant from NodeLog. :param dict extra: Extra parameters to add to the ``params`` dict of the new NodeLog. """ params = self._log_params() # If logging a file-related action, add the file's view and download URLs if self.path: params.update({ 'urls': { 'view': self.node.web_url_for('addon_view_or_download_file', path=self.path, provider=self.addon_short_name), 'download': self.node.web_url_for( 'addon_view_or_download_file', path=self.path, provider=self.addon_short_name ) }, 'path': self.path, }) if extra: params.update(extra) self.node.add_log( action="{0}_{1}".format(self.addon_short_name, action), params=params, auth=self.auth ) if save: self.node.save()
apache-2.0
pfig/CmdrKeen
cmdrkeen/config.py
1
3434
import json import logging logger = logging.getLogger(__name__) class Config(object): """A configuration for a Commander Keen bot This will read and parse a configuration file containing parameters for a Commander Keen Slack bot. Configurations are made of a set of JSON-encoded variables. Commander Keen understands the following parameters (variables marked with * are mandatory):: * ``slack_token``: the bot's token (*) * ``data_file``: the path for the SQLite3 file containing factoids (*) * ``background``: whether to run as a daemon, boolean (default: true) * ``log_file``: the path for the log file (default: None) * ``debug``: whether to run in debug mode, boolean (default: true) * ``plugins``: an object defining the plugins to load (default: none) The ``plugins`` object is a map of name -> configuration. Commander Keen will try to load the corresponding package from ``cmdrkeen.plugins.name`` and configure it accordingly, by passing the configuration object to the constructor. As an example, consider the following configuration stored in the file ``keen.json``:: { "slack_token": "xoxb-super-sekrit-token", "data_file": "brain.sqlite3", "background": false, "plugins": { "weather": { "default_location": "London, UK" } } } This would run the bot in the foreground and try to load the weather plugin from ``cmdrkeen.plugins.weather``, with the given configuration object. """ def __init__(self, file_path): """Constructor Builds a configuration object given a file path. :param file_path: the path to the configuration file. :returns: a ``Config`` object initialised with the given file path. """ self.file = file_path self.slack_token = None self.data_file = None self.background = True self.log_file = None self.debug = True self.plugins = None self.__configure_from_file(file_path) def __configure_from_file(self, file_path): """Configure the bot from a file Reads ``file_path`` and configures the bot accordingly. """ with open(file_path, 'r') as config: try: json_cfg = json.loads(config.read()) except Exception as e: logger.error('Error reading configuration ({}): {}'.format( file_path, e)) raise e slack_token = json_cfg.get('slack_token', None) data_file = json_cfg.get('data_file', None) if not (slack_token and data_file): logger.error('Slack token and data file required') raise ValueError self.slack_token = slack_token self.data_file = data_file self.__configure_optional(json_cfg) def __configure_optional(self, json_cfg): """Configure optional parameters Given a configuration object, configures the optional parameters for the bot. """ self.background = json_cfg.get('background', True) self.debug = json_cfg.get('debug', True) self.log_file = json_cfg.get('log_file', None) self.plugins = json_cfg.get('plugins', None)
mit
ned14/BEurtle
Installer/test/ZSI-2.1-a1/ZSI/wstools/test/test_wsdl.py
17
5500
#!/usr/bin/env python ############################################################################ # Joshua R. Boverhof, David W. Robertson, LBNL # See LBNLCopyright for copyright notice! ########################################################################### import sys, unittest import ConfigParser from ZSI.wstools.Utility import DOM from ZSI.wstools.WSDLTools import WSDLReader from ZSI.wstools.TimeoutSocket import TimeoutError class WSDLToolsTestCase(unittest.TestCase): def __init__(self, methodName='runTest'): unittest.TestCase.__init__(self, methodName) def setUp(self): self.path = nameGenerator.next() print self.path sys.stdout.flush() def __str__(self): teststr = unittest.TestCase.__str__(self) if hasattr(self, "path"): return "%s: %s" % (teststr, self.path ) else: return "%s" % (teststr) def checkWSDLCollection(self, tag_name, component, key='name'): if self.wsdl is None: return definition = self.wsdl.document.documentElement version = DOM.WSDLUriToVersion(definition.namespaceURI) nspname = DOM.GetWSDLUri(version) for node in DOM.getElements(definition, tag_name, nspname): name = DOM.getAttr(node, key) comp = component[name] self.failUnlessEqual(eval('comp.%s' %key), name) def checkXSDCollection(self, tag_name, component, node, key='name'): for cnode in DOM.getElements(node, tag_name): name = DOM.getAttr(cnode, key) component[name] def test_all(self): try: if self.path[:7] == 'http://': self.wsdl = WSDLReader().loadFromURL(self.path) else: self.wsdl = WSDLReader().loadFromFile(self.path) except TimeoutError: print "connection timed out" sys.stdout.flush() return except: self.path = self.path + ": load failed, unable to start" raise try: self.checkWSDLCollection('service', self.wsdl.services) except: self.path = self.path + ": wsdl.services" raise try: self.checkWSDLCollection('message', self.wsdl.messages) except: self.path = self.path + ": wsdl.messages" raise try: self.checkWSDLCollection('portType', self.wsdl.portTypes) except: self.path = self.path + ": wsdl.portTypes" raise try: self.checkWSDLCollection('binding', self.wsdl.bindings) except: self.path = self.path + ": wsdl.bindings" raise try: self.checkWSDLCollection('import', self.wsdl.imports, key='namespace') except: self.path = self.path + ": wsdl.imports" raise try: for key in self.wsdl.types.keys(): schema = self.wsdl.types[key] self.failUnlessEqual(key, schema.getTargetNamespace()) definition = self.wsdl.document.documentElement version = DOM.WSDLUriToVersion(definition.namespaceURI) nspname = DOM.GetWSDLUri(version) for node in DOM.getElements(definition, 'types', nspname): for snode in DOM.getElements(node, 'schema'): tns = DOM.findTargetNS(snode) schema = self.wsdl.types[tns] self.schemaAttributesDeclarations(schema, snode) self.schemaAttributeGroupDeclarations(schema, snode) self.schemaElementDeclarations(schema, snode) self.schemaTypeDefinitions(schema, snode) except: self.path = self.path + ": wsdl.types" raise if self.wsdl.extensions: print 'No check for WSDLTools(%s) Extensions:' %(self.wsdl.name) for ext in self.wsdl.extensions: print '\t', ext def schemaAttributesDeclarations(self, schema, node): self.checkXSDCollection('attribute', schema.attr_decl, node) def schemaAttributeGroupDeclarations(self, schema, node): self.checkXSDCollection('group', schema.attr_groups, node) def schemaElementDeclarations(self, schema, node): self.checkXSDCollection('element', schema.elements, node) def schemaTypeDefinitions(self, schema, node): self.checkXSDCollection('complexType', schema.types, node) self.checkXSDCollection('simpleType', schema.types, node) def setUpOptions(section): cp = ConfigParser.ConfigParser() cp.read('config.txt') if not cp.sections(): print 'fatal error: configuration file config.txt not present' sys.exit(0) if not cp.has_section(section): print '%s section not present in configuration file, exiting' % section sys.exit(0) return cp, len(cp.options(section)) def getOption(cp, section): for name, value in cp.items(section): yield value def makeTestSuite(section='services_by_file'): global nameGenerator cp, numTests = setUpOptions(section) nameGenerator = getOption(cp, section) suite = unittest.TestSuite() for i in range(0, numTests): suite.addTest(unittest.makeSuite(WSDLToolsTestCase, 'test_')) return suite def main(): unittest.main(defaultTest="makeTestSuite") if __name__ == "__main__" : main()
lgpl-2.1
zwChan/VATEC
~/eb-virt/Lib/site-packages/jinja2/debug.py
335
11553
# -*- coding: utf-8 -*- """ jinja2.debug ~~~~~~~~~~~~ Implements the debug interface for Jinja. This module does some pretty ugly stuff with the Python traceback system in order to achieve tracebacks with correct line numbers, locals and contents. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import sys import traceback from types import TracebackType, CodeType from jinja2.utils import missing, internal_code from jinja2.exceptions import TemplateSyntaxError from jinja2._compat import iteritems, reraise, PY2 # on pypy we can take advantage of transparent proxies try: from __pypy__ import tproxy except ImportError: tproxy = None # how does the raise helper look like? try: exec("raise TypeError, 'foo'") except SyntaxError: raise_helper = 'raise __jinja_exception__[1]' except TypeError: raise_helper = 'raise __jinja_exception__[0], __jinja_exception__[1]' class TracebackFrameProxy(object): """Proxies a traceback frame.""" def __init__(self, tb): self.tb = tb self._tb_next = None @property def tb_next(self): return self._tb_next def set_next(self, next): if tb_set_next is not None: try: tb_set_next(self.tb, next and next.tb or None) except Exception: # this function can fail due to all the hackery it does # on various python implementations. We just catch errors # down and ignore them if necessary. pass self._tb_next = next @property def is_jinja_frame(self): return '__jinja_template__' in self.tb.tb_frame.f_globals def __getattr__(self, name): return getattr(self.tb, name) def make_frame_proxy(frame): proxy = TracebackFrameProxy(frame) if tproxy is None: return proxy def operation_handler(operation, *args, **kwargs): if operation in ('__getattribute__', '__getattr__'): return getattr(proxy, args[0]) elif operation == '__setattr__': proxy.__setattr__(*args, **kwargs) else: return getattr(proxy, operation)(*args, **kwargs) return tproxy(TracebackType, operation_handler) class ProcessedTraceback(object): """Holds a Jinja preprocessed traceback for printing or reraising.""" def __init__(self, exc_type, exc_value, frames): assert frames, 'no frames for this traceback?' self.exc_type = exc_type self.exc_value = exc_value self.frames = frames # newly concatenate the frames (which are proxies) prev_tb = None for tb in self.frames: if prev_tb is not None: prev_tb.set_next(tb) prev_tb = tb prev_tb.set_next(None) def render_as_text(self, limit=None): """Return a string with the traceback.""" lines = traceback.format_exception(self.exc_type, self.exc_value, self.frames[0], limit=limit) return ''.join(lines).rstrip() def render_as_html(self, full=False): """Return a unicode string with the traceback as rendered HTML.""" from jinja2.debugrenderer import render_traceback return u'%s\n\n<!--\n%s\n-->' % ( render_traceback(self, full=full), self.render_as_text().decode('utf-8', 'replace') ) @property def is_template_syntax_error(self): """`True` if this is a template syntax error.""" return isinstance(self.exc_value, TemplateSyntaxError) @property def exc_info(self): """Exception info tuple with a proxy around the frame objects.""" return self.exc_type, self.exc_value, self.frames[0] @property def standard_exc_info(self): """Standard python exc_info for re-raising""" tb = self.frames[0] # the frame will be an actual traceback (or transparent proxy) if # we are on pypy or a python implementation with support for tproxy if type(tb) is not TracebackType: tb = tb.tb return self.exc_type, self.exc_value, tb def make_traceback(exc_info, source_hint=None): """Creates a processed traceback object from the exc_info.""" exc_type, exc_value, tb = exc_info if isinstance(exc_value, TemplateSyntaxError): exc_info = translate_syntax_error(exc_value, source_hint) initial_skip = 0 else: initial_skip = 1 return translate_exception(exc_info, initial_skip) def translate_syntax_error(error, source=None): """Rewrites a syntax error to please traceback systems.""" error.source = source error.translated = True exc_info = (error.__class__, error, None) filename = error.filename if filename is None: filename = '<unknown>' return fake_exc_info(exc_info, filename, error.lineno) def translate_exception(exc_info, initial_skip=0): """If passed an exc_info it will automatically rewrite the exceptions all the way down to the correct line numbers and frames. """ tb = exc_info[2] frames = [] # skip some internal frames if wanted for x in range(initial_skip): if tb is not None: tb = tb.tb_next initial_tb = tb while tb is not None: # skip frames decorated with @internalcode. These are internal # calls we can't avoid and that are useless in template debugging # output. if tb.tb_frame.f_code in internal_code: tb = tb.tb_next continue # save a reference to the next frame if we override the current # one with a faked one. next = tb.tb_next # fake template exceptions template = tb.tb_frame.f_globals.get('__jinja_template__') if template is not None: lineno = template.get_corresponding_lineno(tb.tb_lineno) tb = fake_exc_info(exc_info[:2] + (tb,), template.filename, lineno)[2] frames.append(make_frame_proxy(tb)) tb = next # if we don't have any exceptions in the frames left, we have to # reraise it unchanged. # XXX: can we backup here? when could this happen? if not frames: reraise(exc_info[0], exc_info[1], exc_info[2]) return ProcessedTraceback(exc_info[0], exc_info[1], frames) def fake_exc_info(exc_info, filename, lineno): """Helper for `translate_exception`.""" exc_type, exc_value, tb = exc_info # figure the real context out if tb is not None: real_locals = tb.tb_frame.f_locals.copy() ctx = real_locals.get('context') if ctx: locals = ctx.get_all() else: locals = {} for name, value in iteritems(real_locals): if name.startswith('l_') and value is not missing: locals[name[2:]] = value # if there is a local called __jinja_exception__, we get # rid of it to not break the debug functionality. locals.pop('__jinja_exception__', None) else: locals = {} # assamble fake globals we need globals = { '__name__': filename, '__file__': filename, '__jinja_exception__': exc_info[:2], # we don't want to keep the reference to the template around # to not cause circular dependencies, but we mark it as Jinja # frame for the ProcessedTraceback '__jinja_template__': None } # and fake the exception code = compile('\n' * (lineno - 1) + raise_helper, filename, 'exec') # if it's possible, change the name of the code. This won't work # on some python environments such as google appengine try: if tb is None: location = 'template' else: function = tb.tb_frame.f_code.co_name if function == 'root': location = 'top-level template code' elif function.startswith('block_'): location = 'block "%s"' % function[6:] else: location = 'template' if PY2: code = CodeType(0, code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, code.co_consts, code.co_names, code.co_varnames, filename, location, code.co_firstlineno, code.co_lnotab, (), ()) else: code = CodeType(0, code.co_kwonlyargcount, code.co_nlocals, code.co_stacksize, code.co_flags, code.co_code, code.co_consts, code.co_names, code.co_varnames, filename, location, code.co_firstlineno, code.co_lnotab, (), ()) except Exception as e: pass # execute the code and catch the new traceback try: exec(code, globals, locals) except: exc_info = sys.exc_info() new_tb = exc_info[2].tb_next # return without this frame return exc_info[:2] + (new_tb,) def _init_ugly_crap(): """This function implements a few ugly things so that we can patch the traceback objects. The function returned allows resetting `tb_next` on any python traceback object. Do not attempt to use this on non cpython interpreters """ import ctypes from types import TracebackType if PY2: # figure out size of _Py_ssize_t for Python 2: if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'): _Py_ssize_t = ctypes.c_int64 else: _Py_ssize_t = ctypes.c_int else: # platform ssize_t on Python 3 _Py_ssize_t = ctypes.c_ssize_t # regular python class _PyObject(ctypes.Structure): pass _PyObject._fields_ = [ ('ob_refcnt', _Py_ssize_t), ('ob_type', ctypes.POINTER(_PyObject)) ] # python with trace if hasattr(sys, 'getobjects'): class _PyObject(ctypes.Structure): pass _PyObject._fields_ = [ ('_ob_next', ctypes.POINTER(_PyObject)), ('_ob_prev', ctypes.POINTER(_PyObject)), ('ob_refcnt', _Py_ssize_t), ('ob_type', ctypes.POINTER(_PyObject)) ] class _Traceback(_PyObject): pass _Traceback._fields_ = [ ('tb_next', ctypes.POINTER(_Traceback)), ('tb_frame', ctypes.POINTER(_PyObject)), ('tb_lasti', ctypes.c_int), ('tb_lineno', ctypes.c_int) ] def tb_set_next(tb, next): """Set the tb_next attribute of a traceback object.""" if not (isinstance(tb, TracebackType) and (next is None or isinstance(next, TracebackType))): raise TypeError('tb_set_next arguments must be traceback objects') obj = _Traceback.from_address(id(tb)) if tb.tb_next is not None: old = _Traceback.from_address(id(tb.tb_next)) old.ob_refcnt -= 1 if next is None: obj.tb_next = ctypes.POINTER(_Traceback)() else: next = _Traceback.from_address(id(next)) next.ob_refcnt += 1 obj.tb_next = ctypes.pointer(next) return tb_set_next # try to get a tb_set_next implementation if we don't have transparent # proxies. tb_set_next = None if tproxy is None: try: tb_set_next = _init_ugly_crap() except: pass del _init_ugly_crap
apache-2.0
cloakedcode/CouchPotatoServer
libs/suds/xsd/schema.py
192
14328
# This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) GNU Lesser General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # 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 Library Lesser General Public License for more details at # ( http://www.gnu.org/licenses/lgpl.html ). # # You should have received a copy of the GNU Lesser General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # written by: Jeff Ortel ( jortel@redhat.com ) """ The I{schema} module provides a intelligent representation of an XSD schema. The I{raw} model is the XML tree and the I{model} is the denormalized, objectified and intelligent view of the schema. Most of the I{value-add} provided by the model is centered around tranparent referenced type resolution and targeted denormalization. """ import suds.metrics from suds import * from suds.xsd import * from suds.xsd.sxbuiltin import * from suds.xsd.sxbasic import Factory as BasicFactory from suds.xsd.sxbuiltin import Factory as BuiltinFactory from suds.xsd.sxbase import SchemaObject from suds.xsd.deplist import DepList from suds.sax.element import Element from suds.sax import splitPrefix, Namespace from logging import getLogger log = getLogger(__name__) class SchemaCollection: """ A collection of schema objects. This class is needed because WSDLs may contain more then one <schema/> node. @ivar wsdl: A wsdl object. @type wsdl: L{suds.wsdl.Definitions} @ivar children: A list contained schemas. @type children: [L{Schema},...] @ivar namespaces: A dictionary of contained schemas by namespace. @type namespaces: {str:L{Schema}} """ def __init__(self, wsdl): """ @param wsdl: A wsdl object. @type wsdl: L{suds.wsdl.Definitions} """ self.wsdl = wsdl self.children = [] self.namespaces = {} def add(self, schema): """ Add a schema node to the collection. Schema(s) within the same target namespace are consolidated. @param schema: A schema object. @type schema: (L{Schema}) """ key = schema.tns[1] existing = self.namespaces.get(key) if existing is None: self.children.append(schema) self.namespaces[key] = schema else: existing.root.children += schema.root.children existing.root.nsprefixes.update(schema.root.nsprefixes) def load(self, options): """ Load the schema objects for the root nodes. - de-references schemas - merge schemas @param options: An options dictionary. @type options: L{options.Options} @return: The merged schema. @rtype: L{Schema} """ if options.autoblend: self.autoblend() for child in self.children: child.build() for child in self.children: child.open_imports(options) for child in self.children: child.dereference() log.debug('loaded:\n%s', self) merged = self.merge() log.debug('MERGED:\n%s', merged) return merged def autoblend(self): """ Ensure that all schemas within the collection import each other which has a blending effect. @return: self @rtype: L{SchemaCollection} """ namespaces = self.namespaces.keys() for s in self.children: for ns in namespaces: tns = s.root.get('targetNamespace') if tns == ns: continue for imp in s.root.getChildren('import'): if imp.get('namespace') == ns: continue imp = Element('import', ns=Namespace.xsdns) imp.set('namespace', ns) s.root.append(imp) return self def locate(self, ns): """ Find a schema by namespace. Only the URI portion of the namespace is compared to each schema's I{targetNamespace} @param ns: A namespace. @type ns: (prefix,URI) @return: The schema matching the namesapce, else None. @rtype: L{Schema} """ return self.namespaces.get(ns[1]) def merge(self): """ Merge the contained schemas into one. @return: The merged schema. @rtype: L{Schema} """ if len(self): schema = self.children[0] for s in self.children[1:]: schema.merge(s) return schema else: return None def __len__(self): return len(self.children) def __str__(self): return unicode(self).encode('utf-8') def __unicode__(self): result = ['\nschema collection'] for s in self.children: result.append(s.str(1)) return '\n'.join(result) class Schema: """ The schema is an objectification of a <schema/> (xsd) definition. It provides inspection, lookup and type resolution. @ivar root: The root node. @type root: L{sax.element.Element} @ivar baseurl: The I{base} URL for this schema. @type baseurl: str @ivar container: A schema collection containing this schema. @type container: L{SchemaCollection} @ivar children: A list of direct top level children. @type children: [L{SchemaObject},...] @ivar all: A list of all (includes imported) top level children. @type all: [L{SchemaObject},...] @ivar types: A schema types cache. @type types: {name:L{SchemaObject}} @ivar imports: A list of import objects. @type imports: [L{SchemaObject},...] @ivar elements: A list of <element/> objects. @type elements: [L{SchemaObject},...] @ivar attributes: A list of <attribute/> objects. @type attributes: [L{SchemaObject},...] @ivar groups: A list of group objects. @type groups: [L{SchemaObject},...] @ivar agrps: A list of attribute group objects. @type agrps: [L{SchemaObject},...] @ivar form_qualified: The flag indicating: (@elementFormDefault). @type form_qualified: bool """ Tag = 'schema' def __init__(self, root, baseurl, options, container=None): """ @param root: The xml root. @type root: L{sax.element.Element} @param baseurl: The base url used for importing. @type baseurl: basestring @param options: An options dictionary. @type options: L{options.Options} @param container: An optional container. @type container: L{SchemaCollection} """ self.root = root self.id = objid(self) self.tns = self.mktns() self.baseurl = baseurl self.container = container self.children = [] self.all = [] self.types = {} self.imports = [] self.elements = {} self.attributes = {} self.groups = {} self.agrps = {} if options.doctor is not None: options.doctor.examine(root) form = self.root.get('elementFormDefault') if form is None: self.form_qualified = False else: self.form_qualified = ( form == 'qualified' ) if container is None: self.build() self.open_imports(options) log.debug('built:\n%s', self) self.dereference() log.debug('dereferenced:\n%s', self) def mktns(self): """ Make the schema's target namespace. @return: The namespace representation of the schema's targetNamespace value. @rtype: (prefix, uri) """ tns = [None, self.root.get('targetNamespace')] if tns[1] is not None: tns[0] = self.root.findPrefix(tns[1]) return tuple(tns) def build(self): """ Build the schema (object graph) using the root node using the factory. - Build the graph. - Collate the children. """ self.children = BasicFactory.build(self.root, self) collated = BasicFactory.collate(self.children) self.children = collated[0] self.attributes = collated[2] self.imports = collated[1] self.elements = collated[3] self.types = collated[4] self.groups = collated[5] self.agrps = collated[6] def merge(self, schema): """ Merge the contents from the schema. Only objects not already contained in this schema's collections are merged. This is to provide for bidirectional import which produce cyclic includes. @returns: self @rtype: L{Schema} """ for item in schema.attributes.items(): if item[0] in self.attributes: continue self.all.append(item[1]) self.attributes[item[0]] = item[1] for item in schema.elements.items(): if item[0] in self.elements: continue self.all.append(item[1]) self.elements[item[0]] = item[1] for item in schema.types.items(): if item[0] in self.types: continue self.all.append(item[1]) self.types[item[0]] = item[1] for item in schema.groups.items(): if item[0] in self.groups: continue self.all.append(item[1]) self.groups[item[0]] = item[1] for item in schema.agrps.items(): if item[0] in self.agrps: continue self.all.append(item[1]) self.agrps[item[0]] = item[1] schema.merged = True return self def open_imports(self, options): """ Instruct all contained L{sxbasic.Import} children to import the schema's which they reference. The contents of the imported schema are I{merged} in. @param options: An options dictionary. @type options: L{options.Options} """ for imp in self.imports: imported = imp.open(options) if imported is None: continue imported.open_imports(options) log.debug('imported:\n%s', imported) self.merge(imported) def dereference(self): """ Instruct all children to perform dereferencing. """ all = [] indexes = {} for child in self.children: child.content(all) deplist = DepList() for x in all: x.qualify() midx, deps = x.dependencies() item = (x, tuple(deps)) deplist.add(item) indexes[x] = midx for x, deps in deplist.sort(): midx = indexes.get(x) if midx is None: continue d = deps[midx] log.debug('(%s) merging %s <== %s', self.tns[1], Repr(x), Repr(d)) x.merge(d) def locate(self, ns): """ Find a schema by namespace. Only the URI portion of the namespace is compared to each schema's I{targetNamespace}. The request is passed to the container. @param ns: A namespace. @type ns: (prefix,URI) @return: The schema matching the namesapce, else None. @rtype: L{Schema} """ if self.container is not None: return self.container.locate(ns) else: return None def custom(self, ref, context=None): """ Get whether the specified reference is B{not} an (xs) builtin. @param ref: A str or qref. @type ref: (str|qref) @return: True if B{not} a builtin, else False. @rtype: bool """ if ref is None: return True else: return ( not self.builtin(ref, context) ) def builtin(self, ref, context=None): """ Get whether the specified reference is an (xs) builtin. @param ref: A str or qref. @type ref: (str|qref) @return: True if builtin, else False. @rtype: bool """ w3 = 'http://www.w3.org' try: if isqref(ref): ns = ref[1] return ( ref[0] in Factory.tags and ns.startswith(w3) ) if context is None: context = self.root prefix = splitPrefix(ref)[0] prefixes = context.findPrefixes(w3, 'startswith') return ( prefix in prefixes and ref[0] in Factory.tags ) except: return False def instance(self, root, baseurl, options): """ Create and return an new schema object using the specified I{root} and I{url}. @param root: A schema root node. @type root: L{sax.element.Element} @param baseurl: A base URL. @type baseurl: str @param options: An options dictionary. @type options: L{options.Options} @return: The newly created schema object. @rtype: L{Schema} @note: This is only used by Import children. """ return Schema(root, baseurl, options) def str(self, indent=0): tab = '%*s'%(indent*3, '') result = [] result.append('%s%s' % (tab, self.id)) result.append('%s(raw)' % tab) result.append(self.root.str(indent+1)) result.append('%s(model)' % tab) for c in self.children: result.append(c.str(indent+1)) result.append('') return '\n'.join(result) def __repr__(self): myrep = '<%s tns="%s"/>' % (self.id, self.tns[1]) return myrep.encode('utf-8') def __str__(self): return unicode(self).encode('utf-8') def __unicode__(self): return self.str()
gpl-3.0
shermanng10/superathletebuilder
env/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py
99
11451
from __future__ import unicode_literals import base64 import logging import string from datetime import datetime, timedelta from django.conf import settings from django.contrib.sessions.exceptions import SuspiciousSession from django.core.exceptions import SuspiciousOperation from django.utils import timezone from django.utils.crypto import ( constant_time_compare, get_random_string, salted_hmac, ) from django.utils.encoding import force_bytes, force_text from django.utils.module_loading import import_string # session_key should not be case sensitive because some backends can store it # on case insensitive file systems. VALID_KEY_CHARS = string.ascii_lowercase + string.digits class CreateError(Exception): """ Used internally as a consistent exception type to catch from save (see the docstring for SessionBase.save() for details). """ pass class SessionBase(object): """ Base class for all Session classes. """ TEST_COOKIE_NAME = 'testcookie' TEST_COOKIE_VALUE = 'worked' def __init__(self, session_key=None): self._session_key = session_key self.accessed = False self.modified = False self.serializer = import_string(settings.SESSION_SERIALIZER) def __contains__(self, key): return key in self._session def __getitem__(self, key): return self._session[key] def __setitem__(self, key, value): self._session[key] = value self.modified = True def __delitem__(self, key): del self._session[key] self.modified = True def get(self, key, default=None): return self._session.get(key, default) def pop(self, key, *args): self.modified = self.modified or key in self._session return self._session.pop(key, *args) def setdefault(self, key, value): if key in self._session: return self._session[key] else: self.modified = True self._session[key] = value return value def set_test_cookie(self): self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE def test_cookie_worked(self): return self.get(self.TEST_COOKIE_NAME) == self.TEST_COOKIE_VALUE def delete_test_cookie(self): del self[self.TEST_COOKIE_NAME] def _hash(self, value): key_salt = "django.contrib.sessions" + self.__class__.__name__ return salted_hmac(key_salt, value).hexdigest() def encode(self, session_dict): "Returns the given session dictionary serialized and encoded as a string." serialized = self.serializer().dumps(session_dict) hash = self._hash(serialized) return base64.b64encode(hash.encode() + b":" + serialized).decode('ascii') def decode(self, session_data): encoded_data = base64.b64decode(force_bytes(session_data)) try: # could produce ValueError if there is no ':' hash, serialized = encoded_data.split(b':', 1) expected_hash = self._hash(serialized) if not constant_time_compare(hash.decode(), expected_hash): raise SuspiciousSession("Session data corrupted") else: return self.serializer().loads(serialized) except Exception as e: # ValueError, SuspiciousOperation, unpickling exceptions. If any of # these happen, just return an empty dictionary (an empty session). if isinstance(e, SuspiciousOperation): logger = logging.getLogger('django.security.%s' % e.__class__.__name__) logger.warning(force_text(e)) return {} def update(self, dict_): self._session.update(dict_) self.modified = True def has_key(self, key): return key in self._session def keys(self): return self._session.keys() def values(self): return self._session.values() def items(self): return self._session.items() def iterkeys(self): return self._session.iterkeys() def itervalues(self): return self._session.itervalues() def iteritems(self): return self._session.iteritems() def clear(self): # To avoid unnecessary persistent storage accesses, we set up the # internals directly (loading data wastes time, since we are going to # set it to an empty dict anyway). self._session_cache = {} self.accessed = True self.modified = True def is_empty(self): "Returns True when there is no session_key and the session is empty" try: return not bool(self._session_key) and not self._session_cache except AttributeError: return True def _get_new_session_key(self): "Returns session key that isn't being used." while True: session_key = get_random_string(32, VALID_KEY_CHARS) if not self.exists(session_key): break return session_key def _get_or_create_session_key(self): if self._session_key is None: self._session_key = self._get_new_session_key() return self._session_key def _get_session_key(self): return self._session_key session_key = property(_get_session_key) def _get_session(self, no_load=False): """ Lazily loads session from storage (unless "no_load" is True, when only an empty dict is stored) and stores it in the current instance. """ self.accessed = True try: return self._session_cache except AttributeError: if self.session_key is None or no_load: self._session_cache = {} else: self._session_cache = self.load() return self._session_cache _session = property(_get_session) def get_expiry_age(self, **kwargs): """Get the number of seconds until the session expires. Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session. """ try: modification = kwargs['modification'] except KeyError: modification = timezone.now() # Make the difference between "expiry=None passed in kwargs" and # "expiry not passed in kwargs", in order to guarantee not to trigger # self.load() when expiry is provided. try: expiry = kwargs['expiry'] except KeyError: expiry = self.get('_session_expiry') if not expiry: # Checks both None and 0 cases return settings.SESSION_COOKIE_AGE if not isinstance(expiry, datetime): return expiry delta = expiry - modification return delta.days * 86400 + delta.seconds def get_expiry_date(self, **kwargs): """Get session the expiry date (as a datetime object). Optionally, this function accepts `modification` and `expiry` keyword arguments specifying the modification and expiry of the session. """ try: modification = kwargs['modification'] except KeyError: modification = timezone.now() # Same comment as in get_expiry_age try: expiry = kwargs['expiry'] except KeyError: expiry = self.get('_session_expiry') if isinstance(expiry, datetime): return expiry if not expiry: # Checks both None and 0 cases expiry = settings.SESSION_COOKIE_AGE return modification + timedelta(seconds=expiry) def set_expiry(self, value): """ Sets a custom expiration for the session. ``value`` can be an integer, a Python ``datetime`` or ``timedelta`` object or ``None``. If ``value`` is an integer, the session will expire after that many seconds of inactivity. If set to ``0`` then the session will expire on browser close. If ``value`` is a ``datetime`` or ``timedelta`` object, the session will expire at that specific future time. If ``value`` is ``None``, the session uses the global session expiry policy. """ if value is None: # Remove any custom expiration for this session. try: del self['_session_expiry'] except KeyError: pass return if isinstance(value, timedelta): value = timezone.now() + value self['_session_expiry'] = value def get_expire_at_browser_close(self): """ Returns ``True`` if the session is set to expire when the browser closes, and ``False`` if there's an expiry date. Use ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry date/age, if there is one. """ if self.get('_session_expiry') is None: return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE return self.get('_session_expiry') == 0 def flush(self): """ Removes the current session data from the database and regenerates the key. """ self.clear() self.delete() self._session_key = None def cycle_key(self): """ Creates a new session key, whilst retaining the current session data. """ data = self._session_cache key = self.session_key self.create() self._session_cache = data self.delete(key) # Methods that child classes must implement. def exists(self, session_key): """ Returns True if the given session_key already exists. """ raise NotImplementedError('subclasses of SessionBase must provide an exists() method') def create(self): """ Creates a new session instance. Guaranteed to create a new object with a unique key and will have saved the result once (with empty data) before the method returns. """ raise NotImplementedError('subclasses of SessionBase must provide a create() method') def save(self, must_create=False): """ Saves the session data. If 'must_create' is True, a new session object is created (otherwise a CreateError exception is raised). Otherwise, save() can update an existing object with the same key. """ raise NotImplementedError('subclasses of SessionBase must provide a save() method') def delete(self, session_key=None): """ Deletes the session data under this key. If the key is None, the current session key value is used. """ raise NotImplementedError('subclasses of SessionBase must provide a delete() method') def load(self): """ Loads the session data and returns a dictionary. """ raise NotImplementedError('subclasses of SessionBase must provide a load() method') @classmethod def clear_expired(cls): """ Remove expired sessions from the session store. If this operation isn't possible on a given backend, it should raise NotImplementedError. If it isn't necessary, because the backend has a built-in expiration mechanism, it should be a no-op. """ raise NotImplementedError('This backend does not support clear_expired().')
mit
chartly/portfolio
ditfw-gfx/deps/wxwidgets/build/tools/builder.py
8
7907
import os import subprocess import sys import time class BuildError(Exception): def __init__(self, value): self.value = value def __repr__(self): return repr(self.value) def runInDir(command, dir=None, verbose=True): if dir: olddir = os.getcwd() os.chdir(dir) commandStr = " ".join(command) if verbose: print(commandStr) result = os.system(commandStr) if dir: os.chdir(olddir) return result class Builder: """ Base class exposing the Builder interface. """ def __init__(self, formatName="", commandName="", programDir=None): """ formatName = human readable name for project format (should correspond with Bakefile names) commandName = name of command line program used to invoke builder programDir = directory program is located in, if not on the path """ self.dir = dir self.name = commandName self.formatName = formatName self.programDir = programDir self.doSetup() def doSetup(self): """ Do anything special needed to configure the environment to build with this builder. """ pass def isAvailable(self): """ Run sanity checks before attempting to build with this format """ # Make sure the builder program exists programPath = self.getProgramPath() if os.path.exists(programPath): return True else: # check the PATH for the program # TODO: How do we check if we're in Cygwin? if sys.platform.startswith("win"): result = os.system(self.name) if result == 0: return True dirs = os.environ["PATH"].split(":") for dir in dirs: if os.path.isfile(os.path.join(dir, self.name)): return True else: result = os.system("which %s" % self.name) if result == 0: return True return False def getProgramPath(self): if self.programDir: path = os.path.join(self.programDir, self.name) if sys.platform.startswith("win"): path = '"%s"' % path return path return self.name def getProjectFileArg(self, projectFile = None): result = [] if projectFile: result.append(projectFile) return result def clean(self, dir=None, projectFile=None, options=[]): """ dir = the directory containing the project file projectFile = Some formats need to explicitly specify the project file's name """ if self.isAvailable(): args = [self.getProgramPath()] pfArg = self.getProjectFileArg(projectFile) if pfArg: args.extend(pfArg) args.append("clean") if options: args.extend(options) result = runInDir(args, dir) return result return False def configure(self, dir=None, options=[]): # if we don't have configure, just report success return 0 def build(self, dir=None, projectFile=None, targets=None, options=[]): if self.isAvailable(): args = [self.getProgramPath()] pfArg = self.getProjectFileArg(projectFile) if pfArg: args.extend(pfArg) # Important Note: if extending args, check it first! # NoneTypes are not iterable and will crash the clean, build, or install! # Very very irritating when this happens right at the end. if options: args.extend(options) result = runInDir(args, dir) return result return 1 def install(self, dir=None, projectFile=None, options=[]): if self.isAvailable(): args = [self.getProgramPath()] pfArg = self.getProjectFileArg(projectFile) if pfArg: args.extend(pfArg) args.append("install") if options: args.extend(options) result = runInDir(args, dir) return result return 1 # Concrete subclasses of abstract Builder interface class GNUMakeBuilder(Builder): def __init__(self, commandName="make", formatName="GNUMake"): Builder.__init__(self, commandName=commandName, formatName=formatName) class XcodeBuilder(Builder): def __init__(self, commandName="xcodebuild", formatName="Xcode"): Builder.__init__(self, commandName=commandName, formatName=formatName) class AutoconfBuilder(GNUMakeBuilder): def __init__(self, formatName="autoconf"): GNUMakeBuilder.__init__(self, formatName=formatName) def configure(self, dir=None, options=None): #olddir = os.getcwd() #os.chdir(dir) configdir = dir if not dir: configdir = os.getcwd() configure_cmd = "" while os.path.exists(configdir): config_cmd = os.path.join(configdir, "configure") if not os.path.exists(config_cmd): parentdir = os.path.abspath(os.path.join(configdir, "..")) if configdir == parentdir: break configdir = parentdir else: configure_cmd = config_cmd break if not configure_cmd: sys.stderr.write("Could not find configure script at %r. Have you run autoconf?\n" % dir) return 1 optionsStr = " ".join(options) if options else "" command = "%s %s" % (configure_cmd, optionsStr) print(command) result = os.system(command) #os.chdir(olddir) return result class MSVCBuilder(Builder): def __init__(self, commandName="nmake.exe"): Builder.__init__(self, commandName=commandName, formatName="msvc") def isAvailable(self): PATH = os.environ['PATH'].split(os.path.pathsep) for p in PATH: if os.path.exists(os.path.join(p, self.name)): return True return False def getProjectFileArg(self, projectFile = None): result = [] if projectFile: result.extend(['-f', projectFile]) return result class MSVCProjectBuilder(Builder): def __init__(self): Builder.__init__(self, commandName="VCExpress.exe", formatName="msvcProject") for key in ["VS90COMNTOOLS", "VC80COMNTOOLS", "VC71COMNTOOLS"]: if os.environ.has_key(key): self.programDir = os.path.join(os.environ[key], "..", "IDE") if self.programDir == None: for version in ["9.0", "8", ".NET 2003"]: msvcDir = "C:\\Program Files\\Microsoft Visual Studio %s\\Common7\\IDE" % version if os.path.exists(msvcDir): self.programDir = msvcDir def isAvailable(self): if self.programDir: path = os.path.join(self.programDir, self.name) if os.path.exists(path): return True else: # I don't have commercial versions of MSVC so I can't test this name = "devenv.com" path = os.path.join(self.programDir, name) if os.path.exists(path): self.name = "devenv.com" return True return False builders = [GNUMakeBuilder, XcodeBuilder, AutoconfBuilder, MSVCBuilder, MSVCProjectBuilder] def getAvailableBuilders(): availableBuilders = {} for symbol in builders: thisBuilder = symbol() if thisBuilder.isAvailable(): availableBuilders[thisBuilder.formatName] = symbol return availableBuilders
mit
BlindHunter/django
tests/migrations/test_autodetector.py
28
114100
# -*- coding: utf-8 -*- import re from django.apps import apps from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.core.validators import RegexValidator, validate_slug from django.db import connection, models from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.graph import MigrationGraph from django.db.migrations.loader import MigrationLoader from django.db.migrations.questioner import MigrationQuestioner from django.db.migrations.state import ModelState, ProjectState from django.test import TestCase, mock, override_settings from django.test.utils import isolate_lru_cache from .models import FoodManager, FoodQuerySet class DeconstructibleObject(object): """ A custom deconstructible object. """ def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def deconstruct(self): return ( self.__module__ + '.' + self.__class__.__name__, self.args, self.kwargs ) class AutodetectorTests(TestCase): """ Tests the migration autodetector. """ author_empty = ModelState("testapp", "Author", [("id", models.AutoField(primary_key=True))]) author_name = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ]) author_name_null = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, null=True)), ]) author_name_longer = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=400)), ]) author_name_renamed = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("names", models.CharField(max_length=200)), ]) author_name_default = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default='Ada Lovelace')), ]) author_name_deconstructible_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ]) author_name_deconstructible_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ]) author_name_deconstructible_3 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ]) author_name_deconstructible_4 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ]) author_name_deconstructible_list_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=[DeconstructibleObject(), 123])), ]) author_name_deconstructible_list_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=[DeconstructibleObject(), 123])), ]) author_name_deconstructible_list_3 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=[DeconstructibleObject(), 999])), ]) author_name_deconstructible_tuple_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=(DeconstructibleObject(), 123))), ]) author_name_deconstructible_tuple_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=(DeconstructibleObject(), 123))), ]) author_name_deconstructible_tuple_3 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=(DeconstructibleObject(), 999))), ]) author_name_deconstructible_dict_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default={ 'item': DeconstructibleObject(), 'otheritem': 123 })), ]) author_name_deconstructible_dict_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default={ 'item': DeconstructibleObject(), 'otheritem': 123 })), ]) author_name_deconstructible_dict_3 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default={ 'item': DeconstructibleObject(), 'otheritem': 999 })), ]) author_name_nested_deconstructible_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), ))), ]) author_name_nested_deconstructible_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), ))), ]) author_name_nested_deconstructible_changed_arg = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2-changed'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), ))), ]) author_name_nested_deconstructible_extra_arg = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), None, a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), ))), ]) author_name_nested_deconstructible_changed_kwarg = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c-changed')), ))), ]) author_name_nested_deconstructible_extra_kwarg = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), c=None, ))), ]) author_custom_pk = ModelState("testapp", "Author", [("pk_field", models.IntegerField(primary_key=True))]) author_with_biography_non_blank = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField()), ("biography", models.TextField()), ]) author_with_biography_blank = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(blank=True)), ("biography", models.TextField(blank=True)), ]) author_with_book = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ]) author_with_book_order_wrt = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={"order_with_respect_to": "book"}) author_renamed_with_book = ModelState("testapp", "Writer", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ]) author_with_publisher_string = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher_name", models.CharField(max_length=200)), ]) author_with_publisher = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ]) author_with_user = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("auth.User", models.CASCADE)), ]) author_with_custom_user = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("thirdapp.CustomUser", models.CASCADE)), ]) author_proxy = ModelState("testapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author",)) author_proxy_options = ModelState("testapp", "AuthorProxy", [], { "proxy": True, "verbose_name": "Super Author", }, ("testapp.author", )) author_proxy_notproxy = ModelState("testapp", "AuthorProxy", [], {}, ("testapp.author", )) author_proxy_third = ModelState("thirdapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author", )) author_proxy_proxy = ModelState("testapp", "AAuthorProxyProxy", [], {"proxy": True}, ("testapp.authorproxy", )) author_unmanaged = ModelState("testapp", "AuthorUnmanaged", [], {"managed": False}, ("testapp.author", )) author_unmanaged_managed = ModelState("testapp", "AuthorUnmanaged", [], {}, ("testapp.author", )) author_unmanaged_default_pk = ModelState("testapp", "Author", [("id", models.AutoField(primary_key=True))]) author_unmanaged_custom_pk = ModelState("testapp", "Author", [ ("pk_field", models.IntegerField(primary_key=True)), ]) author_with_m2m = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher")), ]) author_with_m2m_blank = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher", blank=True)), ]) author_with_m2m_through = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher", through="testapp.Contract")), ]) author_with_former_m2m = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.CharField(max_length=100)), ]) author_with_options = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], { "permissions": [('can_hire', 'Can hire')], "verbose_name": "Authi", }) author_with_db_table_options = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}) author_with_new_db_table_options = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_two"}) author_renamed_with_db_table_options = ModelState("testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}) author_renamed_with_new_db_table_options = ModelState("testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_three"}) contract = ModelState("testapp", "Contract", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ]) publisher = ModelState("testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ]) publisher_with_author = ModelState("testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("name", models.CharField(max_length=100)), ]) publisher_with_aardvark_author = ModelState("testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Aardvark", models.CASCADE)), ("name", models.CharField(max_length=100)), ]) publisher_with_book = ModelState("testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Book", models.CASCADE)), ("name", models.CharField(max_length=100)), ]) other_pony = ModelState("otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ]) other_pony_food = ModelState("otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ], managers=[ ('food_qs', FoodQuerySet.as_manager()), ('food_mgr', FoodManager('a', 'b')), ('food_mgr_kwargs', FoodManager('x', 'y', 3, 4)), ]) other_stable = ModelState("otherapp", "Stable", [("id", models.AutoField(primary_key=True))]) third_thing = ModelState("thirdapp", "Thing", [("id", models.AutoField(primary_key=True))]) book = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_proxy_fk = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("thirdapp.AuthorProxy", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_migrations_fk = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("migrations.UnmigratedModel", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_with_no_author = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=200)), ]) book_with_author_renamed = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_with_field_and_author_renamed = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("writer", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_with_multiple_authors = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author")), ("title", models.CharField(max_length=200)), ]) book_with_multiple_authors_through_attribution = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author", through="otherapp.Attribution")), ("title", models.CharField(max_length=200)), ]) book_foo_together = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("author", "title")}, "unique_together": {("author", "title")}, }) book_foo_together_2 = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "author")}, "unique_together": {("title", "author")}, }) book_foo_together_3 = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "newfield")}, "unique_together": {("title", "newfield")}, }) book_foo_together_4 = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield2", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "newfield2")}, "unique_together": {("title", "newfield2")}, }) attribution = ModelState("otherapp", "Attribution", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ]) edition = ModelState("thirdapp", "Edition", [ ("id", models.AutoField(primary_key=True)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ]) custom_user = ModelState("thirdapp", "CustomUser", [ ("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255)), ], bases=(AbstractBaseUser, )) custom_user_no_inherit = ModelState("thirdapp", "CustomUser", [ ("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255)), ]) aardvark = ModelState("thirdapp", "Aardvark", [("id", models.AutoField(primary_key=True))]) aardvark_testapp = ModelState("testapp", "Aardvark", [("id", models.AutoField(primary_key=True))]) aardvark_based_on_author = ModelState("testapp", "Aardvark", [], bases=("testapp.Author", )) aardvark_pk_fk_author = ModelState("testapp", "Aardvark", [ ("id", models.OneToOneField("testapp.Author", models.CASCADE, primary_key=True)), ]) knight = ModelState("eggs", "Knight", [("id", models.AutoField(primary_key=True))]) rabbit = ModelState("eggs", "Rabbit", [ ("id", models.AutoField(primary_key=True)), ("knight", models.ForeignKey("eggs.Knight", models.CASCADE)), ("parent", models.ForeignKey("eggs.Rabbit", models.CASCADE)), ], {"unique_together": {("parent", "knight")}}) def repr_changes(self, changes, include_dependencies=False): output = "" for app_label, migrations in sorted(changes.items()): output += " %s:\n" % app_label for migration in migrations: output += " %s\n" % migration.name for operation in migration.operations: output += " %s\n" % operation if include_dependencies: output += " Dependencies:\n" if migration.dependencies: for dep in migration.dependencies: output += " %s\n" % (dep,) else: output += " None\n" return output def assertNumberMigrations(self, changes, app_label, number): if len(changes.get(app_label, [])) != number: self.fail("Incorrect number of migrations (%s) for %s (expected %s)\n%s" % ( len(changes.get(app_label, [])), app_label, number, self.repr_changes(changes), )) def assertMigrationDependencies(self, changes, app_label, index, dependencies): if not changes.get(app_label): self.fail("No migrations found for %s\n%s" % (app_label, self.repr_changes(changes))) if len(changes[app_label]) < index + 1: self.fail("No migration at index %s for %s\n%s" % (index, app_label, self.repr_changes(changes))) migration = changes[app_label][index] if set(migration.dependencies) != set(dependencies): self.fail("Migration dependencies mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, dependencies, self.repr_changes(changes, include_dependencies=True), )) def assertOperationTypes(self, changes, app_label, index, types): if not changes.get(app_label): self.fail("No migrations found for %s\n%s" % (app_label, self.repr_changes(changes))) if len(changes[app_label]) < index + 1: self.fail("No migration at index %s for %s\n%s" % (index, app_label, self.repr_changes(changes))) migration = changes[app_label][index] real_types = [operation.__class__.__name__ for operation in migration.operations] if types != real_types: self.fail("Operation type mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, types, self.repr_changes(changes), )) def assertOperationAttributes(self, changes, app_label, index, operation_index, **attrs): if not changes.get(app_label): self.fail("No migrations found for %s\n%s" % (app_label, self.repr_changes(changes))) if len(changes[app_label]) < index + 1: self.fail("No migration at index %s for %s\n%s" % (index, app_label, self.repr_changes(changes))) migration = changes[app_label][index] if len(changes[app_label]) < index + 1: self.fail("No operation at index %s for %s.%s\n%s" % ( operation_index, app_label, migration.name, self.repr_changes(changes), )) operation = migration.operations[operation_index] for attr, value in attrs.items(): if getattr(operation, attr, None) != value: self.fail("Attribute mismatch for %s.%s op #%s, %s (expected %r, got %r):\n%s" % ( app_label, migration.name, operation_index, attr, value, getattr(operation, attr, None), self.repr_changes(changes), )) def assertOperationFieldAttributes(self, changes, app_label, index, operation_index, **attrs): if not changes.get(app_label): self.fail("No migrations found for %s\n%s" % (app_label, self.repr_changes(changes))) if len(changes[app_label]) < index + 1: self.fail("No migration at index %s for %s\n%s" % (index, app_label, self.repr_changes(changes))) migration = changes[app_label][index] if len(changes[app_label]) < index + 1: self.fail("No operation at index %s for %s.%s\n%s" % ( operation_index, app_label, migration.name, self.repr_changes(changes), )) operation = migration.operations[operation_index] if not hasattr(operation, 'field'): self.fail("No field attribute for %s.%s op #%s." % ( app_label, migration.name, operation_index, )) field = operation.field for attr, value in attrs.items(): if getattr(field, attr, None) != value: self.fail("Field attribute mismatch for %s.%s op #%s, field.%s (expected %r, got %r):\n%s" % ( app_label, migration.name, operation_index, attr, value, getattr(field, attr, None), self.repr_changes(changes), )) def make_project_state(self, model_states): "Shortcut to make ProjectStates from lists of predefined models" project_state = ProjectState() for model_state in model_states: project_state.add_model(model_state.clone()) return project_state def test_arrange_for_graph(self): """Tests auto-naming of migrations for graph matching.""" # Make a fake graph graph = MigrationGraph() graph.add_node(("testapp", "0001_initial"), None) graph.add_node(("testapp", "0002_foobar"), None) graph.add_node(("otherapp", "0001_initial"), None) graph.add_dependency("testapp.0002_foobar", ("testapp", "0002_foobar"), ("testapp", "0001_initial")) graph.add_dependency("testapp.0002_foobar", ("testapp", "0002_foobar"), ("otherapp", "0001_initial")) # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state([self.author_empty, self.other_pony, self.other_stable]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Run through arrange_for_graph changes = autodetector.arrange_for_graph(changes, graph) # Make sure there's a new name, deps match, etc. self.assertEqual(changes["testapp"][0].name, "0003_author") self.assertEqual(changes["testapp"][0].dependencies, [("testapp", "0002_foobar")]) self.assertEqual(changes["otherapp"][0].name, "0002_pony_stable") self.assertEqual(changes["otherapp"][0].dependencies, [("otherapp", "0001_initial")]) def test_trim_apps(self): """ Tests that trim does not remove dependencies but does remove unwanted apps. """ # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state([self.author_empty, self.other_pony, self.other_stable, self.third_thing]) autodetector = MigrationAutodetector(before, after, MigrationQuestioner({"ask_initial": True})) changes = autodetector._detect_changes() # Run through arrange_for_graph graph = MigrationGraph() changes = autodetector.arrange_for_graph(changes, graph) changes["testapp"][0].dependencies.append(("otherapp", "0001_initial")) changes = autodetector._trim_to_apps(changes, {"testapp"}) # Make sure there's the right set of migrations self.assertEqual(changes["testapp"][0].name, "0001_initial") self.assertEqual(changes["otherapp"][0].name, "0001_initial") self.assertNotIn("thirdapp", changes) def test_custom_migration_name(self): """Tests custom naming of migrations for graph matching.""" # Make a fake graph graph = MigrationGraph() graph.add_node(("testapp", "0001_initial"), None) graph.add_node(("testapp", "0002_foobar"), None) graph.add_node(("otherapp", "0001_initial"), None) graph.add_dependency("testapp.0002_foobar", ("testapp", "0002_foobar"), ("testapp", "0001_initial")) # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state([self.author_empty, self.other_pony, self.other_stable]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Run through arrange_for_graph migration_name = 'custom_name' changes = autodetector.arrange_for_graph(changes, graph, migration_name) # Make sure there's a new name, deps match, etc. self.assertEqual(changes["testapp"][0].name, "0003_%s" % migration_name) self.assertEqual(changes["testapp"][0].dependencies, [("testapp", "0002_foobar")]) self.assertEqual(changes["otherapp"][0].name, "0002_%s" % migration_name) self.assertEqual(changes["otherapp"][0].dependencies, [("otherapp", "0001_initial")]) def test_new_model(self): """Tests autodetection of new models.""" # Make state before = self.make_project_state([]) after = self.make_project_state([self.other_pony_food]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Pony") self.assertEqual([name for name, mgr in changes['otherapp'][0].operations[0].managers], ['food_qs', 'food_mgr', 'food_mgr_kwargs']) def test_old_model(self): """Tests deletion of old models.""" # Make state before = self.make_project_state([self.author_empty]) after = self.make_project_state([]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["DeleteModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") def test_add_field(self): """Tests autodetection of new fields.""" # Make state before = self.make_project_state([self.author_empty]) after = self.make_project_state([self.author_name]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") def test_remove_field(self): """Tests autodetection of removed fields.""" # Make state before = self.make_project_state([self.author_name]) after = self.make_project_state([self.author_empty]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RemoveField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") def test_alter_field(self): """Tests autodetection of new fields.""" # Make state before = self.make_project_state([self.author_name]) after = self.make_project_state([self.author_name_longer]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=True) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration', side_effect=AssertionError("Should not have prompted for not null addition")) def test_alter_field_to_not_null_with_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ # Make state before = self.make_project_state([self.author_name_null]) after = self.make_project_state([self.author_name_default]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, default='Ada Lovelace') @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration', return_value=models.NOT_PROVIDED) def test_alter_field_to_not_null_without_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ # Make state before = self.make_project_state([self.author_name_null]) after = self.make_project_state([self.author_name]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(mocked_ask_method.call_count, 1) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, default=models.NOT_PROVIDED) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration', return_value='Some Name') def test_alter_field_to_not_null_oneoff_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ # Make state before = self.make_project_state([self.author_name_null]) after = self.make_project_state([self.author_name]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(mocked_ask_method.call_count, 1) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=False) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, default="Some Name") def test_rename_field(self): """Tests autodetection of renamed fields.""" # Make state before = self.make_project_state([self.author_name]) after = self.make_project_state([self.author_name_renamed]) autodetector = MigrationAutodetector(before, after, MigrationQuestioner({"ask_rename": True})) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, old_name="name", new_name="names") def test_rename_model(self): """Tests autodetection of renamed models.""" # Make state before = self.make_project_state([self.author_with_book, self.book]) after = self.make_project_state([self.author_renamed_with_book, self.book_with_author_renamed]) autodetector = MigrationAutodetector(before, after, MigrationQuestioner({"ask_rename_model": True})) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, old_name="Author", new_name="Writer") # Now that RenameModel handles related fields too, there should be # no AlterField for the related field. self.assertNumberMigrations(changes, 'otherapp', 0) def test_rename_model_with_renamed_rel_field(self): """ Tests autodetection of renamed models while simultaneously renaming one of the fields that relate to the renamed model. """ # Make state before = self.make_project_state([self.author_with_book, self.book]) after = self.make_project_state([self.author_renamed_with_book, self.book_with_field_and_author_renamed]) autodetector = MigrationAutodetector(before, after, MigrationQuestioner({ "ask_rename": True, "ask_rename_model": True, })) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, old_name="Author", new_name="Writer") # Right number/type of migrations for related field rename? # Alter is already taken care of. self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["RenameField"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, old_name="author", new_name="writer") def test_rename_model_with_fks_in_different_position(self): """ #24537 - Tests that the order of fields in a model does not influence the RenameModel detection. """ before = self.make_project_state([ ModelState("testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ]), ModelState("testapp", "EntityB", [ ("id", models.AutoField(primary_key=True)), ("some_label", models.CharField(max_length=255)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ]), ]) after = self.make_project_state([ ModelState("testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ]), ModelState("testapp", "RenamedEntityB", [ ("id", models.AutoField(primary_key=True)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ("some_label", models.CharField(max_length=255)), ]), ]) autodetector = MigrationAutodetector(before, after, MigrationQuestioner({"ask_rename_model": True})) changes = autodetector._detect_changes() self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, old_name="EntityB", new_name="RenamedEntityB") def test_fk_dependency(self): """Tests that having a ForeignKey automatically adds a dependency.""" # Make state # Note that testapp (author) has no dependencies, # otherapp (book) depends on testapp (author), # thirdapp (edition) depends on otherapp (book) before = self.make_project_state([]) after = self.make_project_state([self.author_name, self.book, self.edition]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertMigrationDependencies(changes, 'testapp', 0, []) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="Book") self.assertMigrationDependencies(changes, 'otherapp', 0, [("testapp", "auto_1")]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'thirdapp', 0, 0, name="Edition") self.assertMigrationDependencies(changes, 'thirdapp', 0, [("otherapp", "auto_1")]) def test_proxy_fk_dependency(self): """Tests that FK dependencies still work on proxy models.""" # Make state # Note that testapp (author) has no dependencies, # otherapp (book) depends on testapp (authorproxy) before = self.make_project_state([]) after = self.make_project_state([self.author_empty, self.author_proxy_third, self.book_proxy_fk]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertMigrationDependencies(changes, 'testapp', 0, []) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="Book") self.assertMigrationDependencies(changes, 'otherapp', 0, [("thirdapp", "auto_1")]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'thirdapp', 0, 0, name="AuthorProxy") self.assertMigrationDependencies(changes, 'thirdapp', 0, [("testapp", "auto_1")]) def test_same_app_no_fk_dependency(self): """ Tests that a migration with a FK between two models of the same app does not have a dependency to itself. """ # Make state before = self.make_project_state([]) after = self.make_project_state([self.author_with_publisher, self.publisher]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel", "AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 2, name="publisher") self.assertMigrationDependencies(changes, 'testapp', 0, []) def test_circular_fk_dependency(self): """ Tests that having a circular ForeignKey dependency automatically resolves the situation into 2 migrations on one side and 1 on the other. """ # Make state before = self.make_project_state([]) after = self.make_project_state([self.author_with_book, self.book, self.publisher_with_book]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertMigrationDependencies(changes, 'testapp', 0, [("otherapp", "auto_1")]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 2) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationTypes(changes, 'otherapp', 1, ["AddField"]) self.assertMigrationDependencies(changes, 'otherapp', 0, []) self.assertMigrationDependencies(changes, 'otherapp', 1, [("otherapp", "auto_1"), ("testapp", "auto_1")]) # both split migrations should be `initial` self.assertTrue(changes['otherapp'][0].initial) self.assertTrue(changes['otherapp'][1].initial) def test_same_app_circular_fk_dependency(self): """ Tests that a migration with a FK between two models of the same app does not have a dependency to itself. """ # Make state before = self.make_project_state([]) after = self.make_project_state([self.author_with_publisher, self.publisher_with_author]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel", "AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 2, name="publisher") self.assertMigrationDependencies(changes, 'testapp', 0, []) def test_same_app_circular_fk_dependency_and_unique_together(self): """ #22275 - Tests that a migration with circular FK dependency does not try to create unique together constraint before creating all required fields first. """ # Make state before = self.make_project_state([]) after = self.make_project_state([self.knight, self.rabbit]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'eggs', 1) self.assertOperationTypes(changes, 'eggs', 0, ["CreateModel", "CreateModel", "AlterUniqueTogether"]) self.assertNotIn("unique_together", changes['eggs'][0].operations[0].options) self.assertNotIn("unique_together", changes['eggs'][0].operations[1].options) self.assertMigrationDependencies(changes, 'eggs', 0, []) def test_alter_db_table_add(self): """Tests detection for adding db_table in model's options.""" # Make state before = self.make_project_state([self.author_empty]) after = self.make_project_state([self.author_with_db_table_options]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelTable"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", table="author_one") def test_alter_db_table_change(self): """Tests detection for changing db_table in model's options'.""" # Make state before = self.make_project_state([self.author_with_db_table_options]) after = self.make_project_state([self.author_with_new_db_table_options]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelTable"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", table="author_two") def test_alter_db_table_remove(self): """Tests detection for removing db_table in model's options.""" # Make state before = self.make_project_state([self.author_with_db_table_options]) after = self.make_project_state([self.author_empty]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelTable"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", table=None) def test_alter_db_table_no_changes(self): """ Tests that alter_db_table doesn't generate a migration if no changes have been made. """ # Make state before = self.make_project_state([self.author_with_db_table_options]) after = self.make_project_state([self.author_with_db_table_options]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number of migrations? self.assertEqual(len(changes), 0) def test_keep_db_table_with_model_change(self): """ Tests when model changes but db_table stays as-is, autodetector must not create more than one operation. """ # Make state before = self.make_project_state([self.author_with_db_table_options]) after = self.make_project_state([self.author_renamed_with_db_table_options]) autodetector = MigrationAutodetector(before, after, MigrationQuestioner({"ask_rename_model": True})) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, old_name="Author", new_name="NewAuthor") def test_alter_db_table_with_model_change(self): """ Tests when model and db_table changes, autodetector must create two operations. """ # Make state before = self.make_project_state([self.author_with_db_table_options]) after = self.make_project_state([self.author_renamed_with_new_db_table_options]) autodetector = MigrationAutodetector(before, after, MigrationQuestioner({"ask_rename_model": True})) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameModel", "AlterModelTable"]) self.assertOperationAttributes(changes, "testapp", 0, 0, old_name="Author", new_name="NewAuthor") self.assertOperationAttributes(changes, "testapp", 0, 1, name="newauthor", table="author_three") def test_identical_regex_doesnt_alter(self): from_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[ RegexValidator( re.compile('^[-a-zA-Z0-9_]+\\Z'), "Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.", 'invalid' ) ]))] ) to_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))] ) before = self.make_project_state([from_state]) after = self.make_project_state([to_state]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 0) def test_different_regex_does_alter(self): from_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[ RegexValidator( re.compile('^[a-z]+\\Z', 32), "Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.", 'invalid' ) ]))] ) to_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))] ) before = self.make_project_state([from_state]) after = self.make_project_state([to_state]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) def test_empty_foo_together(self): """ #23452 - Empty unique/index_together shouldn't generate a migration. """ # Explicitly testing for not specified, since this is the case after # a CreateModel operation w/o any definition on the original model model_state_not_specified = ModelState("a", "model", [("id", models.AutoField(primary_key=True))]) # Explicitly testing for None, since this was the issue in #23452 after # a AlterFooTogether operation with e.g. () as value model_state_none = ModelState("a", "model", [ ("id", models.AutoField(primary_key=True)) ], { "index_together": None, "unique_together": None, }) # Explicitly testing for the empty set, since we now always have sets. # During removal (('col1', 'col2'),) --> () this becomes set([]) model_state_empty = ModelState("a", "model", [ ("id", models.AutoField(primary_key=True)) ], { "index_together": set(), "unique_together": set(), }) def test(from_state, to_state, msg): before = self.make_project_state([from_state]) after = self.make_project_state([to_state]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() if len(changes) > 0: ops = ', '.join(o.__class__.__name__ for o in changes['a'][0].operations) self.fail('Created operation(s) %s from %s' % (ops, msg)) tests = ( (model_state_not_specified, model_state_not_specified, '"not specified" to "not specified"'), (model_state_not_specified, model_state_none, '"not specified" to "None"'), (model_state_not_specified, model_state_empty, '"not specified" to "empty"'), (model_state_none, model_state_not_specified, '"None" to "not specified"'), (model_state_none, model_state_none, '"None" to "None"'), (model_state_none, model_state_empty, '"None" to "empty"'), (model_state_empty, model_state_not_specified, '"empty" to "not specified"'), (model_state_empty, model_state_none, '"empty" to "None"'), (model_state_empty, model_state_empty, '"empty" to "empty"'), ) for t in tests: test(*t) def test_add_foo_together(self): """Tests index/unique_together detection.""" # Make state before = self.make_project_state([self.author_empty, self.book]) after = self.make_project_state([self.author_empty, self.book_foo_together]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="book", unique_together={("author", "title")}) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", index_together={("author", "title")}) def test_remove_foo_together(self): """Tests index/unique_together detection.""" before = self.make_project_state([self.author_empty, self.book_foo_together]) after = self.make_project_state([self.author_empty, self.book]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="book", unique_together=set()) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", index_together=set()) def test_foo_together_remove_fk(self): """Tests unique_together and field removal detection & ordering""" # Make state before = self.make_project_state([self.author_empty, self.book_foo_together]) after = self.make_project_state([self.author_empty, self.book_with_no_author]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, [ "AlterUniqueTogether", "AlterIndexTogether", "RemoveField" ]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="book", unique_together=set()) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", index_together=set()) self.assertOperationAttributes(changes, "otherapp", 0, 2, model_name="book", name="author") def test_foo_together_no_changes(self): """ Tests that index/unique_together doesn't generate a migration if no changes have been made. """ # Make state before = self.make_project_state([self.author_empty, self.book_foo_together]) after = self.make_project_state([self.author_empty, self.book_foo_together]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number of migrations? self.assertEqual(len(changes), 0) def test_foo_together_ordering(self): """ Tests that index/unique_together also triggers on ordering changes. """ # Make state before = self.make_project_state([self.author_empty, self.book_foo_together]) after = self.make_project_state([self.author_empty, self.book_foo_together_2]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="book", unique_together={("title", "author")}) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", index_together={("title", "author")}) def test_add_field_and_foo_together(self): """ Tests that added fields will be created before using them in index/unique_together. """ before = self.make_project_state([self.author_empty, self.book]) after = self.make_project_state([self.author_empty, self.book_foo_together_3]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AddField", "AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", unique_together={("title", "newfield")}) self.assertOperationAttributes(changes, "otherapp", 0, 2, name="book", index_together={("title", "newfield")}) def test_create_model_and_unique_together(self): author = ModelState("otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ]) book_with_author = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "author")}, "unique_together": {("title", "author")}, }) before = self.make_project_state([self.book_with_no_author]) after = self.make_project_state([author, book_with_author]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number of migrations? self.assertEqual(len(changes['otherapp']), 1) # Right number of actions? migration = changes['otherapp'][0] self.assertEqual(len(migration.operations), 4) # Right actions order? self.assertOperationTypes( changes, 'otherapp', 0, ['CreateModel', 'AddField', 'AlterUniqueTogether', 'AlterIndexTogether'] ) def test_remove_field_and_foo_together(self): """ Tests that removed fields will be removed after updating index/unique_together. """ before = self.make_project_state([self.author_empty, self.book_foo_together_3]) after = self.make_project_state([self.author_empty, self.book_foo_together]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RemoveField", "AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, model_name="book", name="newfield") self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", unique_together={("author", "title")}) self.assertOperationAttributes(changes, "otherapp", 0, 2, name="book", index_together={("author", "title")}) def test_rename_field_and_foo_together(self): """ Tests that removed fields will be removed after updating index/unique_together. """ before = self.make_project_state([self.author_empty, self.book_foo_together_3]) after = self.make_project_state([self.author_empty, self.book_foo_together_4]) autodetector = MigrationAutodetector(before, after, MigrationQuestioner({"ask_rename": True})) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RenameField", "AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", unique_together={ ("title", "newfield2") }) self.assertOperationAttributes(changes, "otherapp", 0, 2, name="book", index_together={("title", "newfield2")}) def test_proxy(self): """Tests that the autodetector correctly deals with proxy models.""" # First, we test adding a proxy model before = self.make_project_state([self.author_empty]) after = self.make_project_state([self.author_empty, self.author_proxy]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="AuthorProxy", options={"proxy": True}) # Now, we test turning a proxy model into a non-proxy model # It should delete the proxy then make the real one before = self.make_project_state([self.author_empty, self.author_proxy]) after = self.make_project_state([self.author_empty, self.author_proxy_notproxy]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="AuthorProxy") self.assertOperationAttributes(changes, "testapp", 0, 1, name="AuthorProxy", options={}) def test_proxy_custom_pk(self): """ #23415 - The autodetector must correctly deal with custom FK on proxy models. """ # First, we test the default pk field name before = self.make_project_state([]) after = self.make_project_state([self.author_empty, self.author_proxy_third, self.book_proxy_fk]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # The field name the FK on the book model points to self.assertEqual(changes['otherapp'][0].operations[0].fields[2][1].remote_field.field_name, 'id') # Now, we test the custom pk field name before = self.make_project_state([]) after = self.make_project_state([self.author_custom_pk, self.author_proxy_third, self.book_proxy_fk]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # The field name the FK on the book model points to self.assertEqual(changes['otherapp'][0].operations[0].fields[2][1].remote_field.field_name, 'pk_field') def test_unmanaged_create(self): """Tests that the autodetector correctly deals with managed models.""" # First, we test adding an unmanaged model before = self.make_project_state([self.author_empty]) after = self.make_project_state([self.author_empty, self.author_unmanaged]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="AuthorUnmanaged", options={"managed": False}) def test_unmanaged_to_managed(self): # Now, we test turning an unmanaged model into a managed model before = self.make_project_state([self.author_empty, self.author_unmanaged]) after = self.make_project_state([self.author_empty, self.author_unmanaged_managed]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="authorunmanaged", options={}) def test_managed_to_unmanaged(self): # Now, we turn managed to unmanaged. before = self.make_project_state([self.author_empty, self.author_unmanaged_managed]) after = self.make_project_state([self.author_empty, self.author_unmanaged]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="authorunmanaged", options={"managed": False}) def test_unmanaged_custom_pk(self): """ #23415 - The autodetector must correctly deal with custom FK on unmanaged models. """ # First, we test the default pk field name before = self.make_project_state([]) after = self.make_project_state([self.author_unmanaged_default_pk, self.book]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # The field name the FK on the book model points to self.assertEqual(changes['otherapp'][0].operations[0].fields[2][1].remote_field.field_name, 'id') # Now, we test the custom pk field name before = self.make_project_state([]) after = self.make_project_state([self.author_unmanaged_custom_pk, self.book]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # The field name the FK on the book model points to self.assertEqual(changes['otherapp'][0].operations[0].fields[2][1].remote_field.field_name, 'pk_field') @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable(self): with isolate_lru_cache(apps.get_swappable_settings_name): before = self.make_project_state([self.custom_user]) after = self.make_project_state([self.custom_user, self.author_with_custom_user]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertMigrationDependencies(changes, 'testapp', 0, [("__setting__", "AUTH_USER_MODEL")]) def test_swappable_changed(self): with isolate_lru_cache(apps.get_swappable_settings_name): before = self.make_project_state([self.custom_user, self.author_with_user]) with override_settings(AUTH_USER_MODEL="thirdapp.CustomUser"): after = self.make_project_state([self.custom_user, self.author_with_custom_user]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, model_name="author", name='user') fk_field = changes['testapp'][0].operations[0].field to_model = '%s.%s' % ( fk_field.remote_field.model._meta.app_label, fk_field.remote_field.model._meta.object_name, ) self.assertEqual(to_model, 'thirdapp.CustomUser') def test_add_field_with_default(self): """#22030 - Adding a field with a default should work.""" # Make state before = self.make_project_state([self.author_empty]) after = self.make_project_state([self.author_name_default]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="name") def test_custom_deconstructible(self): """ Two instances which deconstruct to the same value aren't considered a change. """ before = self.make_project_state([self.author_name_deconstructible_1]) after = self.make_project_state([self.author_name_deconstructible_2]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number of migrations? self.assertEqual(len(changes), 0) def test_deconstruct_field_kwarg(self): """Field instances are handled correctly by nested deconstruction.""" before = self.make_project_state([self.author_name_deconstructible_3]) after = self.make_project_state([self.author_name_deconstructible_4]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(changes, {}) def test_deconstructible_list(self): """Nested deconstruction descends into lists.""" # When lists contain items that deconstruct to identical values, those lists # should be considered equal for the purpose of detecting state changes # (even if the original items are unequal). before = self.make_project_state([self.author_name_deconstructible_list_1]) after = self.make_project_state([self.author_name_deconstructible_list_2]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(changes, {}) # Legitimate differences within the deconstructed lists should be reported # as a change before = self.make_project_state([self.author_name_deconstructible_list_1]) after = self.make_project_state([self.author_name_deconstructible_list_3]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(len(changes), 1) def test_deconstructible_tuple(self): """Nested deconstruction descends into tuples.""" # When tuples contain items that deconstruct to identical values, those tuples # should be considered equal for the purpose of detecting state changes # (even if the original items are unequal). before = self.make_project_state([self.author_name_deconstructible_tuple_1]) after = self.make_project_state([self.author_name_deconstructible_tuple_2]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(changes, {}) # Legitimate differences within the deconstructed tuples should be reported # as a change before = self.make_project_state([self.author_name_deconstructible_tuple_1]) after = self.make_project_state([self.author_name_deconstructible_tuple_3]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(len(changes), 1) def test_deconstructible_dict(self): """Nested deconstruction descends into dict values.""" # When dicts contain items whose values deconstruct to identical values, # those dicts should be considered equal for the purpose of detecting # state changes (even if the original values are unequal). before = self.make_project_state([self.author_name_deconstructible_dict_1]) after = self.make_project_state([self.author_name_deconstructible_dict_2]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(changes, {}) # Legitimate differences within the deconstructed dicts should be reported # as a change before = self.make_project_state([self.author_name_deconstructible_dict_1]) after = self.make_project_state([self.author_name_deconstructible_dict_3]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(len(changes), 1) def test_nested_deconstructible_objects(self): """ Nested deconstruction is applied recursively to the args/kwargs of deconstructed objects. """ # If the items within a deconstructed object's args/kwargs have the same # deconstructed values - whether or not the items themselves are different # instances - then the object as a whole is regarded as unchanged. before = self.make_project_state([self.author_name_nested_deconstructible_1]) after = self.make_project_state([self.author_name_nested_deconstructible_2]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(changes, {}) # Differences that exist solely within the args list of a deconstructed object # should be reported as changes before = self.make_project_state([self.author_name_nested_deconstructible_1]) after = self.make_project_state([self.author_name_nested_deconstructible_changed_arg]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(len(changes), 1) # Additional args should also be reported as a change before = self.make_project_state([self.author_name_nested_deconstructible_1]) after = self.make_project_state([self.author_name_nested_deconstructible_extra_arg]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(len(changes), 1) # Differences that exist solely within the kwargs dict of a deconstructed object # should be reported as changes before = self.make_project_state([self.author_name_nested_deconstructible_1]) after = self.make_project_state([self.author_name_nested_deconstructible_changed_kwarg]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(len(changes), 1) # Additional kwargs should also be reported as a change before = self.make_project_state([self.author_name_nested_deconstructible_1]) after = self.make_project_state([self.author_name_nested_deconstructible_extra_kwarg]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(len(changes), 1) def test_deconstruct_type(self): """ #22951 -- Uninstantiated classes with deconstruct are correctly returned by deep_deconstruct during serialization. """ author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField( max_length=200, # IntegerField intentionally not instantiated. default=models.IntegerField, )) ], ) # Make state before = self.make_project_state([]) after = self.make_project_state([author]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) def test_replace_string_with_foreignkey(self): """ #22300 - Adding an FK in the same "spot" as a deleted CharField should work. """ # Make state before = self.make_project_state([self.author_with_publisher_string]) after = self.make_project_state([self.author_with_publisher, self.publisher]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "RemoveField", "AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Publisher") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="publisher_name") self.assertOperationAttributes(changes, 'testapp', 0, 2, name="publisher") def test_foreign_key_removed_before_target_model(self): """ Removing an FK and the model it targets in the same change must remove the FK field before the model to maintain consistency. """ before = self.make_project_state([self.author_with_publisher, self.publisher]) after = self.make_project_state([self.author_name]) # removes both the model and FK autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RemoveField", "DeleteModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="publisher") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="Publisher") @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition', side_effect=AssertionError("Should not have prompted for not null addition")) def test_add_many_to_many(self, mocked_ask_method): """#22435 - Adding a ManyToManyField should not prompt for a default.""" before = self.make_project_state([self.author_empty, self.publisher]) after = self.make_project_state([self.author_with_m2m, self.publisher]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="publishers") def test_alter_many_to_many(self): before = self.make_project_state([self.author_with_m2m, self.publisher]) after = self.make_project_state([self.author_with_m2m_blank, self.publisher]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="publishers") def test_create_with_through_model(self): """ Adding a m2m with a through model and the models that use it should be ordered correctly. """ before = self.make_project_state([]) after = self.make_project_state([self.author_with_m2m_through, self.publisher, self.contract]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, [ "CreateModel", "CreateModel", "CreateModel", "AddField", "AddField" ]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="Contract") self.assertOperationAttributes(changes, 'testapp', 0, 2, name="Publisher") self.assertOperationAttributes(changes, 'testapp', 0, 3, model_name='contract', name='publisher') self.assertOperationAttributes(changes, 'testapp', 0, 4, model_name='author', name='publishers') def test_many_to_many_removed_before_through_model(self): """ Removing a ManyToManyField and the "through" model in the same change must remove the field before the model to maintain consistency. """ before = self.make_project_state([ self.book_with_multiple_authors_through_attribution, self.author_name, self.attribution ]) # Remove both the through model and ManyToMany after = self.make_project_state([self.book_with_no_author, self.author_name]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RemoveField", "RemoveField", "RemoveField", "DeleteModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="author", model_name='attribution') self.assertOperationAttributes(changes, 'otherapp', 0, 1, name="book", model_name='attribution') self.assertOperationAttributes(changes, 'otherapp', 0, 2, name="authors", model_name='book') self.assertOperationAttributes(changes, 'otherapp', 0, 3, name='Attribution') def test_many_to_many_removed_before_through_model_2(self): """ Removing a model that contains a ManyToManyField and the "through" model in the same change must remove the field before the model to maintain consistency. """ before = self.make_project_state([ self.book_with_multiple_authors_through_attribution, self.author_name, self.attribution ]) # Remove both the through model and ManyToMany after = self.make_project_state([self.author_name]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, [ "RemoveField", "RemoveField", "RemoveField", "DeleteModel", "DeleteModel" ]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="author", model_name='attribution') self.assertOperationAttributes(changes, 'otherapp', 0, 1, name="book", model_name='attribution') self.assertOperationAttributes(changes, 'otherapp', 0, 2, name="authors", model_name='book') self.assertOperationAttributes(changes, 'otherapp', 0, 3, name='Attribution') self.assertOperationAttributes(changes, 'otherapp', 0, 4, name='Book') def test_m2m_w_through_multistep_remove(self): """ A model with a m2m field that specifies a "through" model cannot be removed in the same migration as that through model as the schema will pass through an inconsistent state. The autodetector should produce two migrations to avoid this issue. """ before = self.make_project_state([self.author_with_m2m_through, self.publisher, self.contract]) after = self.make_project_state([self.publisher]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, [ "RemoveField", "RemoveField", "RemoveField", "DeleteModel", "DeleteModel" ]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="publishers", model_name='author') self.assertOperationAttributes(changes, "testapp", 0, 1, name="author", model_name='contract') self.assertOperationAttributes(changes, "testapp", 0, 2, name="publisher", model_name='contract') self.assertOperationAttributes(changes, "testapp", 0, 3, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 4, name="Contract") def test_concrete_field_changed_to_many_to_many(self): """ #23938 - Tests that changing a concrete field into a ManyToManyField first removes the concrete field and then adds the m2m field. """ before = self.make_project_state([self.author_with_former_m2m]) after = self.make_project_state([self.author_with_m2m, self.publisher]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "RemoveField", "AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name='Publisher') self.assertOperationAttributes(changes, 'testapp', 0, 1, name="publishers", model_name='author') self.assertOperationAttributes(changes, 'testapp', 0, 2, name="publishers", model_name='author') def test_many_to_many_changed_to_concrete_field(self): """ #23938 - Tests that changing a ManyToManyField into a concrete field first removes the m2m field and then adds the concrete field. """ before = self.make_project_state([self.author_with_m2m, self.publisher]) after = self.make_project_state([self.author_with_former_m2m]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveField", "AddField", "DeleteModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="publishers", model_name='author') self.assertOperationAttributes(changes, 'testapp', 0, 1, name="publishers", model_name='author') self.assertOperationAttributes(changes, 'testapp', 0, 2, name='Publisher') self.assertOperationFieldAttributes(changes, 'testapp', 0, 1, max_length=100) def test_non_circular_foreignkey_dependency_removal(self): """ If two models with a ForeignKey from one to the other are removed at the same time, the autodetector should remove them in the correct order. """ before = self.make_project_state([self.author_with_publisher, self.publisher_with_author]) after = self.make_project_state([]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveField", "RemoveField", "DeleteModel", "DeleteModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="publisher", model_name='author') self.assertOperationAttributes(changes, "testapp", 0, 1, name="author", model_name='publisher') self.assertOperationAttributes(changes, "testapp", 0, 2, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 3, name="Publisher") def test_alter_model_options(self): """Changing a model's options should make a change.""" before = self.make_project_state([self.author_empty]) after = self.make_project_state([self.author_with_options]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "testapp", 0, 0, options={ "permissions": [('can_hire', 'Can hire')], "verbose_name": "Authi", }) # Changing them back to empty should also make a change before = self.make_project_state([self.author_with_options]) after = self.make_project_state([self.author_empty]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", options={}) def test_alter_model_options_proxy(self): """Changing a proxy model's options should also make a change.""" before = self.make_project_state([self.author_proxy, self.author_empty]) after = self.make_project_state([self.author_proxy_options, self.author_empty]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="authorproxy", options={ "verbose_name": "Super Author" }) def test_set_alter_order_with_respect_to(self): """Tests that setting order_with_respect_to adds a field.""" # Make state before = self.make_project_state([self.book, self.author_with_book]) after = self.make_project_state([self.book, self.author_with_book_order_wrt]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterOrderWithRespectTo"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="author", order_with_respect_to="book") def test_add_alter_order_with_respect_to(self): """ Tests that setting order_with_respect_to when adding the FK too does things in the right order. """ # Make state before = self.make_project_state([self.author_name]) after = self.make_project_state([self.book, self.author_with_book_order_wrt]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AlterOrderWithRespectTo"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, model_name="author", name="book") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="author", order_with_respect_to="book") def test_remove_alter_order_with_respect_to(self): """ Tests that removing order_with_respect_to when removing the FK too does things in the right order. """ # Make state before = self.make_project_state([self.book, self.author_with_book_order_wrt]) after = self.make_project_state([self.author_name]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterOrderWithRespectTo", "RemoveField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="author", order_with_respect_to=None) self.assertOperationAttributes(changes, 'testapp', 0, 1, model_name="author", name="book") def test_add_model_order_with_respect_to(self): """ Tests that setting order_with_respect_to when adding the whole model does things in the right order. """ # Make state before = self.make_project_state([]) after = self.make_project_state([self.book, self.author_with_book_order_wrt]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "AlterOrderWithRespectTo"]) self.assertOperationAttributes(changes, 'testapp', 0, 1, name="author", order_with_respect_to="book") self.assertNotIn("_order", [name for name, field in changes['testapp'][0].operations[0].fields]) def test_alter_model_managers(self): """ Tests that changing the model managers adds a new operation. """ # Make state before = self.make_project_state([self.other_pony]) after = self.make_project_state([self.other_pony_food]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["AlterModelManagers"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="pony") self.assertEqual([name for name, mgr in changes['otherapp'][0].operations[0].managers], ['food_qs', 'food_mgr', 'food_mgr_kwargs']) self.assertEqual(changes['otherapp'][0].operations[0].managers[1][1].args, ('a', 'b', 1, 2)) self.assertEqual(changes['otherapp'][0].operations[0].managers[2][1].args, ('x', 'y', 3, 4)) def test_swappable_first_inheritance(self): """Tests that swappable models get their CreateModel first.""" # Make state before = self.make_project_state([]) after = self.make_project_state([self.custom_user, self.aardvark]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'thirdapp', 0, 0, name="CustomUser") self.assertOperationAttributes(changes, 'thirdapp', 0, 1, name="Aardvark") @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable_first_setting(self): """Tests that swappable models get their CreateModel first.""" with isolate_lru_cache(apps.get_swappable_settings_name): # Make state before = self.make_project_state([]) after = self.make_project_state([self.custom_user_no_inherit, self.aardvark]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'thirdapp', 0, 0, name="CustomUser") self.assertOperationAttributes(changes, 'thirdapp', 0, 1, name="Aardvark") def test_bases_first(self): """Tests that bases of other models come first.""" # Make state before = self.make_project_state([]) after = self.make_project_state([self.aardvark_based_on_author, self.author_name]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="Aardvark") def test_multiple_bases(self): """#23956 - Tests that inheriting models doesn't move *_ptr fields into AddField operations.""" A = ModelState("app", "A", [("a_id", models.AutoField(primary_key=True))]) B = ModelState("app", "B", [("b_id", models.AutoField(primary_key=True))]) C = ModelState("app", "C", [], bases=("app.A", "app.B")) D = ModelState("app", "D", [], bases=("app.A", "app.B")) E = ModelState("app", "E", [], bases=("app.A", "app.B")) # Make state before = self.make_project_state([]) after = self.make_project_state([A, B, C, D, E]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, [ "CreateModel", "CreateModel", "CreateModel", "CreateModel", "CreateModel" ]) self.assertOperationAttributes(changes, "app", 0, 0, name="A") self.assertOperationAttributes(changes, "app", 0, 1, name="B") self.assertOperationAttributes(changes, "app", 0, 2, name="C") self.assertOperationAttributes(changes, "app", 0, 3, name="D") self.assertOperationAttributes(changes, "app", 0, 4, name="E") def test_proxy_bases_first(self): """Tests that bases of proxies come first.""" # Make state before = self.make_project_state([]) after = self.make_project_state([self.author_empty, self.author_proxy, self.author_proxy_proxy]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="AuthorProxy") self.assertOperationAttributes(changes, 'testapp', 0, 2, name="AAuthorProxyProxy") def test_pk_fk_included(self): """ Tests that a relation used as the primary key is kept as part of CreateModel. """ # Make state before = self.make_project_state([]) after = self.make_project_state([self.aardvark_pk_fk_author, self.author_name]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="Aardvark") def test_first_dependency(self): """ Tests that a dependency to an app with no migrations uses __first__. """ # Load graph loader = MigrationLoader(connection) # Make state before = self.make_project_state([]) after = self.make_project_state([self.book_migrations_fk]) after.real_apps = ["migrations"] autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes(graph=loader.graph) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="Book") self.assertMigrationDependencies(changes, 'otherapp', 0, [("migrations", "__first__")]) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_last_dependency(self): """ Tests that a dependency to an app with existing migrations uses the last migration of that app. """ # Load graph loader = MigrationLoader(connection) # Make state before = self.make_project_state([]) after = self.make_project_state([self.book_migrations_fk]) after.real_apps = ["migrations"] autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes(graph=loader.graph) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="Book") self.assertMigrationDependencies(changes, 'otherapp', 0, [("migrations", "0002_second")]) def test_alter_fk_before_model_deletion(self): """ Tests that ForeignKeys are altered _before_ the model they used to refer to are deleted. """ # Make state before = self.make_project_state([self.author_name, self.publisher_with_author]) after = self.make_project_state([self.aardvark_testapp, self.publisher_with_aardvark_author]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "AlterField", "DeleteModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Aardvark") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="author") self.assertOperationAttributes(changes, 'testapp', 0, 2, name="Author") def test_fk_dependency_other_app(self): """ #23100 - Tests that ForeignKeys correctly depend on other apps' models. """ # Make state before = self.make_project_state([self.author_name, self.book]) after = self.make_project_state([self.author_with_book, self.book]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="book") self.assertMigrationDependencies(changes, 'testapp', 0, [("otherapp", "__first__")]) def test_circular_dependency_mixed_addcreate(self): """ #23315 - Tests that the dependency resolver knows to put all CreateModel before AddField and not become unsolvable. """ address = ModelState("a", "Address", [ ("id", models.AutoField(primary_key=True)), ("country", models.ForeignKey("b.DeliveryCountry", models.CASCADE)), ]) person = ModelState("a", "Person", [ ("id", models.AutoField(primary_key=True)), ]) apackage = ModelState("b", "APackage", [ ("id", models.AutoField(primary_key=True)), ("person", models.ForeignKey("a.Person", models.CASCADE)), ]) country = ModelState("b", "DeliveryCountry", [ ("id", models.AutoField(primary_key=True)), ]) # Make state before = self.make_project_state([]) after = self.make_project_state([address, person, apackage, country]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'a', 2) self.assertNumberMigrations(changes, 'b', 1) self.assertOperationTypes(changes, 'a', 0, ["CreateModel", "CreateModel"]) self.assertOperationTypes(changes, 'a', 1, ["AddField"]) self.assertOperationTypes(changes, 'b', 0, ["CreateModel", "CreateModel"]) @override_settings(AUTH_USER_MODEL="a.Tenant") def test_circular_dependency_swappable(self): """ #23322 - Tests that the dependency resolver knows to explicitly resolve swappable models. """ with isolate_lru_cache(apps.get_swappable_settings_name): tenant = ModelState("a", "Tenant", [ ("id", models.AutoField(primary_key=True)), ("primary_address", models.ForeignKey("b.Address", models.CASCADE))], bases=(AbstractBaseUser, ) ) address = ModelState("b", "Address", [ ("id", models.AutoField(primary_key=True)), ("tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)), ]) # Make state before = self.make_project_state([]) after = self.make_project_state([address, tenant]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'a', 2) self.assertOperationTypes(changes, 'a', 0, ["CreateModel"]) self.assertOperationTypes(changes, 'a', 1, ["AddField"]) self.assertMigrationDependencies(changes, 'a', 0, []) self.assertMigrationDependencies(changes, 'a', 1, [('a', 'auto_1'), ('b', 'auto_1')]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'b', 1) self.assertOperationTypes(changes, 'b', 0, ["CreateModel"]) self.assertMigrationDependencies(changes, 'b', 0, [('__setting__', 'AUTH_USER_MODEL')]) @override_settings(AUTH_USER_MODEL="b.Tenant") def test_circular_dependency_swappable2(self): """ #23322 - Tests that the dependency resolver knows to explicitly resolve swappable models but with the swappable not being the first migrated model. """ with isolate_lru_cache(apps.get_swappable_settings_name): address = ModelState("a", "Address", [ ("id", models.AutoField(primary_key=True)), ("tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)), ]) tenant = ModelState("b", "Tenant", [ ("id", models.AutoField(primary_key=True)), ("primary_address", models.ForeignKey("a.Address", models.CASCADE))], bases=(AbstractBaseUser, ) ) # Make state before = self.make_project_state([]) after = self.make_project_state([address, tenant]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'a', 2) self.assertOperationTypes(changes, 'a', 0, ["CreateModel"]) self.assertOperationTypes(changes, 'a', 1, ["AddField"]) self.assertMigrationDependencies(changes, 'a', 0, []) self.assertMigrationDependencies(changes, 'a', 1, [('__setting__', 'AUTH_USER_MODEL'), ('a', 'auto_1')]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'b', 1) self.assertOperationTypes(changes, 'b', 0, ["CreateModel"]) self.assertMigrationDependencies(changes, 'b', 0, [('a', 'auto_1')]) @override_settings(AUTH_USER_MODEL="a.Person") def test_circular_dependency_swappable_self(self): """ #23322 - Tests that the dependency resolver knows to explicitly resolve swappable models. """ with isolate_lru_cache(apps.get_swappable_settings_name): person = ModelState("a", "Person", [ ("id", models.AutoField(primary_key=True)), ("parent1", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name='children')) ]) # Make state before = self.make_project_state([]) after = self.make_project_state([person]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'a', 1) self.assertOperationTypes(changes, 'a', 0, ["CreateModel"]) self.assertMigrationDependencies(changes, 'a', 0, []) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition', side_effect=AssertionError("Should not have prompted for not null addition")) def test_add_blank_textfield_and_charfield(self, mocked_ask_method): """ #23405 - Adding a NOT NULL and blank `CharField` or `TextField` without default should not prompt for a default. """ before = self.make_project_state([self.author_empty]) after = self.make_project_state([self.author_with_biography_blank]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition') def test_add_non_blank_textfield_and_charfield(self, mocked_ask_method): """ #23405 - Adding a NOT NULL and non-blank `CharField` or `TextField` without default should prompt for a default. """ before = self.make_project_state([self.author_empty]) after = self.make_project_state([self.author_with_biography_non_blank]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() self.assertEqual(mocked_ask_method.call_count, 2) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0)
bsd-3-clause
ajnirp/servo
tests/wpt/css-tests/css-text-decor-3_dev/xhtml1print/reference/support/generate-text-emphasis-position-property-tests.py
841
3343
#!/usr/bin/env python # - * - coding: UTF-8 - * - """ This script generates tests text-emphasis-position-property-001 ~ 006 which cover all possible values of text-emphasis-position property with all combination of three main writing modes and two orientations. Only test files are generated by this script. It also outputs a list of all tests it generated in the format of Mozilla reftest.list to the stdout. """ from __future__ import unicode_literals import itertools TEST_FILE = 'text-emphasis-position-property-{:03}{}.html' REF_FILE = 'text-emphasis-position-property-{:03}-ref.html' TEST_TEMPLATE = '''<!DOCTYPE html> <meta charset="utf-8"> <title>CSS Test: text-emphasis-position: {value}, {title}</title> <link rel="author" title="Xidorn Quan" href="https://www.upsuper.org"> <link rel="author" title="Mozilla" href="https://www.mozilla.org"> <link rel="help" href="https://drafts.csswg.org/css-text-decor-3/#text-emphasis-position-property"> <meta name="assert" content="'text-emphasis-position: {value}' with 'writing-mode: {wm}' puts emphasis marks {position} the text."> <link rel="match" href="text-emphasis-position-property-{index:03}-ref.html"> <p>Pass if the emphasis marks are {position} the text below:</p> <div style="line-height: 5; text-emphasis: circle; writing-mode: {wm}; text-orientation: {orient}; text-emphasis-position: {value}">試験テスト</div> ''' SUFFIXES = ['', 'a', 'b', 'c', 'd', 'e', 'f', 'g'] WRITING_MODES = ["horizontal-tb", "vertical-rl", "vertical-lr"] POSITION_HORIZONTAL = ["over", "under"] POSITION_VERTICAL = ["right", "left"] REF_MAP_MIXED = { "over": 1, "under": 2, "right": 3, "left": 4 } REF_MAP_SIDEWAYS = { "right": 5, "left": 6 } POSITION_TEXT = { "over": "over", "under": "under", "right": "to the right of", "left": "to the left of" } suffixes = [iter(SUFFIXES) for i in range(6)] reftest_items = [] def write_file(filename, content): with open(filename, 'wb') as f: f.write(content.encode('UTF-8')) def write_test_file(idx, suffix, wm, orient, value, position): filename = TEST_FILE.format(idx, suffix) write_file(filename, TEST_TEMPLATE.format( value=value, wm=wm, orient=orient, index=idx, position=position, title=(wm if orient == "mixed" else "{}, {}".format(wm, orient)))) reftest_items.append("== {} {}".format(filename, REF_FILE.format(idx))) def write_test_files(wm, orient, pos1, pos2): idx = (REF_MAP_MIXED if orient == "mixed" else REF_MAP_SIDEWAYS)[pos1] position = POSITION_TEXT[pos1] suffix = suffixes[idx - 1] write_test_file(idx, next(suffix), wm, orient, pos1 + " " + pos2, position) write_test_file(idx, next(suffix), wm, orient, pos2 + " " + pos1, position) for wm in WRITING_MODES: if wm == "horizontal-tb": effective_pos = POSITION_HORIZONTAL ineffective_pos = POSITION_VERTICAL else: effective_pos = POSITION_VERTICAL ineffective_pos = POSITION_HORIZONTAL for pos1, pos2 in itertools.product(effective_pos, ineffective_pos): write_test_files(wm, "mixed", pos1, pos2) if wm != "horizontal-tb": write_test_files(wm, "sideways", pos1, pos2) print("# START tests from {}".format(__file__)) reftest_items.sort() for item in reftest_items: print(item) print("# END tests from {}".format(__file__))
mpl-2.0
mufaddalq/cloudstack-datera-driver
test/integration/component/test_redundant_router_services.py
1
16945
# 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 nose.plugins.attrib import attr from marvin.integration.lib.base import * from marvin.integration.lib.utils import * from marvin.integration.lib.common import * #Import Local Modules from marvin.cloudstackTestCase import cloudstackTestCase from marvin.cloudstackAPI import * class Services: """Test Services for customer defects """ def __init__(self): self.services = { "account": { "email": "test@test.com", "firstname": "Test", "lastname": "User", "username": "test", # Random characters are appended for unique # username "password": "password", }, "service_offering": { "name": "Tiny Instance", "displaytext": "Tiny Instance", "cpunumber": 1, "cpuspeed": 100, "memory": 128, }, "disk_offering": { "displaytext": "Small", "name": "Small", "disksize": 1 }, "virtual_machine": { "displayname": "Test VM", "username": "root", "password": "password", "ssh_port": 22, "hypervisor": 'XenServer', "privateport": 22, "publicport": 22, "protocol": 'TCP', }, "static_nat": { "startport": 22, "endport": 22, "protocol": "TCP" }, "network_offering": { "name": 'Network offering-RVR services', "displaytext": 'Network off-RVR services', "guestiptype": 'Isolated', "supportedservices": 'Vpn,Dhcp,Dns,SourceNat,PortForwarding,Firewall,Lb,UserData,StaticNat', "traffictype": 'GUEST', "availability": 'Optional', "serviceProviderList": { "Vpn": 'VirtualRouter', "Dhcp": 'VirtualRouter', "Dns": 'VirtualRouter', "SourceNat": 'VirtualRouter', "PortForwarding": 'VirtualRouter', "Firewall": 'VirtualRouter', "Lb": 'VirtualRouter', "UserData": 'VirtualRouter', "StaticNat": 'VirtualRouter', }, "serviceCapabilityList": { "SourceNat": { "SupportedSourceNatTypes": "peraccount", "RedundantRouter": "true", }, "lb": { "SupportedLbIsolation": "dedicated" }, }, }, "host": { "username": "root", "password": "password", "publicport": 22, }, "network": { "name": "Test Network", "displaytext": "Test Network", }, "lbrule": { "name": "SSH", "alg": "roundrobin", # Algorithm used for load balancing "privateport": 22, "publicport": 22, "openfirewall": True, }, "natrule": { "privateport": 22, "publicport": 22, "protocol": "TCP" }, "natrule_221": { "privateport": 22, "publicport": 221, "protocol": "TCP" }, "fw_rule": { "startport": 1, "endport": 6000, "cidr": '55.55.0.0/11', # Any network (For creating FW rule) "protocol": 'TCP', }, "ostype": 'CentOS 5.3 (64-bit)', "sleep": 60, } class TestEnableVPNOverRvR(cloudstackTestCase): @classmethod def setUpClass(cls): cls.api_client = super( TestEnableVPNOverRvR, cls ).getClsTestClient().getApiClient() cls.services = Services().services # Get Zone, Domain and templates cls.domain = get_domain(cls.api_client, cls.services) cls.zone = get_zone(cls.api_client, cls.services) cls.template = get_template( cls.api_client, cls.zone.id, cls.services["ostype"] ) cls.services["virtual_machine"]["zoneid"] = cls.zone.id cls.services["virtual_machine"]["template"] = cls.template.id cls.service_offering = ServiceOffering.create( cls.api_client, cls.services["service_offering"] ) cls.network_offering = NetworkOffering.create( cls.api_client, cls.services["network_offering"], conservemode=True ) # Enable Network offering cls.network_offering.update(cls.api_client, state='Enabled') cls._cleanup = [ cls.service_offering, cls.network_offering, ] return @classmethod def tearDownClass(cls): try: #Cleanup resources used cleanup_resources(cls.api_client, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def setUp(self): self.apiclient = self.testClient.getApiClient() self.dbclient = self.testClient.getDbConnection() self.account = Account.create( self.apiclient, self.services["account"], admin=True, domainid=self.domain.id ) self.cleanup = [] self.cleanup.insert(0, self.account) return def tearDown(self): try: cleanup_resources(self.apiclient, self.cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return @attr(tags=["advanced", "advancedns", "ssh"]) def test_enableVPNOverRvR(self): """Test redundant router internals """ # Steps to validate # 1. listNetworks should show the created network in allocated state # 2. listRouters returns no running routers # 3. VMs should be deployed and in Running state # 4. should list MASTER and BACKUP routers # 5. listPublicIpAddresses for networkid should show acquired IP addr # 6. listRemoteAccessVpns for the network associated should show VPN # created # 7. listRemoteAccessVpns for the network associated should return # empty response # Creating network using the network offering created self.debug("Creating network with network offering: %s" % self.network_offering.id) network = Network.create( self.apiclient, self.services["network"], accountid=self.account.name, domainid=self.account.domainid, networkofferingid=self.network_offering.id, zoneid=self.zone.id ) self.debug("Created network with ID: %s" % network.id) networks = Network.list( self.apiclient, id=network.id, listall=True ) self.assertEqual( isinstance(networks, list), True, "List networks should return a valid response for created network" ) nw_response = networks[0] self.debug("Network state: %s" % nw_response.state) self.assertEqual( nw_response.state, "Allocated", "The network should be in allocated state after creation" ) self.debug("Listing routers for network: %s" % network.name) routers = Router.list( self.apiclient, networkid=network.id, listall=True ) self.assertEqual( routers, None, "Routers should not be spawned when network is in allocated state" ) self.debug("Deploying VM in account: %s" % self.account.name) # Spawn an instance in that network virtual_machine = VirtualMachine.create( self.apiclient, self.services["virtual_machine"], accountid=self.account.name, domainid=self.account.domainid, serviceofferingid=self.service_offering.id, networkids=[str(network.id)] ) self.debug("Deployed VM in network: %s" % network.id) vms = VirtualMachine.list( self.apiclient, id=virtual_machine.id, listall=True ) self.assertEqual( isinstance(vms, list), True, "List Vms should return a valid list" ) vm = vms[0] self.assertEqual( vm.state, "Running", "Vm should be in running state after deployment" ) self.debug("Listing routers for network: %s" % network.name) routers = Router.list( self.apiclient, networkid=network.id, listall=True ) self.assertEqual( isinstance(routers, list), True, "list router should return Master and backup routers" ) self.assertEqual( len(routers), 2, "Length of the list router should be 2 (Backup & master)" ) self.debug("Associating public IP for network: %s" % network.name) public_ip = PublicIPAddress.create( self.apiclient, accountid=self.account.name, zoneid=self.zone.id, domainid=self.account.domainid, networkid=network.id ) self.debug("Associated %s with network %s" % ( public_ip.ipaddress.ipaddress, network.id )) self.debug("Creating a remote access VPN for account: %s" % self.account.name) try: vpn = Vpn.create( self.apiclient, publicipid=public_ip.ipaddress.id, account=self.account.name, domainid=self.account.domainid ) except Exception as e: self.fail("Failed to create VPN for account: %s - %s" % ( self.account.name, e)) try: vpnuser = VpnUser.create( self.apiclient, username="root", password="password", account=self.account.name, domainid=self.account.domainid ) except Exception as e: self.fail("Failed to create VPN user: %s" % e) self.debug("Checking if the remote access VPN is created or not?") remote_vpns = Vpn.list( self.apiclient, account=self.account.name, domainid=self.account.domainid, publicipid=public_ip.ipaddress.id, listall=True ) self.assertEqual( isinstance(remote_vpns, list), True, "List remote VPNs should not return empty response" ) self.debug("Deleting the remote access VPN for account: %s" % self.account.name) try: vpn.delete(self.apiclient) except Exception as e: self.fail("Failed to delete VPN : %s" % e) self.debug("Checking if the remote access VPN is created or not?") remote_vpns = Vpn.list( self.apiclient, account=self.account.name, domainid=self.account.domainid, publicipid=public_ip.ipaddress.id, listall=True ) self.assertEqual( remote_vpns, None, "List remote VPNs should not return empty response" ) return
apache-2.0
Solinea/horizon
openstack_dashboard/dashboards/project/data_processing/utils/workflow_helpers.py
30
10029
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from django.utils.translation import ugettext_lazy as _ from horizon import forms from horizon import workflows from openstack_dashboard.api import network LOG = logging.getLogger(__name__) class Parameter(object): def __init__(self, config): self.name = config['name'] self.description = config.get('description', "No description") self.required = not config['is_optional'] self.default_value = config.get('default_value', None) self.initial_value = self.default_value self.param_type = config['config_type'] self.priority = int(config.get('priority', 2)) self.choices = config.get('config_values', None) def build_control(parameter): attrs = {"priority": parameter.priority, "placeholder": parameter.default_value} if parameter.param_type == "string": return forms.CharField( widget=forms.TextInput(attrs=attrs), label=parameter.name, required=(parameter.required and parameter.default_value is None), help_text=parameter.description, initial=parameter.initial_value) if parameter.param_type == "int": return forms.IntegerField( widget=forms.TextInput(attrs=attrs), label=parameter.name, required=parameter.required, help_text=parameter.description, initial=parameter.initial_value) elif parameter.param_type == "bool": return forms.BooleanField( widget=forms.CheckboxInput(attrs=attrs), label=parameter.name, required=False, initial=parameter.initial_value, help_text=parameter.description) elif parameter.param_type == "dropdown": return forms.ChoiceField( widget=forms.Select(attrs=attrs), label=parameter.name, required=parameter.required, choices=parameter.choices, help_text=parameter.description) def _create_step_action(name, title, parameters, advanced_fields=None, service=None): class_fields = {} contributes_field = () for param in parameters: field_name = "CONF:" + service + ":" + param.name contributes_field += (field_name,) class_fields[field_name] = build_control(param) if advanced_fields is not None: for ad_field_name, ad_field_value in advanced_fields: class_fields[ad_field_name] = ad_field_value action_meta = type('Meta', (object, ), dict(help_text_template=("project" "/data_processing." "nodegroup_templates/" "_fields_help.html"))) class_fields['Meta'] = action_meta action = type(str(title), (workflows.Action,), class_fields) step_meta = type('Meta', (object,), dict(name=title)) step = type(str(name), (workflows.Step, ), dict(name=name, process_name=name, action_class=action, contributes=contributes_field, Meta=step_meta)) return step def build_node_group_fields(action, name, template, count, serialized=None): action.fields[name] = forms.CharField( label=_("Name"), widget=forms.TextInput()) action.fields[template] = forms.CharField( label=_("Node group cluster"), widget=forms.HiddenInput()) action.fields[count] = forms.IntegerField( label=_("Count"), min_value=0, widget=forms.HiddenInput()) action.fields[serialized] = forms.CharField( widget=forms.HiddenInput()) def parse_configs_from_context(context, defaults): configs_dict = dict() for key, val in context.items(): if str(key).startswith("CONF"): key_split = str(key).split(":") service = key_split[1] config = key_split[2] if service not in configs_dict: configs_dict[service] = dict() if (val is None or unicode(defaults[service][config]) == unicode(val)): continue configs_dict[service][config] = val return configs_dict def get_security_groups(request, security_group_ids): security_groups = [] for group in security_group_ids or []: try: security_groups.append(network.security_group_get( request, group)) except Exception: LOG.info(_('Unable to retrieve security group %(group)s.') % {'group': group}) security_groups.append({'name': group}) return security_groups def get_plugin_and_hadoop_version(request): plugin_name = None hadoop_version = None if request.REQUEST.get("plugin_name"): plugin_name = request.REQUEST["plugin_name"] hadoop_version = request.REQUEST["hadoop_version"] return (plugin_name, hadoop_version) def clean_node_group(node_group): node_group_copy = dict((key, value) for key, value in node_group.items() if value) for key in ["id", "created_at", "updated_at"]: if key in node_group_copy: node_group_copy.pop(key) return node_group_copy class PluginAndVersionMixin(object): def _generate_plugin_version_fields(self, sahara): plugins = sahara.plugins.list() plugin_choices = [(plugin.name, plugin.title) for plugin in plugins] self.fields["plugin_name"] = forms.ChoiceField( label=_("Plugin Name"), choices=plugin_choices, widget=forms.Select(attrs={"class": "plugin_name_choice"})) for plugin in plugins: field_name = plugin.name + "_version" choice_field = forms.ChoiceField( label=_("Version"), choices=[(version, version) for version in plugin.versions], widget=forms.Select( attrs={"class": "plugin_version_choice " + field_name + "_choice"}) ) self.fields[field_name] = choice_field class PatchedDynamicWorkflow(workflows.Workflow): """Overrides Workflow to fix its issues.""" def _ensure_dynamic_exist(self): if not hasattr(self, 'dynamic_steps'): self.dynamic_steps = list() def _register_step(self, step): # Use that method instead of 'register' to register step. # Note that a step could be registered in descendant class constructor # only before this class constructor is invoked. self._ensure_dynamic_exist() self.dynamic_steps.append(step) def _order_steps(self): # overrides method of Workflow # crutch to fix https://bugs.launchpad.net/horizon/+bug/1196717 # and another not filed issue that dynamic creation of tabs is # not thread safe self._ensure_dynamic_exist() self._registry = dict([(step, step(self)) for step in self.dynamic_steps]) return list(self.default_steps) + self.dynamic_steps class ServiceParametersWorkflow(PatchedDynamicWorkflow): """Base class for Workflows having services tabs with parameters.""" def _populate_tabs(self, general_parameters, service_parameters): # Populates tabs for 'general' and service parameters # Also populates defaults and initial values self.defaults = dict() self._init_step('general', 'General Parameters', general_parameters) for service, parameters in service_parameters.items(): self._init_step(service, service + ' Parameters', parameters) def _init_step(self, service, title, parameters): if not parameters: return self._populate_initial_values(service, parameters) step = _create_step_action(service, title=title, parameters=parameters, service=service) self.defaults[service] = dict() for param in parameters: self.defaults[service][param.name] = param.default_value self._register_step(step) def _set_configs_to_copy(self, configs): self.configs_to_copy = configs def _populate_initial_values(self, service, parameters): if not hasattr(self, 'configs_to_copy'): return configs = self.configs_to_copy for param in parameters: if (service in configs and param.name in configs[service]): param.initial_value = configs[service][param.name] class StatusFormatMixin(workflows.Workflow): def __init__(self, request, context_seed, entry_point, *args, **kwargs): super(StatusFormatMixin, self).__init__(request, context_seed, entry_point, *args, **kwargs) def format_status_message(self, message): error_description = getattr(self, 'error_description', None) if error_description: return error_description else: return message % self.context[self.name_property]
apache-2.0
rbian/tp-libvirt
libguestfs/tests/guestfs_list_operations.py
8
8006
import logging import re from autotest.client.shared import error from virttest import utils_test def test_list_with_mount(vm, params): """ 1) Fall into guestfish session w/o inspector 2) Do some necessary check 3) Try to mount root filesystem to / """ params['libvirt_domain'] = vm.name params['gf_inspector'] = False gf = utils_test.libguestfs.GuestfishTools(params) # Launch run_result = gf.run() if run_result.exit_status: gf.close_session() raise error.TestFail("Can not launch:%s" % run_result) logging.info("Launch successfully.") # List filesystems list_fs_result = gf.list_filesystems() if list_fs_result.exit_status: gf.close_session() raise error.TestFail("List filesystems failed:%s" % list_fs_result) logging.info("List filesystems successfully.") # List partitions list_part_result = gf.list_partitions() if list_part_result.exit_status: gf.close_session() raise error.TestFail("List partitions failed:%s" % list_part_result) logging.info("List partitions successfully.") # List devices list_dev_result = gf.list_devices() if list_dev_result.exit_status: gf.close_session() raise error.TestFail("List devices failed:%s" % list_dev_result) logging.info("List devices successfully.") # Mount root filesystem roots, rooto = gf.get_root() if roots is False: gf.close_session() raise error.TestFail("Can not get root filesystem in guestfish.") mount_result = gf.mount(rooto.strip(), "/") if mount_result.exit_status: gf.close_session() raise error.TestFail("Mount filesystem failed:%s" % mount_result) logging.debug("Mount filesystem successfully.") # List mounts list_df_result = gf.df() if list_df_result.exit_status: gf.close_session() raise error.TestFail("Df failed:%s" % list_df_result) logging.info("Df successfully.") def test_list_without_mount(vm, params): """ 1) Fall into guestfish session w/o inspector 2) Do some necessary check 3) Try to list umounted partitions """ params['libvirt_domain'] = vm.name params['gf_inspector'] = False gf = utils_test.libguestfs.GuestfishTools(params) # Launch run_result = gf.run() if run_result.exit_status: gf.close_session() raise error.TestFail("Can not launch:%s" % run_result) logging.info("Launch successfully.") # List filesystems list_fs_result = gf.list_filesystems() if list_fs_result.exit_status: gf.close_session() raise error.TestFail("List filesystems failed:%s" % list_fs_result) logging.info("List filesystems successfully.") # List partitions list_part_result = gf.list_partitions() if list_part_result.exit_status: gf.close_session() raise error.TestFail("List partitions failed:%s" % list_part_result) logging.info("List partitions successfully.") # List devices list_dev_result = gf.list_devices() if list_dev_result.exit_status: gf.close_session() raise error.TestFail("List devices failed:%s" % list_dev_result) logging.info("List devices successfully.") # List mounts list_df_result = gf.df() gf.close_session() logging.debug(list_df_result) if list_df_result.exit_status == 0: raise error.TestFail("Df successfully unexpected.") else: if not re.search("call.*mount.*first", list_df_result.stdout): raise error.TestFail("Unknown error.") logging.info("Df failed as expected.") logging.info("Test end as expected.") def test_list_without_launch(vm, params): """ 1) Fall into guestfish session w/o inspector 2) Do some necessary check w/o launch 3) Try to mount root filesystem to / """ # Get root filesystem before test params['libvirt_domain'] = vm.name params['gf_inspector'] = True gf = utils_test.libguestfs.GuestfishTools(params) roots, rootfs = gf.get_root() gf.close_session() if roots is False: raise error.TestError("Can not get root filesystem " "in guestfish before test") params['gf_inspector'] = False gf = utils_test.libguestfs.GuestfishTools(params) # Do not launch # List filesystems list_fs_result = gf.list_filesystems() logging.debug(list_fs_result) if list_fs_result.exit_status == 0: gf.close_session() raise error.TestFail("List filesystems successfully") else: if not re.search("call\slaunch\sbefore", list_fs_result.stdout): gf.close_session() raise error.TestFail("Unknown error.") # List partitions list_part_result = gf.list_partitions() logging.debug(list_part_result) if list_part_result.exit_status == 0: gf.close_session() raise error.TestFail("List partitions successfully") else: if not re.search("call\slaunch\sbefore", list_part_result.stdout): gf.close_session() raise error.TestFail("Unknown error.") # List devices list_dev_result = gf.list_devices() logging.debug(list_dev_result) if list_dev_result.exit_status == 0: gf.close_session() raise error.TestFail("List devices successfully") else: if not re.search("call\slaunch\sbefore", list_dev_result.stdout): gf.close_session() raise error.TestFail("Unknown error.") # Mount root filesystem mount_result = gf.mount(rootfs, "/") logging.debug(mount_result) gf.close_session() if mount_result.exit_status == 0: raise error.TestFail("Mount filesystem successfully") else: if not re.search("call\slaunch\sbefore", mount_result.stdout): raise error.TestFail("Unknown error.") logging.info("Test end as expected.") def test_list_with_inspector(vm, params): """ 1) Fall into guestfish session w/ mounting root filesystem 2) Do some necessary check """ # Get root filesystem before test params['libvirt_domain'] = vm.name params['gf_inspector'] = True gf = utils_test.libguestfs.GuestfishTools(params) roots, rootfs = gf.get_root() gf.close_session() if roots is False: raise error.TestError("Can not get root filesystem " "in guestfish before test") params['gf_inspector'] = False params['mount_options'] = "%s:/" % rootfs gf = utils_test.libguestfs.GuestfishTools(params) # List filesystems list_fs_result = gf.list_filesystems() logging.debug(list_fs_result) if list_fs_result.exit_status: gf.close_session() raise error.TestFail("List filesystems failed") logging.info("List filesystems successfully.") # List partitions list_part_result = gf.list_partitions() logging.debug(list_part_result) if list_part_result.exit_status: gf.close_session() raise error.TestFail("List partitions failed") logging.info("List partitions successfully.") # List devices list_dev_result = gf.list_devices() logging.debug(list_dev_result) if list_dev_result.exit_status: gf.close_session() raise error.TestFail("List devices failed") logging.info("List devices successfully.") # List mounts list_df_result = gf.df() gf.close_session() logging.debug(list_df_result) if list_df_result.exit_status: raise error.TestFail("Df failed") logging.info("Df successfully.") def run(test, params, env): """ Test guestfs with list commands: list-partitions, list-filesystems list-devices """ vm_name = params.get("main_vm") vm = env.get_vm(vm_name) # guestfish cannot operate living vm if vm.is_alive(): vm.destroy() operation = params.get("list_operation") eval("test_%s(vm, params)" % operation)
gpl-2.0
heartsucker/securedrop
securedrop/tests/functional/source_navigation_steps.py
2
10246
import tempfile import time from selenium.webdriver.common.action_chains import ActionChains class SourceNavigationStepsMixin: def _is_on_source_homepage(self): return self.wait_for( lambda: self.driver.find_element_by_id("source-index") ) def _is_logged_in(self): return self.wait_for( lambda: self.driver.find_element_by_id("logout") ) def _is_on_lookup_page(self): return self.wait_for(lambda: self.driver.find_element_by_id("upload")) def _source_visits_source_homepage(self): self.driver.get(self.source_location) assert self._is_on_source_homepage() def _source_clicks_submit_documents_on_homepage(self): # First move the cursor to a known position in case it happens to # be hovering over one of the buttons we are testing below. header_image = self.driver.find_element_by_css_selector(".header") ActionChains(self.driver).move_to_element(header_image).perform() # It's the source's first time visiting this SecureDrop site, so they # choose to "Submit Documents". submit_button = self.driver.find_element_by_id("submit-documents-button") submit_button_icon = self.driver.find_element_by_css_selector( "a#submit-documents-button > img.off-hover" ) self.wait_for(lambda: submit_button_icon.is_displayed()) # The source hovers their cursor over the button, and the visual style # of the button changes to encourage them to click it. ActionChains(self.driver).move_to_element(submit_button).perform() # Let's make sure toggling the icon image with the hover state is working. hovered_icon_selector = "a#submit-documents-button > img.on-hover" submit_button_hover_icon = self.driver.find_element_by_css_selector(hovered_icon_selector) self.wait_for(lambda: submit_button_hover_icon.is_displayed()) # The source clicks the submit button. submit_button.click() def _source_chooses_to_submit_documents(self): self._source_clicks_submit_documents_on_homepage() codename = self.driver.find_element_by_css_selector("#codename") assert len(codename.text) > 0 self.source_name = codename.text def _source_shows_codename(self): content = self.driver.find_element_by_id("codename-hint-content") assert not content.is_displayed() self.safe_click_by_id("codename-hint-show") self.wait_for(lambda: content.is_displayed()) assert content.is_displayed() content_content = self.driver.find_element_by_css_selector("#codename-hint-content p") assert content_content.text == self.source_name def _source_hides_codename(self): content = self.driver.find_element_by_id("codename-hint-content") assert content.is_displayed() self.safe_click_by_id("codename-hint-hide") self.wait_for(lambda: not content.is_displayed()) assert not content.is_displayed() def _source_sees_no_codename(self): codename = self.driver.find_elements_by_css_selector(".code-reminder") assert len(codename) == 0 def _source_chooses_to_login(self): self.driver.find_element_by_id("login-button").click() self.wait_for(lambda: self.driver.find_elements_by_id("login-with-existing-codename")) def _source_hits_cancel_at_login_page(self): self.driver.find_element_by_id("cancel").click() self.driver.get(self.source_location) assert self._is_on_source_homepage() def _source_proceeds_to_login(self): codename_input = self.driver.find_element_by_id("login-with-existing-codename") codename_input.send_keys(self.source_name) self.safe_click_by_id("login") # Check that we've logged in assert self._is_logged_in() replies = self.driver.find_elements_by_id("replies") assert len(replies) == 1 def _source_enters_codename_in_login_form(self): codename_input = self.driver.find_element_by_id("login-with-existing-codename") codename_input.send_keys("ascension hypertext concert synopses") def _source_hits_cancel_at_submit_page(self): self.driver.find_element_by_id("cancel").click() if not hasattr(self, "accept_languages"): headline = self.driver.find_element_by_class_name("headline") assert "Submit Files or Messages" == headline.text def _source_continues_to_submit_page(self): continue_button = self.driver.find_element_by_id("continue-button") continue_button_icon = self.driver.find_element_by_css_selector( "button#continue-button > img.off-hover" ) assert continue_button_icon.is_displayed() # Hover over the continue button test toggle the icon images # with the hover state. ActionChains(self.driver).move_to_element(continue_button).perform() assert continue_button_icon.is_displayed() is False continue_button_hover_icon = self.driver.find_element_by_css_selector( "button#continue-button img.on-hover" ) assert continue_button_hover_icon.is_displayed() continue_button.click() def submit_page_loaded(): if not hasattr(self, "accept_languages"): headline = self.driver.find_element_by_class_name("headline") assert "Submit Files or Messages" == headline.text self.wait_for(submit_page_loaded) def _source_submits_a_file(self): with tempfile.NamedTemporaryFile() as file: file.write(self.secret_message.encode('utf-8')) file.seek(0) filename = file.name file_upload_box = self.driver.find_element_by_css_selector("[name=fh]") file_upload_box.send_keys(filename) submit_button = self.driver.find_element_by_id("submit-doc-button") ActionChains(self.driver).move_to_element(submit_button).perform() toggled_submit_button_icon = self.driver.find_element_by_css_selector( "button#submit-doc-button img.on-hover" ) assert toggled_submit_button_icon.is_displayed() submit_button.click() self.wait_for_source_key(self.source_name) def file_submitted(): if not hasattr(self, "accept_languages"): notification = self.driver.find_element_by_css_selector(".success") expected_notification = "Thank you for sending this information to us" assert expected_notification in notification.text # Allow extra time for file uploads self.wait_for(file_submitted, timeout=(self.timeout * 3)) # allow time for reply key to be generated time.sleep(self.timeout) def _source_submits_a_message(self): self._source_enters_text_in_message_field() self._source_clicks_submit_button_on_submission_page() def message_submitted(): if not hasattr(self, "accept_languages"): notification = self.driver.find_element_by_css_selector(".success") assert "Thank" in notification.text self.wait_for(message_submitted) # allow time for reply key to be generated time.sleep(self.timeout) def _source_enters_text_in_message_field(self): text_box = self.driver.find_element_by_css_selector("[name=msg]") text_box.send_keys(self.secret_message) def _source_clicks_submit_button_on_submission_page(self): submit_button = self.driver.find_element_by_id("submit-doc-button") submit_button.click() def _source_deletes_a_journalist_reply(self): # Get the reply filename so we can use IDs to select the delete buttons reply_filename_element = self.driver.find_element_by_name("reply_filename") reply_filename = reply_filename_element.get_attribute("value") delete_button_id = "delete-reply-{}".format(reply_filename) delete_button = self.driver.find_element_by_id(delete_button_id) delete_button.click() def confirm_displayed(): confirm_button_id = "confirm-delete-reply-button-{}".format(reply_filename) confirm_button = self.driver.find_element_by_id(confirm_button_id) confirm_button.location_once_scrolled_into_view assert confirm_button.is_displayed() self.wait_for(confirm_displayed) confirm_button_id = "confirm-delete-reply-button-{}".format(reply_filename) confirm_button = self.driver.find_element_by_id(confirm_button_id) confirm_button.click() def reply_deleted(): if not hasattr(self, "accept_languages"): notification = self.driver.find_element_by_class_name("notification") assert "Reply deleted" in notification.text self.wait_for(reply_deleted) def _source_logs_out(self): logout = self.driver.find_element_by_id("logout") logout.send_keys(" ") logout.click() self.wait_for(lambda: ("Submit for the first time" in self.driver.page_source)) def _source_not_found(self): self.driver.get(self.source_location + "/unlikely") message = self.driver.find_element_by_id("page-not-found") assert message.is_displayed() def _source_visits_use_tor(self): self.driver.get(self.source_location + "/use-tor") def _source_tor2web_warning(self): self.driver.get(self.source_location + "/tor2web-warning") def _source_why_journalist_key(self): self.driver.get(self.source_location + "/why-journalist-key") def _source_waits_for_session_to_timeout(self, session_length_minutes): time.sleep(session_length_minutes * 60 + 0.1) def _source_sees_session_timeout_message(self): notification = self.driver.find_element_by_css_selector(".important") if not hasattr(self, "accept_languages"): expected_text = "Your session timed out due to inactivity." assert expected_text in notification.text
agpl-3.0
JioCloud/python-ironicclient
ironicclient/common/http.py
2
13727
# -*- coding: utf-8 -*- # # Copyright 2012 OpenStack LLC. # 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 import json import logging import os import socket import ssl from keystoneclient import adapter import six import six.moves.urllib.parse as urlparse from ironicclient import exc LOG = logging.getLogger(__name__) USER_AGENT = 'python-ironicclient' CHUNKSIZE = 1024 * 64 # 64kB API_VERSION = '/v1' def _trim_endpoint_api_version(url): """Trim API version and trailing slash from endpoint.""" return url.rstrip('/').rstrip(API_VERSION) def _extract_error_json(body): """Return error_message from the HTTP response body.""" error_json = {} try: body_json = json.loads(body) if 'error_message' in body_json: raw_msg = body_json['error_message'] error_json = json.loads(raw_msg) except ValueError: pass return error_json class HTTPClient(object): def __init__(self, endpoint, **kwargs): self.endpoint = endpoint self.endpoint_trimmed = _trim_endpoint_api_version(endpoint) self.auth_token = kwargs.get('token') self.auth_ref = kwargs.get('auth_ref') self.connection_params = self.get_connection_params(endpoint, **kwargs) @staticmethod def get_connection_params(endpoint, **kwargs): parts = urlparse.urlparse(endpoint) path = _trim_endpoint_api_version(parts.path) _args = (parts.hostname, parts.port, path) _kwargs = {'timeout': (float(kwargs.get('timeout')) if kwargs.get('timeout') else 600)} if parts.scheme == 'https': _class = VerifiedHTTPSConnection _kwargs['ca_file'] = kwargs.get('ca_file', None) _kwargs['cert_file'] = kwargs.get('cert_file', None) _kwargs['key_file'] = kwargs.get('key_file', None) _kwargs['insecure'] = kwargs.get('insecure', False) elif parts.scheme == 'http': _class = six.moves.http_client.HTTPConnection else: msg = 'Unsupported scheme: %s' % parts.scheme raise exc.EndpointException(msg) return (_class, _args, _kwargs) def get_connection(self): _class = self.connection_params[0] try: return _class(*self.connection_params[1][0:2], **self.connection_params[2]) except six.moves.http_client.InvalidURL: raise exc.EndpointException() def log_curl_request(self, method, url, kwargs): curl = ['curl -i -X %s' % method] for (key, value) in kwargs['headers'].items(): header = '-H \'%s: %s\'' % (key, value) curl.append(header) conn_params_fmt = [ ('key_file', '--key %s'), ('cert_file', '--cert %s'), ('ca_file', '--cacert %s'), ] for (key, fmt) in conn_params_fmt: value = self.connection_params[2].get(key) if value: curl.append(fmt % value) if self.connection_params[2].get('insecure'): curl.append('-k') if 'body' in kwargs: curl.append('-d \'%s\'' % kwargs['body']) curl.append(urlparse.urljoin(self.endpoint_trimmed, url)) LOG.debug(' '.join(curl)) @staticmethod def log_http_response(resp, body=None): status = (resp.version / 10.0, resp.status, resp.reason) dump = ['\nHTTP/%.1f %s %s' % status] dump.extend(['%s: %s' % (k, v) for k, v in resp.getheaders()]) dump.append('') if body: dump.extend([body, '']) LOG.debug('\n'.join(dump)) def _make_connection_url(self, url): (_class, _args, _kwargs) = self.connection_params base_url = _args[2] return '%s/%s' % (base_url, url.lstrip('/')) def _http_request(self, url, method, **kwargs): """Send an http request with the specified characteristics. Wrapper around httplib.HTTP(S)Connection.request to handle tasks such as setting headers and error handling. """ # Copy the kwargs so we can reuse the original in case of redirects kwargs['headers'] = copy.deepcopy(kwargs.get('headers', {})) kwargs['headers'].setdefault('User-Agent', USER_AGENT) if self.auth_token: kwargs['headers'].setdefault('X-Auth-Token', self.auth_token) self.log_curl_request(method, url, kwargs) conn = self.get_connection() try: conn_url = self._make_connection_url(url) conn.request(method, conn_url, **kwargs) resp = conn.getresponse() except socket.gaierror as e: message = ("Error finding address for %(url)s: %(e)s" % dict(url=url, e=e)) raise exc.EndpointNotFound(message) except (socket.error, socket.timeout) as e: endpoint = self.endpoint message = ("Error communicating with %(endpoint)s %(e)s" % dict(endpoint=endpoint, e=e)) raise exc.ConnectionRefused(message) body_iter = ResponseBodyIterator(resp) # Read body into string if it isn't obviously image data body_str = None if resp.getheader('content-type', None) != 'application/octet-stream': body_str = ''.join([chunk for chunk in body_iter]) self.log_http_response(resp, body_str) body_iter = six.StringIO(body_str) else: self.log_http_response(resp) if 400 <= resp.status < 600: LOG.warn("Request returned failure status.") error_json = _extract_error_json(body_str) raise exc.from_response( resp, error_json.get('faultstring'), error_json.get('debuginfo'), method, url) elif resp.status in (301, 302, 305): # Redirected. Reissue the request to the new location. return self._http_request(resp['location'], method, **kwargs) elif resp.status == 300: raise exc.from_response(resp, method=method, url=url) return resp, body_iter def json_request(self, method, url, **kwargs): kwargs.setdefault('headers', {}) kwargs['headers'].setdefault('Content-Type', 'application/json') kwargs['headers'].setdefault('Accept', 'application/json') if 'body' in kwargs: kwargs['body'] = json.dumps(kwargs['body']) resp, body_iter = self._http_request(url, method, **kwargs) content_type = resp.getheader('content-type', None) if resp.status == 204 or resp.status == 205 or content_type is None: return resp, list() if 'application/json' in content_type: body = ''.join([chunk for chunk in body_iter]) try: body = json.loads(body) except ValueError: LOG.error('Could not decode response body as JSON') else: body = None return resp, body def raw_request(self, method, url, **kwargs): kwargs.setdefault('headers', {}) kwargs['headers'].setdefault('Content-Type', 'application/octet-stream') return self._http_request(url, method, **kwargs) class VerifiedHTTPSConnection(six.moves.http_client.HTTPSConnection): """httplib-compatibile connection using client-side SSL authentication :see http://code.activestate.com/recipes/ 577548-https-httplib-client-connection-with-certificate-v/ """ def __init__(self, host, port, key_file=None, cert_file=None, ca_file=None, timeout=None, insecure=False): six.moves.http_client.HTTPSConnection.__init__(self, host, port, key_file=key_file, cert_file=cert_file) self.key_file = key_file self.cert_file = cert_file if ca_file is not None: self.ca_file = ca_file else: self.ca_file = self.get_system_ca_file() self.timeout = timeout self.insecure = insecure def connect(self): """Connect to a host on a given (SSL) port. If ca_file is pointing somewhere, use it to check Server Certificate. Redefined/copied and extended from httplib.py:1105 (Python 2.6.x). This is needed to pass cert_reqs=ssl.CERT_REQUIRED as parameter to ssl.wrap_socket(), which forces SSL to check server certificate against our client certificate. """ sock = socket.create_connection((self.host, self.port), self.timeout) if self._tunnel_host: self.sock = sock self._tunnel() if self.insecure is True: kwargs = {'cert_reqs': ssl.CERT_NONE} else: kwargs = {'cert_reqs': ssl.CERT_REQUIRED, 'ca_certs': self.ca_file} if self.cert_file: kwargs['certfile'] = self.cert_file if self.key_file: kwargs['keyfile'] = self.key_file self.sock = ssl.wrap_socket(sock, **kwargs) @staticmethod def get_system_ca_file(): """Return path to system default CA file.""" # Standard CA file locations for Debian/Ubuntu, RedHat/Fedora, # Suse, FreeBSD/OpenBSD ca_path = ['/etc/ssl/certs/ca-certificates.crt', '/etc/pki/tls/certs/ca-bundle.crt', '/etc/ssl/ca-bundle.pem', '/etc/ssl/cert.pem'] for ca in ca_path: if os.path.exists(ca): return ca return None class SessionClient(adapter.LegacyJsonAdapter): """HTTP client based on Keystone client session.""" def _http_request(self, url, method, **kwargs): kwargs.setdefault('user_agent', USER_AGENT) kwargs.setdefault('auth', self.auth) endpoint_filter = kwargs.setdefault('endpoint_filter', {}) endpoint_filter.setdefault('interface', self.interface) endpoint_filter.setdefault('service_type', self.service_type) endpoint_filter.setdefault('region_name', self.region_name) resp = self.session.request(url, method, raise_exc=False, **kwargs) if 400 <= resp.status_code < 600: error_json = _extract_error_json(resp.content) raise exc.from_response(resp, error_json.get('faultstring'), error_json.get('debuginfo'), method, url) elif resp.status_code in (301, 302, 305): # Redirected. Reissue the request to the new location. location = resp.headers.get('location') resp = self._http_request(location, method, **kwargs) elif resp.status_code == 300: raise exc.from_response(resp, method=method, url=url) return resp def json_request(self, method, url, **kwargs): kwargs.setdefault('headers', {}) kwargs['headers'].setdefault('Content-Type', 'application/json') kwargs['headers'].setdefault('Accept', 'application/json') if 'body' in kwargs: kwargs['data'] = json.dumps(kwargs.pop('body')) resp = self._http_request(url, method, **kwargs) body = resp.content content_type = resp.headers.get('content-type', None) status = resp.status_code if status == 204 or status == 205 or content_type is None: return resp, list() if 'application/json' in content_type: try: body = resp.json() except ValueError: LOG.error('Could not decode response body as JSON') else: body = None return resp, body def raw_request(self, method, url, **kwargs): kwargs.setdefault('headers', {}) kwargs['headers'].setdefault('Content-Type', 'application/octet-stream') return self._http_request(url, method, **kwargs) class ResponseBodyIterator(object): """A class that acts as an iterator over an HTTP response.""" def __init__(self, resp): self.resp = resp def __iter__(self): while True: yield self.next() def next(self): chunk = self.resp.read(CHUNKSIZE) if chunk: return chunk else: raise StopIteration() def _construct_http_client(*args, **kwargs): session = kwargs.pop('session', None) auth = kwargs.pop('auth', None) if session: service_type = kwargs.pop('service_type', 'baremetal') interface = kwargs.pop('endpoint_type', None) region_name = kwargs.pop('region_name', None) return SessionClient(session=session, auth=auth, interface=interface, service_type=service_type, region_name=region_name, service_name=None, user_agent='python-ironicclient') else: return HTTPClient(*args, **kwargs)
apache-2.0
mishravikas/geonode-cas
geonode/maps/populate_maplayers.py
1
3222
from geonode.maps.models import Map, MapLayer from django.conf import settings maplayers = [ { "fixed": False, "group": "background", "layer_params": "", "map": 1, "name": "geonode:CA", "ows_url": "http://localhost:8080/geoserver/wms", "source_params": "", "transparent": False, "stack_order": 0, "visibility": True, "opacity": 1, }, { "fixed": True, "group": "background", "layer_params": "{\"args\": [\"bluemarble\", \"http://maps.opengeo.org/geowebcache/service/wms\", {\"layers\": [\"bluemarble\"], \"tiled\": true, \"tilesOrigin\": [-20037508.34, -20037508.34], \"format\": \"image/png\"}, {\"buffer\": 0}], \"type\": \"OpenLayers.Layer.WMS\"}", "map": 1, "name": None, "opacity": 1, "source_params": "{\"ptype\": \"gxp_olsource\"}", "stack_order": 0, "transparent": False, "visibility": True }, { "fixed": True, "group": "background", "layer_params": "{\"args\": [\"geonode:CA\", \"http://localhost:8080/geoserver/wms\", {\"layers\": [\"geonode:CA\"], \"tiled\": true, \"tilesOrigin\": [-20037508.34, -20037508.34], \"format\": \"image/png\"}, {\"buffer\": 0}], \"type\": \"OpenLayers.Layer.WMS\"}", "map": 1, "name": None, "opacity": 1, "source_params": "{\"ptype\": \"gxp_olsource\"}", "stack_order": 1, "transparent": False, "visibility": False }, { "fixed": True, "group": "background", "layer_params": "{}", "map": 1, "name": "SATELLITE", "opacity": 1, "source_params": "{\"apiKey\": \"ABQIAAAAkofooZxTfcCv9Wi3zzGTVxTnme5EwnLVtEDGnh-lFVzRJhbdQhQgAhB1eT_2muZtc0dl-ZSWrtzmrw\", \"ptype\": \"gxp_googlesource\"}", "stack_order": 2, "transparent": False, "visibility": False }, { "fixed": True, "group": "background", "layer_params": "{\"args\": [\"No background\"], \"type\": \"OpenLayers.Layer\"}", "map": 1, "name": None, "opacity": 1, "source_params": "{\"ptype\": \"gxp_olsource\"}", "stack_order": 3, "transparent": False, "visibility": False } ] def create_maplayers(): if 'geonode.geoserver' in settings.INSTALLED_APPS: from django.db.models import signals from geonode.geoserver.signals import geoserver_pre_save_maplayer from geonode.geoserver.signals import geoserver_post_save_map signals.pre_save.disconnect(geoserver_pre_save_maplayer, sender=MapLayer) signals.post_save.disconnect(geoserver_post_save_map, sender=Map) for ml in maplayers: MapLayer.objects.create( fixed = ml['fixed'], group = ml['group'], name = ml['name'], layer_params = ml['layer_params'], map = Map.objects.get(pk=ml['map']), source_params = ml['source_params'], stack_order = ml['stack_order'], opacity = ml['opacity'], transparent = ml['stack_order'], visibility = ml['stack_order'], )
gpl-3.0
jmartiuk5/python-mode
pymode/libs3/rope/base/evaluate.py
32
12459
import rope.base.builtins import rope.base.pynames import rope.base.pyobjects from rope.base import ast, astutils, exceptions, pyobjects, arguments, worder BadIdentifierError = exceptions.BadIdentifierError def eval_location(pymodule, offset): """Find the pyname at the offset""" return eval_location2(pymodule, offset)[1] def eval_location2(pymodule, offset): """Find the primary and pyname at offset""" pyname_finder = ScopeNameFinder(pymodule) return pyname_finder.get_primary_and_pyname_at(offset) def eval_node(scope, node): """Evaluate a `ast.AST` node and return a PyName Return `None` if the expression cannot be evaluated. """ return eval_node2(scope, node)[1] def eval_node2(scope, node): evaluator = StatementEvaluator(scope) ast.walk(node, evaluator) return evaluator.old_result, evaluator.result def eval_str(holding_scope, name): return eval_str2(holding_scope, name)[1] def eval_str2(holding_scope, name): try: # parenthesizing for handling cases like 'a_var.\nattr' node = ast.parse('(%s)' % name) except SyntaxError: raise BadIdentifierError('Not a resolvable python identifier selected.') return eval_node2(holding_scope, node) class ScopeNameFinder(object): def __init__(self, pymodule): self.module_scope = pymodule.get_scope() self.lines = pymodule.lines self.worder = worder.Worder(pymodule.source_code, True) def _is_defined_in_class_body(self, holding_scope, offset, lineno): if lineno == holding_scope.get_start() and \ holding_scope.parent is not None and \ holding_scope.parent.get_kind() == 'Class' and \ self.worder.is_a_class_or_function_name_in_header(offset): return True if lineno != holding_scope.get_start() and \ holding_scope.get_kind() == 'Class' and \ self.worder.is_name_assigned_in_class_body(offset): return True return False def _is_function_name_in_function_header(self, scope, offset, lineno): if scope.get_start() <= lineno <= scope.get_body_start() and \ scope.get_kind() == 'Function' and \ self.worder.is_a_class_or_function_name_in_header(offset): return True return False def get_pyname_at(self, offset): return self.get_primary_and_pyname_at(offset)[1] def get_primary_and_pyname_at(self, offset): lineno = self.lines.get_line_number(offset) holding_scope = self.module_scope.get_inner_scope_for_line(lineno) # function keyword parameter if self.worder.is_function_keyword_parameter(offset): keyword_name = self.worder.get_word_at(offset) pyobject = self.get_enclosing_function(offset) if isinstance(pyobject, pyobjects.PyFunction): return (None, pyobject.get_parameters().get(keyword_name, None)) # class body if self._is_defined_in_class_body(holding_scope, offset, lineno): class_scope = holding_scope if lineno == holding_scope.get_start(): class_scope = holding_scope.parent name = self.worder.get_primary_at(offset).strip() try: return (None, class_scope.pyobject[name]) except rope.base.exceptions.AttributeNotFoundError: return (None, None) # function header if self._is_function_name_in_function_header(holding_scope, offset, lineno): name = self.worder.get_primary_at(offset).strip() return (None, holding_scope.parent[name]) # from statement module if self.worder.is_from_statement_module(offset): module = self.worder.get_primary_at(offset) module_pyname = self._find_module(module) return (None, module_pyname) if self.worder.is_from_aliased(offset): name = self.worder.get_from_aliased(offset) else: name = self.worder.get_primary_at(offset) return eval_str2(holding_scope, name) def get_enclosing_function(self, offset): function_parens = self.worder.find_parens_start_from_inside(offset) try: function_pyname = self.get_pyname_at(function_parens - 1) except BadIdentifierError: function_pyname = None if function_pyname is not None: pyobject = function_pyname.get_object() if isinstance(pyobject, pyobjects.AbstractFunction): return pyobject elif isinstance(pyobject, pyobjects.AbstractClass) and \ '__init__' in pyobject: return pyobject['__init__'].get_object() elif '__call__' in pyobject: return pyobject['__call__'].get_object() return None def _find_module(self, module_name): dots = 0 while module_name[dots] == '.': dots += 1 return rope.base.pynames.ImportedModule( self.module_scope.pyobject, module_name[dots:], dots) class StatementEvaluator(object): def __init__(self, scope): self.scope = scope self.result = None self.old_result = None def _Name(self, node): self.result = self.scope.lookup(node.id) def _Attribute(self, node): pyname = eval_node(self.scope, node.value) if pyname is None: pyname = rope.base.pynames.UnboundName() self.old_result = pyname if pyname.get_object() != rope.base.pyobjects.get_unknown(): try: self.result = pyname.get_object()[node.attr] except exceptions.AttributeNotFoundError: self.result = None def _Call(self, node): primary, pyobject = self._get_primary_and_object_for_node(node.func) if pyobject is None: return def _get_returned(pyobject): args = arguments.create_arguments(primary, pyobject, node, self.scope) return pyobject.get_returned_object(args) if isinstance(pyobject, rope.base.pyobjects.AbstractClass): result = None if '__new__' in pyobject: new_function = pyobject['__new__'].get_object() result = _get_returned(new_function) if result is None or \ result == rope.base.pyobjects.get_unknown(): result = rope.base.pyobjects.PyObject(pyobject) self.result = rope.base.pynames.UnboundName(pyobject=result) return pyfunction = None if isinstance(pyobject, rope.base.pyobjects.AbstractFunction): pyfunction = pyobject elif '__call__' in pyobject: pyfunction = pyobject['__call__'].get_object() if pyfunction is not None: self.result = rope.base.pynames.UnboundName( pyobject=_get_returned(pyfunction)) def _Str(self, node): self.result = rope.base.pynames.UnboundName( pyobject=rope.base.builtins.get_str()) def _Num(self, node): type_name = type(node.n).__name__ self.result = self._get_builtin_name(type_name) def _get_builtin_name(self, type_name): pytype = rope.base.builtins.builtins[type_name].get_object() return rope.base.pynames.UnboundName( rope.base.pyobjects.PyObject(pytype)) def _BinOp(self, node): self.result = rope.base.pynames.UnboundName( self._get_object_for_node(node.left)) def _BoolOp(self, node): pyobject = self._get_object_for_node(node.values[0]) if pyobject is None: pyobject = self._get_object_for_node(node.values[1]) self.result = rope.base.pynames.UnboundName(pyobject) def _Repr(self, node): self.result = self._get_builtin_name('str') def _UnaryOp(self, node): self.result = rope.base.pynames.UnboundName( self._get_object_for_node(node.operand)) def _Compare(self, node): self.result = self._get_builtin_name('bool') def _Dict(self, node): keys = None values = None if node.keys: keys = self._get_object_for_node(node.keys[0]) values = self._get_object_for_node(node.values[0]) self.result = rope.base.pynames.UnboundName( pyobject=rope.base.builtins.get_dict(keys, values)) def _List(self, node): holding = None if node.elts: holding = self._get_object_for_node(node.elts[0]) self.result = rope.base.pynames.UnboundName( pyobject=rope.base.builtins.get_list(holding)) def _ListComp(self, node): pyobject = self._what_does_comprehension_hold(node) self.result = rope.base.pynames.UnboundName( pyobject=rope.base.builtins.get_list(pyobject)) def _GeneratorExp(self, node): pyobject = self._what_does_comprehension_hold(node) self.result = rope.base.pynames.UnboundName( pyobject=rope.base.builtins.get_iterator(pyobject)) def _what_does_comprehension_hold(self, node): scope = self._make_comprehension_scope(node) pyname = eval_node(scope, node.elt) return pyname.get_object() if pyname is not None else None def _make_comprehension_scope(self, node): scope = self.scope module = scope.pyobject.get_module() names = {} for comp in node.generators: new_names = _get_evaluated_names(comp.target, comp.iter, module, '.__iter__().next()', node.lineno) names.update(new_names) return rope.base.pyscopes.TemporaryScope(scope.pycore, scope, names) def _Tuple(self, node): objects = [] if len(node.elts) < 4: for stmt in node.elts: pyobject = self._get_object_for_node(stmt) objects.append(pyobject) else: objects.append(self._get_object_for_node(node.elts[0])) self.result = rope.base.pynames.UnboundName( pyobject=rope.base.builtins.get_tuple(*objects)) def _get_object_for_node(self, stmt): pyname = eval_node(self.scope, stmt) pyobject = None if pyname is not None: pyobject = pyname.get_object() return pyobject def _get_primary_and_object_for_node(self, stmt): primary, pyname = eval_node2(self.scope, stmt) pyobject = None if pyname is not None: pyobject = pyname.get_object() return primary, pyobject def _Subscript(self, node): if isinstance(node.slice, ast.Index): self._call_function(node.value, '__getitem__', [node.slice.value]) elif isinstance(node.slice, ast.Slice): self._call_function(node.value, '__getitem__', [node.slice]) def _Slice(self, node): self.result = self._get_builtin_name('slice') def _call_function(self, node, function_name, other_args=None): pyname = eval_node(self.scope, node) if pyname is not None: pyobject = pyname.get_object() else: return if function_name in pyobject: called = pyobject[function_name].get_object() if not called or not isinstance(called, pyobjects.AbstractFunction): return args = [node] if other_args: args += other_args arguments_ = arguments.Arguments(args, self.scope) self.result = rope.base.pynames.UnboundName( pyobject=called.get_returned_object(arguments_)) def _Lambda(self, node): self.result = rope.base.pynames.UnboundName( pyobject=rope.base.builtins.Lambda(node, self.scope)) def _get_evaluated_names(targets, assigned, module, evaluation, lineno): result = {} for name, levels in astutils.get_name_levels(targets): assignment = rope.base.pynames.AssignmentValue(assigned, levels, evaluation) # XXX: this module should not access `rope.base.pynamesdef`! pyname = rope.base.pynamesdef.AssignedName(lineno, module) pyname.assignments.append(assignment) result[name] = pyname return result
lgpl-3.0
lavalamp-/ws-backend-community
wselasticsearch/models/dns/base.py
1
4055
# -*- coding: utf-8 -*- from __future__ import absolute_import from ..organizations.base import BaseOrganizationModel from ..types import * class BaseDomainNameModel(BaseOrganizationModel): """ This is a base Elasticsearch model for representing data that is tied to a given domain name. """ # Class Members domain_uuid = KeywordElasticsearchType( help_text="The UUID of the domain name that the data in this model is related to.", ) domain_name = KeywordElasticsearchType( help_text="The domain name that the data in this model is related to." ) domain_added_by = KeywordElasticsearchType( help_text="A string depicting how the referenced domain name was added to Web Sight.", ) # Instantiation def __init__(self, domain_uuid=None, domain_name=None, domain_added_by=None, **kwargs): super(BaseDomainNameModel, self).__init__(**kwargs) self.domain_uuid = domain_uuid self.domain_name = domain_name self.domain_added_by = domain_added_by # Static Methods # Class Methods @classmethod def get_has_mapped_parent(cls): return True @classmethod def get_mapped_model_class(cls): from lib.sqlalchemy import DomainName return DomainName @classmethod def get_mapped_model_parent(cls): return "organization" @classmethod def _populate_dummy(cls, to_populate): from lib import WsFaker to_populate.domain_uuid = WsFaker.create_uuid() to_populate.domain_name = WsFaker.get_domain_name() to_populate.domain_added_by = WsFaker.get_word() return to_populate @classmethod def _populate_from_database_model(cls, database_model=None, to_populate=None): to_populate.domain_uuid = database_model.uuid to_populate.domain_name = database_model.name to_populate.domain_added_by = database_model.added_by return to_populate # Public Methods # Protected Methods # Private Methods # Properties # Representation and Comparison def __repr__(self): return "<%s - %s (%s)>" % (self.__class__.__name__, self.domain_name, self.domain_uuid) class BaseDomainNameScanModel(BaseDomainNameModel): """ This is a base Elasticsearch model for representing data that is tied to a given domain name scan. """ # Class Members domain_scan_uuid = KeywordElasticsearchType( help_text="The UUID of the domain name scan that the data in this model is related to.", ) is_latest_scan = BooleanElasticsearchType( help_text="Whether or not the data in this model reflects the most recently collected data of " "this format for the entity in question.", ) # Instantiation def __init__(self, domain_scan_uuid=None, is_latest_scan=None, **kwargs): super(BaseDomainNameScanModel, self).__init__(**kwargs) self.domain_scan_uuid = domain_scan_uuid self.is_latest_scan = is_latest_scan # Static Methods # Class Methods @classmethod def get_has_mapped_parent(cls): return True @classmethod def get_mapped_model_class(cls): from lib.sqlalchemy import DomainNameScan return DomainNameScan @classmethod def get_mapped_model_parent(cls): return "domain_name" @classmethod def _populate_dummy(cls, to_populate): from lib import WsFaker, RandomHelper to_populate.domain_scan_uuid = WsFaker.create_uuid() to_populate.is_latest_scan = RandomHelper.flip_coin() return to_populate @classmethod def _populate_from_database_model(cls, database_model=None, to_populate=None): to_populate.domain_scan_uuid = database_model.uuid return to_populate # Public Methods # Protected Methods # Private Methods # Properties # Representation and Comparison def __repr__(self): return "<%s - %s>" % (self.__class__.__name__, self.domain_scan_uuid)
gpl-3.0
brandond/ansible
lib/ansible/modules/cloud/cloudstack/cs_ip_address.py
14
8325
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2015, Darren Worrall <darren@iweb.co.uk> # Copyright (c) 2015, René Moser <mail@renemoser.net> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cs_ip_address short_description: Manages public IP address associations on Apache CloudStack based clouds. description: - Acquires and associates a public IP to an account or project. - Due to API limitations this is not an idempotent call, so be sure to only conditionally call this when C(state=present). - Tagging the IP address can also make the call idempotent. version_added: '2.0' author: - "Darren Worrall (@dazworrall)" - "René Moser (@resmo)" options: ip_address: description: - Public IP address. - Required if I(state=absent) and I(tags) is not set. domain: description: - Domain the IP address is related to. network: description: - Network the IP address is related to. - Mutually exclusive with I(vpc). vpc: description: - VPC the IP address is related to. - Mutually exclusive with I(network). version_added: "2.2" account: description: - Account the IP address is related to. project: description: - Name of the project the IP address is related to. zone: description: - Name of the zone in which the IP address is in. - If not set, default zone is used. state: description: - State of the IP address. default: present choices: [ present, absent ] tags: description: - List of tags. Tags are a list of dictionaries having keys I(key) and I(value). - Tags can be used as an unique identifier for the IP Addresses. - In this case, at least one of them must be unique to ensure idempontency. aliases: [ 'tag' ] version_added: "2.6" poll_async: description: - Poll async jobs until job has finished. type: bool default: 'yes' extends_documentation_fragment: cloudstack ''' EXAMPLES = ''' - name: Associate an IP address conditonally local_action: module: cs_ip_address network: My Network register: ip_address when: instance.public_ip is undefined - name: Disassociate an IP address local_action: module: cs_ip_address ip_address: 1.2.3.4 state: absent - name: Associate an IP address with tags local_action: module: cs_ip_address network: My Network tags: - key: myCustomID - value: 5510c31a-416e-11e8-9013-02000a6b00bf register: ip_address - name: Disassociate an IP address with tags local_action: module: cs_ip_address state: absent tags: - key: myCustomID - value: 5510c31a-416e-11e8-9013-02000a6b00bf ''' RETURN = ''' --- id: description: UUID of the Public IP address. returned: success type: str sample: a6f7a5fc-43f8-11e5-a151-feff819cdc9f ip_address: description: Public IP address. returned: success type: str sample: 1.2.3.4 zone: description: Name of zone the IP address is related to. returned: success type: str sample: ch-gva-2 project: description: Name of project the IP address is related to. returned: success type: str sample: Production account: description: Account the IP address is related to. returned: success type: str sample: example account domain: description: Domain the IP address is related to. returned: success type: str sample: example domain tags: description: List of resource tags associated with the IP address. returned: success type: dict sample: '[ { "key": "myCustomID", "value": "5510c31a-416e-11e8-9013-02000a6b00bf" } ]' version_added: "2.6" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.cloudstack import ( AnsibleCloudStack, cs_argument_spec, cs_required_together, ) class AnsibleCloudStackIPAddress(AnsibleCloudStack): def __init__(self, module): super(AnsibleCloudStackIPAddress, self).__init__(module) self.returns = { 'ipaddress': 'ip_address', } def get_ip_address(self, key=None): if self.ip_address: return self._get_by_key(key, self.ip_address) args = { 'ipaddress': self.module.params.get('ip_address'), 'account': self.get_account(key='name'), 'domainid': self.get_domain(key='id'), 'projectid': self.get_project(key='id'), 'vpcid': self.get_vpc(key='id'), } ip_addresses = self.query_api('listPublicIpAddresses', **args) if ip_addresses: tags = self.module.params.get('tags') for ip_addr in ip_addresses['publicipaddress']: if ip_addr['ipaddress'] == args['ipaddress'] != '': self.ip_address = ip_addresses['publicipaddress'][0] elif tags: if sorted([tag for tag in tags if tag in ip_addr['tags']]) == sorted(tags): self.ip_address = ip_addr return self._get_by_key(key, self.ip_address) def present_ip_address(self): ip_address = self.get_ip_address() if not ip_address: ip_address = self.associate_ip_address(ip_address) if ip_address: ip_address = self.ensure_tags(resource=ip_address, resource_type='publicipaddress') return ip_address def associate_ip_address(self, ip_address): self.result['changed'] = True args = { 'account': self.get_account(key='name'), 'domainid': self.get_domain(key='id'), 'projectid': self.get_project(key='id'), # For the VPC case networkid is irrelevant, special case and we have to ignore it here. 'networkid': self.get_network(key='id') if not self.module.params.get('vpc') else None, 'zoneid': self.get_zone(key='id'), 'vpcid': self.get_vpc(key='id'), } ip_address = None if not self.module.check_mode: res = self.query_api('associateIpAddress', **args) poll_async = self.module.params.get('poll_async') if poll_async: ip_address = self.poll_job(res, 'ipaddress') return ip_address def disassociate_ip_address(self): ip_address = self.get_ip_address() if not ip_address: return None if ip_address['isstaticnat']: self.module.fail_json(msg="IP address is allocated via static nat") self.result['changed'] = True if not self.module.check_mode: self.module.params['tags'] = [] ip_address = self.ensure_tags(resource=ip_address, resource_type='publicipaddress') res = self.query_api('disassociateIpAddress', id=ip_address['id']) poll_async = self.module.params.get('poll_async') if poll_async: self.poll_job(res, 'ipaddress') return ip_address def main(): argument_spec = cs_argument_spec() argument_spec.update(dict( ip_address=dict(required=False), state=dict(choices=['present', 'absent'], default='present'), vpc=dict(), network=dict(), zone=dict(), domain=dict(), account=dict(), project=dict(), tags=dict(type='list', aliases=['tag']), poll_async=dict(type='bool', default=True), )) module = AnsibleModule( argument_spec=argument_spec, required_together=cs_required_together(), required_if=[ ('state', 'absent', ['ip_address', 'tags'], True), ], mutually_exclusive=( ['vpc', 'network'], ), supports_check_mode=True ) acs_ip_address = AnsibleCloudStackIPAddress(module) state = module.params.get('state') if state in ['absent']: ip_address = acs_ip_address.disassociate_ip_address() else: ip_address = acs_ip_address.present_ip_address() result = acs_ip_address.get_result(ip_address) module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
slackhq/python-slackclient
tests/slack_sdk/webhook/mock_web_api_server.py
1
9339
import asyncio import json import logging import re import sys import threading import time from http import HTTPStatus from http.server import HTTPServer, SimpleHTTPRequestHandler from multiprocessing.context import Process from typing import Type from unittest import TestCase from urllib.request import Request, urlopen from tests.helpers import get_mock_server_mode class MockHandler(SimpleHTTPRequestHandler): protocol_version = "HTTP/1.1" default_request_version = "HTTP/1.1" logger = logging.getLogger(__name__) pattern_for_language = re.compile("python/(\\S+)", re.IGNORECASE) pattern_for_package_identifier = re.compile("slackclient/(\\S+)") error_html_response_body = '<!DOCTYPE html>\n<html lang="en">\n<head>\n\t<meta charset="utf-8">\n\t<title>Server Error | Slack</title>\n\t<meta name="author" content="Slack">\n\t<style></style>\n</head>\n<body>\n\t<nav class="top persistent">\n\t\t<a href="https://status.slack.com/" class="logo" data-qa="logo"></a>\n\t</nav>\n\t<div id="page">\n\t\t<div id="page_contents">\n\t\t\t<h1>\n\t\t\t\t<svg width="30px" height="27px" viewBox="0 0 60 54" class="warning_icon"><path d="" fill="#D94827"/></svg>\n\t\t\t\tServer Error\n\t\t\t</h1>\n\t\t\t<div class="card">\n\t\t\t\t<p>It seems like there’s a problem connecting to our servers, and we’re investigating the issue.</p>\n\t\t\t\t<p>Please <a href="https://status.slack.com/">check our Status page for updates</a>.</p>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n\t<script type="text/javascript">\n\t\tif (window.desktop) {\n\t\t\tdocument.documentElement.className = \'desktop\';\n\t\t}\n\n\t\tvar FIVE_MINS = 5 * 60 * 1000;\n\t\tvar TEN_MINS = 10 * 60 * 1000;\n\n\t\tfunction randomBetween(min, max) {\n\t\t\treturn Math.floor(Math.random() * (max - (min + 1))) + min;\n\t\t}\n\n\t\twindow.setTimeout(function () {\n\t\t\twindow.location.reload(true);\n\t\t}, randomBetween(FIVE_MINS, TEN_MINS));\n\t</script>\n</body>\n</html>' def is_valid_user_agent(self): user_agent = self.headers["User-Agent"] return self.pattern_for_language.search( user_agent ) and self.pattern_for_package_identifier.search(user_agent) def set_common_headers(self): self.send_header("content-type", "text/plain;charset=utf-8") self.send_header("connection", "close") self.end_headers() def do_GET(self): if self.path == "/received_requests.json": self.send_response(200) self.set_common_headers() self.wfile.write(json.dumps(self.received_requests).encode("utf-8")) return def do_POST(self): try: if self.path == "/timeout": time.sleep(2) # user-agent-this_is-test if self.path.startswith("/user-agent-"): elements = self.path.split("-") prefix, suffix = elements[2], elements[-1] ua: str = self.headers["User-Agent"] if ua.startswith(prefix) and ua.endswith(suffix): self.send_response(HTTPStatus.OK) self.set_common_headers() self.wfile.write("ok".encode("utf-8")) self.wfile.close() return else: self.send_response(HTTPStatus.BAD_REQUEST) self.set_common_headers() self.wfile.write("invalid user agent".encode("utf-8")) self.wfile.close() return if self.path == "/error": self.send_response(HTTPStatus.INTERNAL_SERVER_ERROR) # no charset here is intentional for testing self.send_header("content-type", "text/html") self.send_header("connection", "close") self.end_headers() self.wfile.write(self.error_html_response_body.encode("utf-8")) self.wfile.close() return body = "ok" self.send_response(HTTPStatus.OK) self.set_common_headers() self.wfile.write(body.encode("utf-8")) self.wfile.close() except Exception as e: self.logger.error(str(e), exc_info=True) raise class MockServerProcessTarget: def __init__(self, handler: Type[SimpleHTTPRequestHandler] = MockHandler): self.handler = handler def run(self): self.handler.received_requests = {} self.server = HTTPServer(("localhost", 8888), self.handler) try: self.server.serve_forever(0.05) finally: self.server.server_close() def stop(self): self.handler.received_requests = {} self.server.shutdown() self.join() class MonitorThread(threading.Thread): def __init__( self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler ): threading.Thread.__init__(self, daemon=True) self.handler = handler self.test = test self.test.mock_received_requests = None self.is_running = True def run(self) -> None: while self.is_running: try: req = Request(f"{self.test.server_url}/received_requests.json") resp = urlopen(req, timeout=1) self.test.mock_received_requests = json.loads( resp.read().decode("utf-8") ) except Exception as e: # skip logging for the initial request if self.test.mock_received_requests is not None: logging.getLogger(__name__).exception(e) time.sleep(0.01) def stop(self): self.is_running = False self.join() class MockServerThread(threading.Thread): def __init__( self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler ): threading.Thread.__init__(self) self.handler = handler self.test = test def run(self): self.server = HTTPServer(("localhost", 8888), self.handler) self.test.server_url = "http://localhost:8888" self.test.host, self.test.port = self.server.socket.getsockname() self.test.server_started.set() # threading.Event() self.test = None try: self.server.serve_forever() finally: self.server.server_close() def stop(self): self.server.shutdown() self.join() def setup_mock_web_api_server(test: TestCase): if get_mock_server_mode() == "threading": test.server_started = threading.Event() test.thread = MockServerThread(test) test.thread.start() test.server_started.wait() else: # start a mock server as another process target = MockServerProcessTarget() test.server_url = "http://localhost:8888" test.host, test.port = "localhost", 8888 test.process = Process(target=target.run, daemon=True) test.process.start() time.sleep(0.1) # start a thread in the current process # this thread fetches mock_received_requests from the remote process test.monitor_thread = MonitorThread(test) test.monitor_thread.start() count = 0 # wait until the first successful data retrieval while test.mock_received_requests is None: time.sleep(0.01) count += 1 if count >= 100: raise Exception("The mock server is not yet running!") def cleanup_mock_web_api_server(test: TestCase): if get_mock_server_mode() == "threading": test.thread.stop() test.thread = None else: # stop the thread to fetch mock_received_requests from the remote process test.monitor_thread.stop() retry_count = 0 # terminate the process while test.process.is_alive(): test.process.terminate() time.sleep(0.01) retry_count += 1 if retry_count >= 100: raise Exception("Failed to stop the mock server!") # Python 3.6 does not have this method if sys.version_info.major == 3 and sys.version_info.minor > 6: # cleanup the process's resources test.process.close() test.process = None def assert_auth_test_count(test: TestCase, expected_count: int): time.sleep(0.1) retry_count = 0 error = None while retry_count < 3: try: test.mock_received_requests["/auth.test"] == expected_count break except Exception as e: error = e retry_count += 1 # waiting for mock_received_requests updates time.sleep(0.1) if error is not None: raise error async def assert_auth_test_count_async(test: TestCase, expected_count: int): await asyncio.sleep(0.1) retry_count = 0 error = None while retry_count < 3: try: test.mock_received_requests["/auth.test"] == expected_count break except Exception as e: error = e retry_count += 1 # waiting for mock_received_requests updates await asyncio.sleep(0.1) if error is not None: raise error
mit
smkr/pyclipse
plugins/org.python.pydev.jython/Lib/encodings/cp737.py
9
7185
""" Python Character Mapping Codec generated from 'CP737.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x0391, # GREEK CAPITAL LETTER ALPHA 0x0081: 0x0392, # GREEK CAPITAL LETTER BETA 0x0082: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x0083: 0x0394, # GREEK CAPITAL LETTER DELTA 0x0084: 0x0395, # GREEK CAPITAL LETTER EPSILON 0x0085: 0x0396, # GREEK CAPITAL LETTER ZETA 0x0086: 0x0397, # GREEK CAPITAL LETTER ETA 0x0087: 0x0398, # GREEK CAPITAL LETTER THETA 0x0088: 0x0399, # GREEK CAPITAL LETTER IOTA 0x0089: 0x039a, # GREEK CAPITAL LETTER KAPPA 0x008a: 0x039b, # GREEK CAPITAL LETTER LAMDA 0x008b: 0x039c, # GREEK CAPITAL LETTER MU 0x008c: 0x039d, # GREEK CAPITAL LETTER NU 0x008d: 0x039e, # GREEK CAPITAL LETTER XI 0x008e: 0x039f, # GREEK CAPITAL LETTER OMICRON 0x008f: 0x03a0, # GREEK CAPITAL LETTER PI 0x0090: 0x03a1, # GREEK CAPITAL LETTER RHO 0x0091: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x0092: 0x03a4, # GREEK CAPITAL LETTER TAU 0x0093: 0x03a5, # GREEK CAPITAL LETTER UPSILON 0x0094: 0x03a6, # GREEK CAPITAL LETTER PHI 0x0095: 0x03a7, # GREEK CAPITAL LETTER CHI 0x0096: 0x03a8, # GREEK CAPITAL LETTER PSI 0x0097: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x0098: 0x03b1, # GREEK SMALL LETTER ALPHA 0x0099: 0x03b2, # GREEK SMALL LETTER BETA 0x009a: 0x03b3, # GREEK SMALL LETTER GAMMA 0x009b: 0x03b4, # GREEK SMALL LETTER DELTA 0x009c: 0x03b5, # GREEK SMALL LETTER EPSILON 0x009d: 0x03b6, # GREEK SMALL LETTER ZETA 0x009e: 0x03b7, # GREEK SMALL LETTER ETA 0x009f: 0x03b8, # GREEK SMALL LETTER THETA 0x00a0: 0x03b9, # GREEK SMALL LETTER IOTA 0x00a1: 0x03ba, # GREEK SMALL LETTER KAPPA 0x00a2: 0x03bb, # GREEK SMALL LETTER LAMDA 0x00a3: 0x03bc, # GREEK SMALL LETTER MU 0x00a4: 0x03bd, # GREEK SMALL LETTER NU 0x00a5: 0x03be, # GREEK SMALL LETTER XI 0x00a6: 0x03bf, # GREEK SMALL LETTER OMICRON 0x00a7: 0x03c0, # GREEK SMALL LETTER PI 0x00a8: 0x03c1, # GREEK SMALL LETTER RHO 0x00a9: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00aa: 0x03c2, # GREEK SMALL LETTER FINAL SIGMA 0x00ab: 0x03c4, # GREEK SMALL LETTER TAU 0x00ac: 0x03c5, # GREEK SMALL LETTER UPSILON 0x00ad: 0x03c6, # GREEK SMALL LETTER PHI 0x00ae: 0x03c7, # GREEK SMALL LETTER CHI 0x00af: 0x03c8, # GREEK SMALL LETTER PSI 0x00b0: 0x2591, # LIGHT SHADE 0x00b1: 0x2592, # MEDIUM SHADE 0x00b2: 0x2593, # DARK SHADE 0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL 0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL 0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT 0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT 0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL 0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL 0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2588, # FULL BLOCK 0x00dc: 0x2584, # LOWER HALF BLOCK 0x00dd: 0x258c, # LEFT HALF BLOCK 0x00de: 0x2590, # RIGHT HALF BLOCK 0x00df: 0x2580, # UPPER HALF BLOCK 0x00e0: 0x03c9, # GREEK SMALL LETTER OMEGA 0x00e1: 0x03ac, # GREEK SMALL LETTER ALPHA WITH TONOS 0x00e2: 0x03ad, # GREEK SMALL LETTER EPSILON WITH TONOS 0x00e3: 0x03ae, # GREEK SMALL LETTER ETA WITH TONOS 0x00e4: 0x03ca, # GREEK SMALL LETTER IOTA WITH DIALYTIKA 0x00e5: 0x03af, # GREEK SMALL LETTER IOTA WITH TONOS 0x00e6: 0x03cc, # GREEK SMALL LETTER OMICRON WITH TONOS 0x00e7: 0x03cd, # GREEK SMALL LETTER UPSILON WITH TONOS 0x00e8: 0x03cb, # GREEK SMALL LETTER UPSILON WITH DIALYTIKA 0x00e9: 0x03ce, # GREEK SMALL LETTER OMEGA WITH TONOS 0x00ea: 0x0386, # GREEK CAPITAL LETTER ALPHA WITH TONOS 0x00eb: 0x0388, # GREEK CAPITAL LETTER EPSILON WITH TONOS 0x00ec: 0x0389, # GREEK CAPITAL LETTER ETA WITH TONOS 0x00ed: 0x038a, # GREEK CAPITAL LETTER IOTA WITH TONOS 0x00ee: 0x038c, # GREEK CAPITAL LETTER OMICRON WITH TONOS 0x00ef: 0x038e, # GREEK CAPITAL LETTER UPSILON WITH TONOS 0x00f0: 0x038f, # GREEK CAPITAL LETTER OMEGA WITH TONOS 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO 0x00f3: 0x2264, # LESS-THAN OR EQUAL TO 0x00f4: 0x03aa, # GREEK CAPITAL LETTER IOTA WITH DIALYTIKA 0x00f5: 0x03ab, # GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA 0x00f6: 0x00f7, # DIVISION SIGN 0x00f7: 0x2248, # ALMOST EQUAL TO 0x00f8: 0x00b0, # DEGREE SIGN 0x00f9: 0x2219, # BULLET OPERATOR 0x00fa: 0x00b7, # MIDDLE DOT 0x00fb: 0x221a, # SQUARE ROOT 0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N 0x00fd: 0x00b2, # SUPERSCRIPT TWO 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: 0x00a0, # NO-BREAK SPACE }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
epl-1.0
salguarnieri/intellij-community
python/lib/Lib/site-packages/django/core/management/__init__.py
145
17405
import os import sys from optparse import OptionParser, NO_DEFAULT import imp import django from django.core.management.base import BaseCommand, CommandError, handle_default_options from django.utils.importlib import import_module # For backwards compatibility: get_version() used to be in this module. get_version = django.get_version # A cache of loaded commands, so that call_command # doesn't have to reload every time it's called. _commands = None def find_commands(management_dir): """ Given a path to a management directory, returns a list of all the command names that are available. Returns an empty list if no commands are defined. """ command_dir = os.path.join(management_dir, 'commands') try: return [f[:-3] for f in os.listdir(command_dir) if not f.startswith('_') and f.endswith('.py')] except OSError: return [] def find_management_module(app_name): """ Determines the path to the management module for the given app_name, without actually importing the application or the management module. Raises ImportError if the management module cannot be found for any reason. """ parts = app_name.split('.') parts.append('management') parts.reverse() part = parts.pop() path = None # When using manage.py, the project module is added to the path, # loaded, then removed from the path. This means that # testproject.testapp.models can be loaded in future, even if # testproject isn't in the path. When looking for the management # module, we need look for the case where the project name is part # of the app_name but the project directory itself isn't on the path. try: f, path, descr = imp.find_module(part,path) except ImportError,e: if os.path.basename(os.getcwd()) != part: raise e while parts: part = parts.pop() f, path, descr = imp.find_module(part, path and [path] or None) return path def load_command_class(app_name, name): """ Given a command name and an application name, returns the Command class instance. All errors raised by the import process (ImportError, AttributeError) are allowed to propagate. """ module = import_module('%s.management.commands.%s' % (app_name, name)) return module.Command() def get_commands(): """ Returns a dictionary mapping command names to their callback applications. This works by looking for a management.commands package in django.core, and in each installed application -- if a commands package exists, all commands in that package are registered. Core commands are always included. If a settings module has been specified, user-defined commands will also be included, the startproject command will be disabled, and the startapp command will be modified to use the directory in which the settings module appears. The dictionary is in the format {command_name: app_name}. Key-value pairs from this dictionary can then be used in calls to load_command_class(app_name, command_name) If a specific version of a command must be loaded (e.g., with the startapp command), the instantiated module can be placed in the dictionary in place of the application name. The dictionary is cached on the first call and reused on subsequent calls. """ global _commands if _commands is None: _commands = dict([(name, 'django.core') for name in find_commands(__path__[0])]) # Find the installed apps try: from django.conf import settings apps = settings.INSTALLED_APPS except (AttributeError, EnvironmentError, ImportError): apps = [] # Find the project directory try: from django.conf import settings module = import_module(settings.SETTINGS_MODULE) project_directory = setup_environ(module, settings.SETTINGS_MODULE) except (AttributeError, EnvironmentError, ImportError, KeyError): project_directory = None # Find and load the management module for each installed app. for app_name in apps: try: path = find_management_module(app_name) _commands.update(dict([(name, app_name) for name in find_commands(path)])) except ImportError: pass # No management module - ignore this app if project_directory: # Remove the "startproject" command from self.commands, because # that's a django-admin.py command, not a manage.py command. del _commands['startproject'] # Override the startapp command so that it always uses the # project_directory, not the current working directory # (which is default). from django.core.management.commands.startapp import ProjectCommand _commands['startapp'] = ProjectCommand(project_directory) return _commands def call_command(name, *args, **options): """ Calls the given command, with the given options and args/kwargs. This is the primary API you should use for calling specific commands. Some examples: call_command('syncdb') call_command('shell', plain=True) call_command('sqlall', 'myapp') """ # Load the command object. try: app_name = get_commands()[name] if isinstance(app_name, BaseCommand): # If the command is already loaded, use it directly. klass = app_name else: klass = load_command_class(app_name, name) except KeyError: raise CommandError("Unknown command: %r" % name) # Grab out a list of defaults from the options. optparse does this for us # when the script runs from the command line, but since call_command can # be called programatically, we need to simulate the loading and handling # of defaults (see #10080 for details). defaults = dict([(o.dest, o.default) for o in klass.option_list if o.default is not NO_DEFAULT]) defaults.update(options) return klass.execute(*args, **defaults) class LaxOptionParser(OptionParser): """ An option parser that doesn't raise any errors on unknown options. This is needed because the --settings and --pythonpath options affect the commands (and thus the options) that are available to the user. """ def error(self, msg): pass def print_help(self): """Output nothing. The lax options are included in the normal option parser, so under normal usage, we don't need to print the lax options. """ pass def print_lax_help(self): """Output the basic options available to every command. This just redirects to the default print_help() behaviour. """ OptionParser.print_help(self) def _process_args(self, largs, rargs, values): """ Overrides OptionParser._process_args to exclusively handle default options and ignore args and other options. This overrides the behavior of the super class, which stop parsing at the first unrecognized option. """ while rargs: arg = rargs[0] try: if arg[0:2] == "--" and len(arg) > 2: # process a single long option (possibly with value(s)) # the superclass code pops the arg off rargs self._process_long_opt(rargs, values) elif arg[:1] == "-" and len(arg) > 1: # process a cluster of short options (possibly with # value(s) for the last one only) # the superclass code pops the arg off rargs self._process_short_opts(rargs, values) else: # it's either a non-default option or an arg # either way, add it to the args list so we can keep # dealing with options del rargs[0] raise Exception except: largs.append(arg) class ManagementUtility(object): """ Encapsulates the logic of the django-admin.py and manage.py utilities. A ManagementUtility has a number of commands, which can be manipulated by editing the self.commands dictionary. """ def __init__(self, argv=None): self.argv = argv or sys.argv[:] self.prog_name = os.path.basename(self.argv[0]) def main_help_text(self): """ Returns the script's main help text, as a string. """ usage = ['',"Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,''] usage.append('Available subcommands:') commands = get_commands().keys() commands.sort() for cmd in commands: usage.append(' %s' % cmd) return '\n'.join(usage) def fetch_command(self, subcommand): """ Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "django-admin.py" or "manage.py") if it can't be found. """ try: app_name = get_commands()[subcommand] except KeyError: sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" % \ (subcommand, self.prog_name)) sys.exit(1) if isinstance(app_name, BaseCommand): # If the command is already loaded, use it directly. klass = app_name else: klass = load_command_class(app_name, subcommand) return klass def autocomplete(self): """ Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used to get information about the cli input. Please refer to the BASH man-page for more information about this variables. Subcommand options are saved as pairs. A pair consists of the long option string (e.g. '--exclude') and a boolean value indicating if the option requires arguments. When printing to stdout, a equal sign is appended to options which require arguments. Note: If debugging this function, it is recommended to write the debug output in a separate file. Otherwise the debug output will be treated and formatted as potential completion suggestions. """ # Don't complete if user hasn't sourced bash_completion file. if not os.environ.has_key('DJANGO_AUTO_COMPLETE'): return cwords = os.environ['COMP_WORDS'].split()[1:] cword = int(os.environ['COMP_CWORD']) try: curr = cwords[cword-1] except IndexError: curr = '' subcommands = get_commands().keys() + ['help'] options = [('--help', None)] # subcommand if cword == 1: print ' '.join(sorted(filter(lambda x: x.startswith(curr), subcommands))) # subcommand options # special case: the 'help' subcommand has no options elif cwords[0] in subcommands and cwords[0] != 'help': subcommand_cls = self.fetch_command(cwords[0]) # special case: 'runfcgi' stores additional options as # 'key=value' pairs if cwords[0] == 'runfcgi': from django.core.servers.fastcgi import FASTCGI_OPTIONS options += [(k, 1) for k in FASTCGI_OPTIONS] # special case: add the names of installed apps to options elif cwords[0] in ('dumpdata', 'reset', 'sql', 'sqlall', 'sqlclear', 'sqlcustom', 'sqlindexes', 'sqlreset', 'sqlsequencereset', 'test'): try: from django.conf import settings # Get the last part of the dotted path as the app name. options += [(a.split('.')[-1], 0) for a in settings.INSTALLED_APPS] except ImportError: # Fail silently if DJANGO_SETTINGS_MODULE isn't set. The # user will find out once they execute the command. pass options += [(s_opt.get_opt_string(), s_opt.nargs) for s_opt in subcommand_cls.option_list] # filter out previously specified options from available options prev_opts = [x.split('=')[0] for x in cwords[1:cword-1]] options = filter(lambda (x, v): x not in prev_opts, options) # filter options by current input options = sorted([(k, v) for k, v in options if k.startswith(curr)]) for option in options: opt_label = option[0] # append '=' to options which require args if option[1]: opt_label += '=' print opt_label sys.exit(1) def execute(self): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. parser = LaxOptionParser(usage="%prog subcommand [options] [args]", version=get_version(), option_list=BaseCommand.option_list) self.autocomplete() try: options, args = parser.parse_args(self.argv) handle_default_options(options) except: pass # Ignore any option errors at this point. try: subcommand = self.argv[1] except IndexError: subcommand = 'help' # Display help if no arguments were given. if subcommand == 'help': if len(args) > 2: self.fetch_command(args[2]).print_help(self.prog_name, args[2]) else: parser.print_lax_help() sys.stderr.write(self.main_help_text() + '\n') sys.exit(1) # Special-cases: We want 'django-admin.py --version' and # 'django-admin.py --help' to work, for backwards compatibility. elif self.argv[1:] == ['--version']: # LaxOptionParser already takes care of printing the version. pass elif self.argv[1:] == ['--help']: parser.print_lax_help() sys.stderr.write(self.main_help_text() + '\n') else: self.fetch_command(subcommand).run_from_argv(self.argv) def setup_environ(settings_mod, original_settings_path=None): """ Configures the runtime environment. This can also be used by external scripts wanting to set up a similar environment to manage.py. Returns the project directory (assuming the passed settings module is directly in the project directory). The "original_settings_path" parameter is optional, but recommended, since trying to work out the original path from the module can be problematic. """ # Add this project to sys.path so that it's importable in the conventional # way. For example, if this file (manage.py) lives in a directory # "myproject", this code would add "/path/to/myproject" to sys.path. if '__init__.py' in settings_mod.__file__: p = os.path.dirname(settings_mod.__file__) else: p = settings_mod.__file__ project_directory, settings_filename = os.path.split(p) if project_directory == os.curdir or not project_directory: project_directory = os.getcwd() project_name = os.path.basename(project_directory) # Strip filename suffix to get the module name. settings_name = os.path.splitext(settings_filename)[0] # Strip $py for Jython compiled files (like settings$py.class) if settings_name.endswith("$py"): settings_name = settings_name[:-3] # Set DJANGO_SETTINGS_MODULE appropriately. if original_settings_path: os.environ['DJANGO_SETTINGS_MODULE'] = original_settings_path else: os.environ['DJANGO_SETTINGS_MODULE'] = '%s.%s' % (project_name, settings_name) # Import the project module. We add the parent directory to PYTHONPATH to # avoid some of the path errors new users can have. sys.path.append(os.path.join(project_directory, os.pardir)) project_module = import_module(project_name) sys.path.pop() return project_directory def execute_from_command_line(argv=None): """ A simple method that runs a ManagementUtility. """ utility = ManagementUtility(argv) utility.execute() def execute_manager(settings_mod, argv=None): """ Like execute_from_command_line(), but for use by manage.py, a project-specific django-admin.py utility. """ setup_environ(settings_mod) utility = ManagementUtility(argv) utility.execute()
apache-2.0
zhDai/CToFun
ML/KMeans/BKMeans.py
2
2388
# coding:utf-8 #二分KMeans方法 #依赖于KMeans里面的一些方法 import numpy as np from KMeans import * from pylab import * #进行多次(n次),寻找到近似最小SSE def choose_min_SSE(n,data_1): min_sse = np.inf i = 0 while i<n : data_2=choose_initil_point(2, data_1) [outcomes,poly_point]=k_means(data_1, data_2) sse = 0 sse1 = 0 sse2 = 0 for j in xrange(len(data_1)): if outcomes[j][0]==0: sse1 += pow(data_1[j][0]-data_2[0][0],2)+pow(data_1[j][1]-data_2[0][1],2) elif outcomes[j][0]==1: sse2 += pow(data_1[j][0]-data_2[1][0],2)+pow(data_1[j][1]-data_2[1][1],2) else: pass sse = sse1+sse2 if sse < min_sse: min_sse = sse min_sse1 = sse1 min_sse2 = sse2 data1 = [] data2 = [] for j in xrange(len(data_1)): if outcomes[j][0]==0: data1.append(data_1[j]) elif outcomes[j][0]==1: data2.append(data_1[j]) poly_point2 = poly_point i+=1 return min_sse1,min_sse2,data1,data2,poly_point2 #这个函数是为了寻找字典里面的最大的sse,以便继续划分 def choose_max_SSE(rad): maxvalue = 0 for key in rad.keys(): if maxvalue<key: maxvalue = key return maxvalue #二分Kmeans方法 def Bk_means(k,dataname): data_1=openfile(dataname) i = 2 n = 50 #尝试次数 rad = {} [min_sse1,min_sse2,data1,data2,poly_point2] = choose_min_SSE(n, data_1) rad[min_sse1] = data1,poly_point2[0] rad[min_sse2] = data2,poly_point2[1] while i<k: svalue = choose_max_SSE(rad) data_1 = rad[svalue][0] del rad[svalue] [min_sse1,min_sse2,data1,data2,poly_point2] = choose_min_SSE(n, data_1) rad[min_sse1] = data1,poly_point2[0] rad[min_sse2] = data2,poly_point2[1] i+=1 return rad if __name__ == "__main__": rad = Bk_means(4, 'Kmean_test.txt') data_1=openfile('Kmean_test.txt') aa = [] for ivalue in rad.itervalues(): aa.append(ivalue[1]) bb = [] for ikey in rad.iterkeys(): bb.append(ikey) print sum(bb) hua_tu(data_1, aa)
gpl-2.0
bitglue/pyflakes
setup.py
3
1644
#!/usr/bin/env python # Copyright 2005-2011 Divmod, Inc. # Copyright 2013 Florent Xicluna. See LICENSE file for details from __future__ import with_statement import os.path try: from setuptools import setup except ImportError: from distutils.core import setup extra = {'scripts': ["bin/pyflakes"]} else: extra = { 'test_suite': 'pyflakes.test', 'entry_points': { 'console_scripts': ['pyflakes = pyflakes.api:main'], }, } def get_version(fname=os.path.join('pyflakes', '__init__.py')): with open(fname) as f: for line in f: if line.startswith('__version__'): return eval(line.split('=')[-1]) def get_long_description(): descr = [] for fname in ('README.rst',): with open(fname) as f: descr.append(f.read()) return '\n\n'.join(descr) setup( name="pyflakes", license="MIT", version=get_version(), description="passive checker of Python programs", long_description=get_long_description(), author="A lot of people", author_email="code-quality@python.org", url="https://github.com/pyflakes/pyflakes", packages=["pyflakes", "pyflakes.scripts", "pyflakes.test"], classifiers=[ "Development Status :: 6 - Mature", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development", "Topic :: Utilities", ], **extra)
mit
debugger22/sympy
sympy/simplify/tests/test_sqrtdenest.py
98
6451
from sympy import sqrt, root, S, Symbol, sqrtdenest, Integral, cos from sympy.simplify.sqrtdenest import _subsets as subsets r2, r3, r5, r6, r7, r10, r15, r29 = [sqrt(x) for x in [2, 3, 5, 6, 7, 10, 15, 29]] def test_sqrtdenest(): d = {sqrt(5 + 2 * r6): r2 + r3, sqrt(5. + 2 * r6): sqrt(5. + 2 * r6), sqrt(5. + 4*sqrt(5 + 2 * r6)): sqrt(5.0 + 4*r2 + 4*r3), sqrt(r2): sqrt(r2), sqrt(5 + r7): sqrt(5 + r7), sqrt(3 + sqrt(5 + 2*r7)): 3*r2*(5 + 2*r7)**(S(1)/4)/(2*sqrt(6 + 3*r7)) + r2*sqrt(6 + 3*r7)/(2*(5 + 2*r7)**(S(1)/4)), sqrt(3 + 2*r3): 3**(S(3)/4)*(r6/2 + 3*r2/2)/3} for i in d: assert sqrtdenest(i) == d[i] def test_sqrtdenest2(): assert sqrtdenest(sqrt(16 - 2*r29 + 2*sqrt(55 - 10*r29))) == \ r5 + sqrt(11 - 2*r29) e = sqrt(-r5 + sqrt(-2*r29 + 2*sqrt(-10*r29 + 55) + 16)) assert sqrtdenest(e) == root(-2*r29 + 11, 4) r = sqrt(1 + r7) assert sqrtdenest(sqrt(1 + r)) == sqrt(1 + r) e = sqrt(((1 + sqrt(1 + 2*sqrt(3 + r2 + r5)))**2).expand()) assert sqrtdenest(e) == 1 + sqrt(1 + 2*sqrt(r2 + r5 + 3)) assert sqrtdenest(sqrt(5*r3 + 6*r2)) == \ sqrt(2)*root(3, 4) + root(3, 4)**3 assert sqrtdenest(sqrt(((1 + r5 + sqrt(1 + r3))**2).expand())) == \ 1 + r5 + sqrt(1 + r3) assert sqrtdenest(sqrt(((1 + r5 + r7 + sqrt(1 + r3))**2).expand())) == \ 1 + sqrt(1 + r3) + r5 + r7 e = sqrt(((1 + cos(2) + cos(3) + sqrt(1 + r3))**2).expand()) assert sqrtdenest(e) == cos(3) + cos(2) + 1 + sqrt(1 + r3) e = sqrt(-2*r10 + 2*r2*sqrt(-2*r10 + 11) + 14) assert sqrtdenest(e) == sqrt(-2*r10 - 2*r2 + 4*r5 + 14) # check that the result is not more complicated than the input z = sqrt(-2*r29 + cos(2) + 2*sqrt(-10*r29 + 55) + 16) assert sqrtdenest(z) == z assert sqrtdenest(sqrt(r6 + sqrt(15))) == sqrt(r6 + sqrt(15)) z = sqrt(15 - 2*sqrt(31) + 2*sqrt(55 - 10*r29)) assert sqrtdenest(z) == z def test_sqrtdenest_rec(): assert sqrtdenest(sqrt(-4*sqrt(14) - 2*r6 + 4*sqrt(21) + 33)) == \ -r2 + r3 + 2*r7 assert sqrtdenest(sqrt(-28*r7 - 14*r5 + 4*sqrt(35) + 82)) == \ -7 + r5 + 2*r7 assert sqrtdenest(sqrt(6*r2/11 + 2*sqrt(22)/11 + 6*sqrt(11)/11 + 2)) == \ sqrt(11)*(r2 + 3 + sqrt(11))/11 assert sqrtdenest(sqrt(468*r3 + 3024*r2 + 2912*r6 + 19735)) == \ 9*r3 + 26 + 56*r6 z = sqrt(-490*r3 - 98*sqrt(115) - 98*sqrt(345) - 2107) assert sqrtdenest(z) == sqrt(-1)*(7*r5 + 7*r15 + 7*sqrt(23)) z = sqrt(-4*sqrt(14) - 2*r6 + 4*sqrt(21) + 34) assert sqrtdenest(z) == z assert sqrtdenest(sqrt(-8*r2 - 2*r5 + 18)) == -r10 + 1 + r2 + r5 assert sqrtdenest(sqrt(8*r2 + 2*r5 - 18)) == \ sqrt(-1)*(-r10 + 1 + r2 + r5) assert sqrtdenest(sqrt(8*r2/3 + 14*r5/3 + S(154)/9)) == \ -r10/3 + r2 + r5 + 3 assert sqrtdenest(sqrt(sqrt(2*r6 + 5) + sqrt(2*r7 + 8))) == \ sqrt(1 + r2 + r3 + r7) assert sqrtdenest(sqrt(4*r15 + 8*r5 + 12*r3 + 24)) == 1 + r3 + r5 + r15 w = 1 + r2 + r3 + r5 + r7 assert sqrtdenest(sqrt((w**2).expand())) == w z = sqrt((w**2).expand() + 1) assert sqrtdenest(z) == z z = sqrt(2*r10 + 6*r2 + 4*r5 + 12 + 10*r15 + 30*r3) assert sqrtdenest(z) == z def test_issue_6241(): z = sqrt( -320 + 32*sqrt(5) + 64*r15) assert sqrtdenest(z) == z def test_sqrtdenest3(): z = sqrt(13 - 2*r10 + 2*r2*sqrt(-2*r10 + 11)) assert sqrtdenest(z) == -1 + r2 + r10 assert sqrtdenest(z, max_iter=1) == -1 + sqrt(2) + sqrt(10) n = sqrt(2*r6/7 + 2*r7/7 + 2*sqrt(42)/7 + 2) d = sqrt(16 - 2*r29 + 2*sqrt(55 - 10*r29)) assert sqrtdenest(n/d).equals( r7*(1 + r6 + r7)/(7*(sqrt(-2*r29 + 11) + r5))) z = sqrt(sqrt(r2 + 2) + 2) assert sqrtdenest(z) == z assert sqrtdenest(sqrt(-2*r10 + 4*r2*sqrt(-2*r10 + 11) + 20)) == \ sqrt(-2*r10 - 4*r2 + 8*r5 + 20) assert sqrtdenest(sqrt((112 + 70*r2) + (46 + 34*r2)*r5)) == \ r10 + 5 + 4*r2 + 3*r5 z = sqrt(5 + sqrt(2*r6 + 5)*sqrt(-2*r29 + 2*sqrt(-10*r29 + 55) + 16)) r = sqrt(-2*r29 + 11) assert sqrtdenest(z) == sqrt(r2*r + r3*r + r10 + r15 + 5) def test_sqrtdenest4(): # see Denest_en.pdf in https://github.com/sympy/sympy/issues/3192 z = sqrt(8 - r2*sqrt(5 - r5) - sqrt(3)*(1 + r5)) z1 = sqrtdenest(z) c = sqrt(-r5 + 5) z1 = ((-r15*c - r3*c + c + r5*c - r6 - r2 + r10 + sqrt(30))/4).expand() assert sqrtdenest(z) == z1 z = sqrt(2*r2*sqrt(r2 + 2) + 5*r2 + 4*sqrt(r2 + 2) + 8) assert sqrtdenest(z) == r2 + sqrt(r2 + 2) + 2 w = 2 + r2 + r3 + (1 + r3)*sqrt(2 + r2 + 5*r3) z = sqrt((w**2).expand()) assert sqrtdenest(z) == w.expand() def test_sqrt_symbolic_denest(): x = Symbol('x') z = sqrt(((1 + sqrt(sqrt(2 + x) + 3))**2).expand()) assert sqrtdenest(z) == sqrt((1 + sqrt(sqrt(2 + x) + 3))**2) z = sqrt(((1 + sqrt(sqrt(2 + cos(1)) + 3))**2).expand()) assert sqrtdenest(z) == 1 + sqrt(sqrt(2 + cos(1)) + 3) z = ((1 + cos(2))**4 + 1).expand() assert sqrtdenest(z) == z z = sqrt(((1 + sqrt(sqrt(2 + cos(3*x)) + 3))**2 + 1).expand()) assert sqrtdenest(z) == z c = cos(3) c2 = c**2 assert sqrtdenest(sqrt(2*sqrt(1 + r3)*c + c2 + 1 + r3*c2)) == \ -1 - sqrt(1 + r3)*c ra = sqrt(1 + r3) z = sqrt(20*ra*sqrt(3 + 3*r3) + 12*r3*ra*sqrt(3 + 3*r3) + 64*r3 + 112) assert sqrtdenest(z) == z def test_issue_5857(): from sympy.abc import x, y z = sqrt(1/(4*r3 + 7) + 1) ans = (r2 + r6)/(r3 + 2) assert sqrtdenest(z) == ans assert sqrtdenest(1 + z) == 1 + ans assert sqrtdenest(Integral(z + 1, (x, 1, 2))) == \ Integral(1 + ans, (x, 1, 2)) assert sqrtdenest(x + sqrt(y)) == x + sqrt(y) ans = (r2 + r6)/(r3 + 2) assert sqrtdenest(z) == ans assert sqrtdenest(1 + z) == 1 + ans assert sqrtdenest(Integral(z + 1, (x, 1, 2))) == \ Integral(1 + ans, (x, 1, 2)) assert sqrtdenest(x + sqrt(y)) == x + sqrt(y) def test_subsets(): assert subsets(1) == [[1]] assert subsets(4) == [ [1, 0, 0, 0], [0, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 0], [1, 0, 1, 0], [0, 1, 1, 0], [1, 1, 1, 0], [0, 0, 0, 1], [1, 0, 0, 1], [0, 1, 0, 1], [1, 1, 0, 1], [0, 0, 1, 1], [1, 0, 1, 1], [0, 1, 1, 1], [1, 1, 1, 1]] def test_issue_5653(): assert sqrtdenest( sqrt(2 + sqrt(2 + sqrt(2)))) == sqrt(2 + sqrt(2 + sqrt(2)))
bsd-3-clause
namccart/gnuradio
docs/doxygen/doxyxml/generated/compoundsuper.py
348
359948
#!/usr/bin/env python # # Generated Thu Jun 11 18:44:25 2009 by generateDS.py. # import sys import getopt from string import lower as str_lower from xml.dom import minidom from xml.dom import Node # # User methods # # Calls to the methods in these classes are generated by generateDS.py. # You can replace these methods by re-implementing the following class # in a module named generatedssuper.py. try: from generatedssuper import GeneratedsSuper except ImportError, exp: class GeneratedsSuper: def format_string(self, input_data, input_name=''): return input_data def format_integer(self, input_data, input_name=''): return '%d' % input_data def format_float(self, input_data, input_name=''): return '%f' % input_data def format_double(self, input_data, input_name=''): return '%e' % input_data def format_boolean(self, input_data, input_name=''): return '%s' % input_data # # If you have installed IPython you can uncomment and use the following. # IPython is available from http://ipython.scipy.org/. # ## from IPython.Shell import IPShellEmbed ## args = '' ## ipshell = IPShellEmbed(args, ## banner = 'Dropping into IPython', ## exit_msg = 'Leaving Interpreter, back to program.') # Then use the following line where and when you want to drop into the # IPython shell: # ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit') # # Globals # ExternalEncoding = 'ascii' # # Support/utility functions. # def showIndent(outfile, level): for idx in range(level): outfile.write(' ') def quote_xml(inStr): s1 = (isinstance(inStr, basestring) and inStr or '%s' % inStr) s1 = s1.replace('&', '&amp;') s1 = s1.replace('<', '&lt;') s1 = s1.replace('>', '&gt;') return s1 def quote_attrib(inStr): s1 = (isinstance(inStr, basestring) and inStr or '%s' % inStr) s1 = s1.replace('&', '&amp;') s1 = s1.replace('<', '&lt;') s1 = s1.replace('>', '&gt;') if '"' in s1: if "'" in s1: s1 = '"%s"' % s1.replace('"', "&quot;") else: s1 = "'%s'" % s1 else: s1 = '"%s"' % s1 return s1 def quote_python(inStr): s1 = inStr if s1.find("'") == -1: if s1.find('\n') == -1: return "'%s'" % s1 else: return "'''%s'''" % s1 else: if s1.find('"') != -1: s1 = s1.replace('"', '\\"') if s1.find('\n') == -1: return '"%s"' % s1 else: return '"""%s"""' % s1 class MixedContainer: # Constants for category: CategoryNone = 0 CategoryText = 1 CategorySimple = 2 CategoryComplex = 3 # Constants for content_type: TypeNone = 0 TypeText = 1 TypeString = 2 TypeInteger = 3 TypeFloat = 4 TypeDecimal = 5 TypeDouble = 6 TypeBoolean = 7 def __init__(self, category, content_type, name, value): self.category = category self.content_type = content_type self.name = name self.value = value def getCategory(self): return self.category def getContenttype(self, content_type): return self.content_type def getValue(self): return self.value def getName(self): return self.name def export(self, outfile, level, name, namespace): if self.category == MixedContainer.CategoryText: outfile.write(self.value) elif self.category == MixedContainer.CategorySimple: self.exportSimple(outfile, level, name) else: # category == MixedContainer.CategoryComplex self.value.export(outfile, level, namespace,name) def exportSimple(self, outfile, level, name): if self.content_type == MixedContainer.TypeString: outfile.write('<%s>%s</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeInteger or \ self.content_type == MixedContainer.TypeBoolean: outfile.write('<%s>%d</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeFloat or \ self.content_type == MixedContainer.TypeDecimal: outfile.write('<%s>%f</%s>' % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeDouble: outfile.write('<%s>%g</%s>' % (self.name, self.value, self.name)) def exportLiteral(self, outfile, level, name): if self.category == MixedContainer.CategoryText: showIndent(outfile, level) outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ (self.category, self.content_type, self.name, self.value)) elif self.category == MixedContainer.CategorySimple: showIndent(outfile, level) outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ (self.category, self.content_type, self.name, self.value)) else: # category == MixedContainer.CategoryComplex showIndent(outfile, level) outfile.write('MixedContainer(%d, %d, "%s",\n' % \ (self.category, self.content_type, self.name,)) self.value.exportLiteral(outfile, level + 1) showIndent(outfile, level) outfile.write(')\n') class _MemberSpec(object): def __init__(self, name='', data_type='', container=0): self.name = name self.data_type = data_type self.container = container def set_name(self, name): self.name = name def get_name(self): return self.name def set_data_type(self, data_type): self.data_type = data_type def get_data_type(self): return self.data_type def set_container(self, container): self.container = container def get_container(self): return self.container # # Data representation classes. # class DoxygenType(GeneratedsSuper): subclass = None superclass = None def __init__(self, version=None, compounddef=None): self.version = version self.compounddef = compounddef def factory(*args_, **kwargs_): if DoxygenType.subclass: return DoxygenType.subclass(*args_, **kwargs_) else: return DoxygenType(*args_, **kwargs_) factory = staticmethod(factory) def get_compounddef(self): return self.compounddef def set_compounddef(self, compounddef): self.compounddef = compounddef def get_version(self): return self.version def set_version(self, version): self.version = version def export(self, outfile, level, namespace_='', name_='DoxygenType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='DoxygenType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='DoxygenType'): outfile.write(' version=%s' % (quote_attrib(self.version), )) def exportChildren(self, outfile, level, namespace_='', name_='DoxygenType'): if self.compounddef: self.compounddef.export(outfile, level, namespace_, name_='compounddef') def hasContent_(self): if ( self.compounddef is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='DoxygenType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.version is not None: showIndent(outfile, level) outfile.write('version = "%s",\n' % (self.version,)) def exportLiteralChildren(self, outfile, level, name_): if self.compounddef: showIndent(outfile, level) outfile.write('compounddef=model_.compounddefType(\n') self.compounddef.exportLiteral(outfile, level, name_='compounddef') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('version'): self.version = attrs.get('version').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'compounddef': obj_ = compounddefType.factory() obj_.build(child_) self.set_compounddef(obj_) # end class DoxygenType class compounddefType(GeneratedsSuper): subclass = None superclass = None def __init__(self, kind=None, prot=None, id=None, compoundname=None, title=None, basecompoundref=None, derivedcompoundref=None, includes=None, includedby=None, incdepgraph=None, invincdepgraph=None, innerdir=None, innerfile=None, innerclass=None, innernamespace=None, innerpage=None, innergroup=None, templateparamlist=None, sectiondef=None, briefdescription=None, detaileddescription=None, inheritancegraph=None, collaborationgraph=None, programlisting=None, location=None, listofallmembers=None): self.kind = kind self.prot = prot self.id = id self.compoundname = compoundname self.title = title if basecompoundref is None: self.basecompoundref = [] else: self.basecompoundref = basecompoundref if derivedcompoundref is None: self.derivedcompoundref = [] else: self.derivedcompoundref = derivedcompoundref if includes is None: self.includes = [] else: self.includes = includes if includedby is None: self.includedby = [] else: self.includedby = includedby self.incdepgraph = incdepgraph self.invincdepgraph = invincdepgraph if innerdir is None: self.innerdir = [] else: self.innerdir = innerdir if innerfile is None: self.innerfile = [] else: self.innerfile = innerfile if innerclass is None: self.innerclass = [] else: self.innerclass = innerclass if innernamespace is None: self.innernamespace = [] else: self.innernamespace = innernamespace if innerpage is None: self.innerpage = [] else: self.innerpage = innerpage if innergroup is None: self.innergroup = [] else: self.innergroup = innergroup self.templateparamlist = templateparamlist if sectiondef is None: self.sectiondef = [] else: self.sectiondef = sectiondef self.briefdescription = briefdescription self.detaileddescription = detaileddescription self.inheritancegraph = inheritancegraph self.collaborationgraph = collaborationgraph self.programlisting = programlisting self.location = location self.listofallmembers = listofallmembers def factory(*args_, **kwargs_): if compounddefType.subclass: return compounddefType.subclass(*args_, **kwargs_) else: return compounddefType(*args_, **kwargs_) factory = staticmethod(factory) def get_compoundname(self): return self.compoundname def set_compoundname(self, compoundname): self.compoundname = compoundname def get_title(self): return self.title def set_title(self, title): self.title = title def get_basecompoundref(self): return self.basecompoundref def set_basecompoundref(self, basecompoundref): self.basecompoundref = basecompoundref def add_basecompoundref(self, value): self.basecompoundref.append(value) def insert_basecompoundref(self, index, value): self.basecompoundref[index] = value def get_derivedcompoundref(self): return self.derivedcompoundref def set_derivedcompoundref(self, derivedcompoundref): self.derivedcompoundref = derivedcompoundref def add_derivedcompoundref(self, value): self.derivedcompoundref.append(value) def insert_derivedcompoundref(self, index, value): self.derivedcompoundref[index] = value def get_includes(self): return self.includes def set_includes(self, includes): self.includes = includes def add_includes(self, value): self.includes.append(value) def insert_includes(self, index, value): self.includes[index] = value def get_includedby(self): return self.includedby def set_includedby(self, includedby): self.includedby = includedby def add_includedby(self, value): self.includedby.append(value) def insert_includedby(self, index, value): self.includedby[index] = value def get_incdepgraph(self): return self.incdepgraph def set_incdepgraph(self, incdepgraph): self.incdepgraph = incdepgraph def get_invincdepgraph(self): return self.invincdepgraph def set_invincdepgraph(self, invincdepgraph): self.invincdepgraph = invincdepgraph def get_innerdir(self): return self.innerdir def set_innerdir(self, innerdir): self.innerdir = innerdir def add_innerdir(self, value): self.innerdir.append(value) def insert_innerdir(self, index, value): self.innerdir[index] = value def get_innerfile(self): return self.innerfile def set_innerfile(self, innerfile): self.innerfile = innerfile def add_innerfile(self, value): self.innerfile.append(value) def insert_innerfile(self, index, value): self.innerfile[index] = value def get_innerclass(self): return self.innerclass def set_innerclass(self, innerclass): self.innerclass = innerclass def add_innerclass(self, value): self.innerclass.append(value) def insert_innerclass(self, index, value): self.innerclass[index] = value def get_innernamespace(self): return self.innernamespace def set_innernamespace(self, innernamespace): self.innernamespace = innernamespace def add_innernamespace(self, value): self.innernamespace.append(value) def insert_innernamespace(self, index, value): self.innernamespace[index] = value def get_innerpage(self): return self.innerpage def set_innerpage(self, innerpage): self.innerpage = innerpage def add_innerpage(self, value): self.innerpage.append(value) def insert_innerpage(self, index, value): self.innerpage[index] = value def get_innergroup(self): return self.innergroup def set_innergroup(self, innergroup): self.innergroup = innergroup def add_innergroup(self, value): self.innergroup.append(value) def insert_innergroup(self, index, value): self.innergroup[index] = value def get_templateparamlist(self): return self.templateparamlist def set_templateparamlist(self, templateparamlist): self.templateparamlist = templateparamlist def get_sectiondef(self): return self.sectiondef def set_sectiondef(self, sectiondef): self.sectiondef = sectiondef def add_sectiondef(self, value): self.sectiondef.append(value) def insert_sectiondef(self, index, value): self.sectiondef[index] = value def get_briefdescription(self): return self.briefdescription def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription def get_detaileddescription(self): return self.detaileddescription def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription def get_inheritancegraph(self): return self.inheritancegraph def set_inheritancegraph(self, inheritancegraph): self.inheritancegraph = inheritancegraph def get_collaborationgraph(self): return self.collaborationgraph def set_collaborationgraph(self, collaborationgraph): self.collaborationgraph = collaborationgraph def get_programlisting(self): return self.programlisting def set_programlisting(self, programlisting): self.programlisting = programlisting def get_location(self): return self.location def set_location(self, location): self.location = location def get_listofallmembers(self): return self.listofallmembers def set_listofallmembers(self, listofallmembers): self.listofallmembers = listofallmembers def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='compounddefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='compounddefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='compounddefType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='compounddefType'): if self.compoundname is not None: showIndent(outfile, level) outfile.write('<%scompoundname>%s</%scompoundname>\n' % (namespace_, self.format_string(quote_xml(self.compoundname).encode(ExternalEncoding), input_name='compoundname'), namespace_)) if self.title is not None: showIndent(outfile, level) outfile.write('<%stitle>%s</%stitle>\n' % (namespace_, self.format_string(quote_xml(self.title).encode(ExternalEncoding), input_name='title'), namespace_)) for basecompoundref_ in self.basecompoundref: basecompoundref_.export(outfile, level, namespace_, name_='basecompoundref') for derivedcompoundref_ in self.derivedcompoundref: derivedcompoundref_.export(outfile, level, namespace_, name_='derivedcompoundref') for includes_ in self.includes: includes_.export(outfile, level, namespace_, name_='includes') for includedby_ in self.includedby: includedby_.export(outfile, level, namespace_, name_='includedby') if self.incdepgraph: self.incdepgraph.export(outfile, level, namespace_, name_='incdepgraph') if self.invincdepgraph: self.invincdepgraph.export(outfile, level, namespace_, name_='invincdepgraph') for innerdir_ in self.innerdir: innerdir_.export(outfile, level, namespace_, name_='innerdir') for innerfile_ in self.innerfile: innerfile_.export(outfile, level, namespace_, name_='innerfile') for innerclass_ in self.innerclass: innerclass_.export(outfile, level, namespace_, name_='innerclass') for innernamespace_ in self.innernamespace: innernamespace_.export(outfile, level, namespace_, name_='innernamespace') for innerpage_ in self.innerpage: innerpage_.export(outfile, level, namespace_, name_='innerpage') for innergroup_ in self.innergroup: innergroup_.export(outfile, level, namespace_, name_='innergroup') if self.templateparamlist: self.templateparamlist.export(outfile, level, namespace_, name_='templateparamlist') for sectiondef_ in self.sectiondef: sectiondef_.export(outfile, level, namespace_, name_='sectiondef') if self.briefdescription: self.briefdescription.export(outfile, level, namespace_, name_='briefdescription') if self.detaileddescription: self.detaileddescription.export(outfile, level, namespace_, name_='detaileddescription') if self.inheritancegraph: self.inheritancegraph.export(outfile, level, namespace_, name_='inheritancegraph') if self.collaborationgraph: self.collaborationgraph.export(outfile, level, namespace_, name_='collaborationgraph') if self.programlisting: self.programlisting.export(outfile, level, namespace_, name_='programlisting') if self.location: self.location.export(outfile, level, namespace_, name_='location') if self.listofallmembers: self.listofallmembers.export(outfile, level, namespace_, name_='listofallmembers') def hasContent_(self): if ( self.compoundname is not None or self.title is not None or self.basecompoundref is not None or self.derivedcompoundref is not None or self.includes is not None or self.includedby is not None or self.incdepgraph is not None or self.invincdepgraph is not None or self.innerdir is not None or self.innerfile is not None or self.innerclass is not None or self.innernamespace is not None or self.innerpage is not None or self.innergroup is not None or self.templateparamlist is not None or self.sectiondef is not None or self.briefdescription is not None or self.detaileddescription is not None or self.inheritancegraph is not None or self.collaborationgraph is not None or self.programlisting is not None or self.location is not None or self.listofallmembers is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='compounddefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) if self.prot is not None: showIndent(outfile, level) outfile.write('prot = "%s",\n' % (self.prot,)) if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('compoundname=%s,\n' % quote_python(self.compoundname).encode(ExternalEncoding)) if self.title: showIndent(outfile, level) outfile.write('title=model_.xsd_string(\n') self.title.exportLiteral(outfile, level, name_='title') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('basecompoundref=[\n') level += 1 for basecompoundref in self.basecompoundref: showIndent(outfile, level) outfile.write('model_.basecompoundref(\n') basecompoundref.exportLiteral(outfile, level, name_='basecompoundref') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('derivedcompoundref=[\n') level += 1 for derivedcompoundref in self.derivedcompoundref: showIndent(outfile, level) outfile.write('model_.derivedcompoundref(\n') derivedcompoundref.exportLiteral(outfile, level, name_='derivedcompoundref') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('includes=[\n') level += 1 for includes in self.includes: showIndent(outfile, level) outfile.write('model_.includes(\n') includes.exportLiteral(outfile, level, name_='includes') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('includedby=[\n') level += 1 for includedby in self.includedby: showIndent(outfile, level) outfile.write('model_.includedby(\n') includedby.exportLiteral(outfile, level, name_='includedby') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.incdepgraph: showIndent(outfile, level) outfile.write('incdepgraph=model_.graphType(\n') self.incdepgraph.exportLiteral(outfile, level, name_='incdepgraph') showIndent(outfile, level) outfile.write('),\n') if self.invincdepgraph: showIndent(outfile, level) outfile.write('invincdepgraph=model_.graphType(\n') self.invincdepgraph.exportLiteral(outfile, level, name_='invincdepgraph') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('innerdir=[\n') level += 1 for innerdir in self.innerdir: showIndent(outfile, level) outfile.write('model_.innerdir(\n') innerdir.exportLiteral(outfile, level, name_='innerdir') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('innerfile=[\n') level += 1 for innerfile in self.innerfile: showIndent(outfile, level) outfile.write('model_.innerfile(\n') innerfile.exportLiteral(outfile, level, name_='innerfile') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('innerclass=[\n') level += 1 for innerclass in self.innerclass: showIndent(outfile, level) outfile.write('model_.innerclass(\n') innerclass.exportLiteral(outfile, level, name_='innerclass') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('innernamespace=[\n') level += 1 for innernamespace in self.innernamespace: showIndent(outfile, level) outfile.write('model_.innernamespace(\n') innernamespace.exportLiteral(outfile, level, name_='innernamespace') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('innerpage=[\n') level += 1 for innerpage in self.innerpage: showIndent(outfile, level) outfile.write('model_.innerpage(\n') innerpage.exportLiteral(outfile, level, name_='innerpage') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('innergroup=[\n') level += 1 for innergroup in self.innergroup: showIndent(outfile, level) outfile.write('model_.innergroup(\n') innergroup.exportLiteral(outfile, level, name_='innergroup') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.templateparamlist: showIndent(outfile, level) outfile.write('templateparamlist=model_.templateparamlistType(\n') self.templateparamlist.exportLiteral(outfile, level, name_='templateparamlist') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('sectiondef=[\n') level += 1 for sectiondef in self.sectiondef: showIndent(outfile, level) outfile.write('model_.sectiondef(\n') sectiondef.exportLiteral(outfile, level, name_='sectiondef') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.briefdescription: showIndent(outfile, level) outfile.write('briefdescription=model_.descriptionType(\n') self.briefdescription.exportLiteral(outfile, level, name_='briefdescription') showIndent(outfile, level) outfile.write('),\n') if self.detaileddescription: showIndent(outfile, level) outfile.write('detaileddescription=model_.descriptionType(\n') self.detaileddescription.exportLiteral(outfile, level, name_='detaileddescription') showIndent(outfile, level) outfile.write('),\n') if self.inheritancegraph: showIndent(outfile, level) outfile.write('inheritancegraph=model_.graphType(\n') self.inheritancegraph.exportLiteral(outfile, level, name_='inheritancegraph') showIndent(outfile, level) outfile.write('),\n') if self.collaborationgraph: showIndent(outfile, level) outfile.write('collaborationgraph=model_.graphType(\n') self.collaborationgraph.exportLiteral(outfile, level, name_='collaborationgraph') showIndent(outfile, level) outfile.write('),\n') if self.programlisting: showIndent(outfile, level) outfile.write('programlisting=model_.listingType(\n') self.programlisting.exportLiteral(outfile, level, name_='programlisting') showIndent(outfile, level) outfile.write('),\n') if self.location: showIndent(outfile, level) outfile.write('location=model_.locationType(\n') self.location.exportLiteral(outfile, level, name_='location') showIndent(outfile, level) outfile.write('),\n') if self.listofallmembers: showIndent(outfile, level) outfile.write('listofallmembers=model_.listofallmembersType(\n') self.listofallmembers.exportLiteral(outfile, level, name_='listofallmembers') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'compoundname': compoundname_ = '' for text__content_ in child_.childNodes: compoundname_ += text__content_.nodeValue self.compoundname = compoundname_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': obj_ = docTitleType.factory() obj_.build(child_) self.set_title(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'basecompoundref': obj_ = compoundRefType.factory() obj_.build(child_) self.basecompoundref.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'derivedcompoundref': obj_ = compoundRefType.factory() obj_.build(child_) self.derivedcompoundref.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'includes': obj_ = incType.factory() obj_.build(child_) self.includes.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'includedby': obj_ = incType.factory() obj_.build(child_) self.includedby.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'incdepgraph': obj_ = graphType.factory() obj_.build(child_) self.set_incdepgraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'invincdepgraph': obj_ = graphType.factory() obj_.build(child_) self.set_invincdepgraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'innerdir': obj_ = refType.factory() obj_.build(child_) self.innerdir.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'innerfile': obj_ = refType.factory() obj_.build(child_) self.innerfile.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'innerclass': obj_ = refType.factory() obj_.build(child_) self.innerclass.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'innernamespace': obj_ = refType.factory() obj_.build(child_) self.innernamespace.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'innerpage': obj_ = refType.factory() obj_.build(child_) self.innerpage.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'innergroup': obj_ = refType.factory() obj_.build(child_) self.innergroup.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'templateparamlist': obj_ = templateparamlistType.factory() obj_.build(child_) self.set_templateparamlist(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sectiondef': obj_ = sectiondefType.factory() obj_.build(child_) self.sectiondef.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'briefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_briefdescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'detaileddescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_detaileddescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'inheritancegraph': obj_ = graphType.factory() obj_.build(child_) self.set_inheritancegraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'collaborationgraph': obj_ = graphType.factory() obj_.build(child_) self.set_collaborationgraph(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'programlisting': obj_ = listingType.factory() obj_.build(child_) self.set_programlisting(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'location': obj_ = locationType.factory() obj_.build(child_) self.set_location(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'listofallmembers': obj_ = listofallmembersType.factory() obj_.build(child_) self.set_listofallmembers(obj_) # end class compounddefType class listofallmembersType(GeneratedsSuper): subclass = None superclass = None def __init__(self, member=None): if member is None: self.member = [] else: self.member = member def factory(*args_, **kwargs_): if listofallmembersType.subclass: return listofallmembersType.subclass(*args_, **kwargs_) else: return listofallmembersType(*args_, **kwargs_) factory = staticmethod(factory) def get_member(self): return self.member def set_member(self, member): self.member = member def add_member(self, value): self.member.append(value) def insert_member(self, index, value): self.member[index] = value def export(self, outfile, level, namespace_='', name_='listofallmembersType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='listofallmembersType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='listofallmembersType'): pass def exportChildren(self, outfile, level, namespace_='', name_='listofallmembersType'): for member_ in self.member: member_.export(outfile, level, namespace_, name_='member') def hasContent_(self): if ( self.member is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='listofallmembersType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('member=[\n') level += 1 for member in self.member: showIndent(outfile, level) outfile.write('model_.member(\n') member.exportLiteral(outfile, level, name_='member') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'member': obj_ = memberRefType.factory() obj_.build(child_) self.member.append(obj_) # end class listofallmembersType class memberRefType(GeneratedsSuper): subclass = None superclass = None def __init__(self, virt=None, prot=None, refid=None, ambiguityscope=None, scope=None, name=None): self.virt = virt self.prot = prot self.refid = refid self.ambiguityscope = ambiguityscope self.scope = scope self.name = name def factory(*args_, **kwargs_): if memberRefType.subclass: return memberRefType.subclass(*args_, **kwargs_) else: return memberRefType(*args_, **kwargs_) factory = staticmethod(factory) def get_scope(self): return self.scope def set_scope(self, scope): self.scope = scope def get_name(self): return self.name def set_name(self, name): self.name = name def get_virt(self): return self.virt def set_virt(self, virt): self.virt = virt def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def get_ambiguityscope(self): return self.ambiguityscope def set_ambiguityscope(self, ambiguityscope): self.ambiguityscope = ambiguityscope def export(self, outfile, level, namespace_='', name_='memberRefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='memberRefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='memberRefType'): if self.virt is not None: outfile.write(' virt=%s' % (quote_attrib(self.virt), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.ambiguityscope is not None: outfile.write(' ambiguityscope=%s' % (self.format_string(quote_attrib(self.ambiguityscope).encode(ExternalEncoding), input_name='ambiguityscope'), )) def exportChildren(self, outfile, level, namespace_='', name_='memberRefType'): if self.scope is not None: showIndent(outfile, level) outfile.write('<%sscope>%s</%sscope>\n' % (namespace_, self.format_string(quote_xml(self.scope).encode(ExternalEncoding), input_name='scope'), namespace_)) if self.name is not None: showIndent(outfile, level) outfile.write('<%sname>%s</%sname>\n' % (namespace_, self.format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) def hasContent_(self): if ( self.scope is not None or self.name is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='memberRefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.virt is not None: showIndent(outfile, level) outfile.write('virt = "%s",\n' % (self.virt,)) if self.prot is not None: showIndent(outfile, level) outfile.write('prot = "%s",\n' % (self.prot,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) if self.ambiguityscope is not None: showIndent(outfile, level) outfile.write('ambiguityscope = %s,\n' % (self.ambiguityscope,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('scope=%s,\n' % quote_python(self.scope).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('virt'): self.virt = attrs.get('virt').value if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('refid'): self.refid = attrs.get('refid').value if attrs.get('ambiguityscope'): self.ambiguityscope = attrs.get('ambiguityscope').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'scope': scope_ = '' for text__content_ in child_.childNodes: scope_ += text__content_.nodeValue self.scope = scope_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'name': name_ = '' for text__content_ in child_.childNodes: name_ += text__content_.nodeValue self.name = name_ # end class memberRefType class scope(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if scope.subclass: return scope.subclass(*args_, **kwargs_) else: return scope(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='scope', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='scope') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='scope'): pass def exportChildren(self, outfile, level, namespace_='', name_='scope'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='scope'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class scope class name(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if name.subclass: return name.subclass(*args_, **kwargs_) else: return name(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='name', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='name') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='name'): pass def exportChildren(self, outfile, level, namespace_='', name_='name'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='name'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class name class compoundRefType(GeneratedsSuper): subclass = None superclass = None def __init__(self, virt=None, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None): self.virt = virt self.prot = prot self.refid = refid if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if compoundRefType.subclass: return compoundRefType.subclass(*args_, **kwargs_) else: return compoundRefType(*args_, **kwargs_) factory = staticmethod(factory) def get_virt(self): return self.virt def set_virt(self, virt): self.virt = virt def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='compoundRefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='compoundRefType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='compoundRefType'): if self.virt is not None: outfile.write(' virt=%s' % (quote_attrib(self.virt), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) def exportChildren(self, outfile, level, namespace_='', name_='compoundRefType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='compoundRefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.virt is not None: showIndent(outfile, level) outfile.write('virt = "%s",\n' % (self.virt,)) if self.prot is not None: showIndent(outfile, level) outfile.write('prot = "%s",\n' % (self.prot,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('virt'): self.virt = attrs.get('virt').value if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('refid'): self.refid = attrs.get('refid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class compoundRefType class reimplementType(GeneratedsSuper): subclass = None superclass = None def __init__(self, refid=None, valueOf_='', mixedclass_=None, content_=None): self.refid = refid if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if reimplementType.subclass: return reimplementType.subclass(*args_, **kwargs_) else: return reimplementType(*args_, **kwargs_) factory = staticmethod(factory) def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='reimplementType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='reimplementType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='reimplementType'): if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) def exportChildren(self, outfile, level, namespace_='', name_='reimplementType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='reimplementType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class reimplementType class incType(GeneratedsSuper): subclass = None superclass = None def __init__(self, local=None, refid=None, valueOf_='', mixedclass_=None, content_=None): self.local = local self.refid = refid if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if incType.subclass: return incType.subclass(*args_, **kwargs_) else: return incType(*args_, **kwargs_) factory = staticmethod(factory) def get_local(self): return self.local def set_local(self, local): self.local = local def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='incType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='incType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='incType'): if self.local is not None: outfile.write(' local=%s' % (quote_attrib(self.local), )) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) def exportChildren(self, outfile, level, namespace_='', name_='incType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='incType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.local is not None: showIndent(outfile, level) outfile.write('local = "%s",\n' % (self.local,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('local'): self.local = attrs.get('local').value if attrs.get('refid'): self.refid = attrs.get('refid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class incType class refType(GeneratedsSuper): subclass = None superclass = None def __init__(self, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None): self.prot = prot self.refid = refid if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if refType.subclass: return refType.subclass(*args_, **kwargs_) else: return refType(*args_, **kwargs_) factory = staticmethod(factory) def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='refType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='refType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='refType'): if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) def exportChildren(self, outfile, level, namespace_='', name_='refType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='refType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.prot is not None: showIndent(outfile, level) outfile.write('prot = "%s",\n' % (self.prot,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('refid'): self.refid = attrs.get('refid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class refType class refTextType(GeneratedsSuper): subclass = None superclass = None def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None): self.refid = refid self.kindref = kindref self.external = external if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if refTextType.subclass: return refTextType.subclass(*args_, **kwargs_) else: return refTextType(*args_, **kwargs_) factory = staticmethod(factory) def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def get_kindref(self): return self.kindref def set_kindref(self, kindref): self.kindref = kindref def get_external(self): return self.external def set_external(self, external): self.external = external def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='refTextType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='refTextType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='refTextType'): if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.kindref is not None: outfile.write(' kindref=%s' % (quote_attrib(self.kindref), )) if self.external is not None: outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), )) def exportChildren(self, outfile, level, namespace_='', name_='refTextType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='refTextType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) if self.kindref is not None: showIndent(outfile, level) outfile.write('kindref = "%s",\n' % (self.kindref,)) if self.external is not None: showIndent(outfile, level) outfile.write('external = %s,\n' % (self.external,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value if attrs.get('kindref'): self.kindref = attrs.get('kindref').value if attrs.get('external'): self.external = attrs.get('external').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class refTextType class sectiondefType(GeneratedsSuper): subclass = None superclass = None def __init__(self, kind=None, header=None, description=None, memberdef=None): self.kind = kind self.header = header self.description = description if memberdef is None: self.memberdef = [] else: self.memberdef = memberdef def factory(*args_, **kwargs_): if sectiondefType.subclass: return sectiondefType.subclass(*args_, **kwargs_) else: return sectiondefType(*args_, **kwargs_) factory = staticmethod(factory) def get_header(self): return self.header def set_header(self, header): self.header = header def get_description(self): return self.description def set_description(self, description): self.description = description def get_memberdef(self): return self.memberdef def set_memberdef(self, memberdef): self.memberdef = memberdef def add_memberdef(self, value): self.memberdef.append(value) def insert_memberdef(self, index, value): self.memberdef[index] = value def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def export(self, outfile, level, namespace_='', name_='sectiondefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='sectiondefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='sectiondefType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) def exportChildren(self, outfile, level, namespace_='', name_='sectiondefType'): if self.header is not None: showIndent(outfile, level) outfile.write('<%sheader>%s</%sheader>\n' % (namespace_, self.format_string(quote_xml(self.header).encode(ExternalEncoding), input_name='header'), namespace_)) if self.description: self.description.export(outfile, level, namespace_, name_='description') for memberdef_ in self.memberdef: memberdef_.export(outfile, level, namespace_, name_='memberdef') def hasContent_(self): if ( self.header is not None or self.description is not None or self.memberdef is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='sectiondefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('header=%s,\n' % quote_python(self.header).encode(ExternalEncoding)) if self.description: showIndent(outfile, level) outfile.write('description=model_.descriptionType(\n') self.description.exportLiteral(outfile, level, name_='description') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('memberdef=[\n') level += 1 for memberdef in self.memberdef: showIndent(outfile, level) outfile.write('model_.memberdef(\n') memberdef.exportLiteral(outfile, level, name_='memberdef') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'header': header_ = '' for text__content_ in child_.childNodes: header_ += text__content_.nodeValue self.header = header_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'description': obj_ = descriptionType.factory() obj_.build(child_) self.set_description(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'memberdef': obj_ = memberdefType.factory() obj_.build(child_) self.memberdef.append(obj_) # end class sectiondefType class memberdefType(GeneratedsSuper): subclass = None superclass = None def __init__(self, initonly=None, kind=None, volatile=None, const=None, raisexx=None, virt=None, readable=None, prot=None, explicit=None, new=None, final=None, writable=None, add=None, static=None, remove=None, sealed=None, mutable=None, gettable=None, inline=None, settable=None, id=None, templateparamlist=None, type_=None, definition=None, argsstring=None, name=None, read=None, write=None, bitfield=None, reimplements=None, reimplementedby=None, param=None, enumvalue=None, initializer=None, exceptions=None, briefdescription=None, detaileddescription=None, inbodydescription=None, location=None, references=None, referencedby=None): self.initonly = initonly self.kind = kind self.volatile = volatile self.const = const self.raisexx = raisexx self.virt = virt self.readable = readable self.prot = prot self.explicit = explicit self.new = new self.final = final self.writable = writable self.add = add self.static = static self.remove = remove self.sealed = sealed self.mutable = mutable self.gettable = gettable self.inline = inline self.settable = settable self.id = id self.templateparamlist = templateparamlist self.type_ = type_ self.definition = definition self.argsstring = argsstring self.name = name self.read = read self.write = write self.bitfield = bitfield if reimplements is None: self.reimplements = [] else: self.reimplements = reimplements if reimplementedby is None: self.reimplementedby = [] else: self.reimplementedby = reimplementedby if param is None: self.param = [] else: self.param = param if enumvalue is None: self.enumvalue = [] else: self.enumvalue = enumvalue self.initializer = initializer self.exceptions = exceptions self.briefdescription = briefdescription self.detaileddescription = detaileddescription self.inbodydescription = inbodydescription self.location = location if references is None: self.references = [] else: self.references = references if referencedby is None: self.referencedby = [] else: self.referencedby = referencedby def factory(*args_, **kwargs_): if memberdefType.subclass: return memberdefType.subclass(*args_, **kwargs_) else: return memberdefType(*args_, **kwargs_) factory = staticmethod(factory) def get_templateparamlist(self): return self.templateparamlist def set_templateparamlist(self, templateparamlist): self.templateparamlist = templateparamlist def get_type(self): return self.type_ def set_type(self, type_): self.type_ = type_ def get_definition(self): return self.definition def set_definition(self, definition): self.definition = definition def get_argsstring(self): return self.argsstring def set_argsstring(self, argsstring): self.argsstring = argsstring def get_name(self): return self.name def set_name(self, name): self.name = name def get_read(self): return self.read def set_read(self, read): self.read = read def get_write(self): return self.write def set_write(self, write): self.write = write def get_bitfield(self): return self.bitfield def set_bitfield(self, bitfield): self.bitfield = bitfield def get_reimplements(self): return self.reimplements def set_reimplements(self, reimplements): self.reimplements = reimplements def add_reimplements(self, value): self.reimplements.append(value) def insert_reimplements(self, index, value): self.reimplements[index] = value def get_reimplementedby(self): return self.reimplementedby def set_reimplementedby(self, reimplementedby): self.reimplementedby = reimplementedby def add_reimplementedby(self, value): self.reimplementedby.append(value) def insert_reimplementedby(self, index, value): self.reimplementedby[index] = value def get_param(self): return self.param def set_param(self, param): self.param = param def add_param(self, value): self.param.append(value) def insert_param(self, index, value): self.param[index] = value def get_enumvalue(self): return self.enumvalue def set_enumvalue(self, enumvalue): self.enumvalue = enumvalue def add_enumvalue(self, value): self.enumvalue.append(value) def insert_enumvalue(self, index, value): self.enumvalue[index] = value def get_initializer(self): return self.initializer def set_initializer(self, initializer): self.initializer = initializer def get_exceptions(self): return self.exceptions def set_exceptions(self, exceptions): self.exceptions = exceptions def get_briefdescription(self): return self.briefdescription def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription def get_detaileddescription(self): return self.detaileddescription def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription def get_inbodydescription(self): return self.inbodydescription def set_inbodydescription(self, inbodydescription): self.inbodydescription = inbodydescription def get_location(self): return self.location def set_location(self, location): self.location = location def get_references(self): return self.references def set_references(self, references): self.references = references def add_references(self, value): self.references.append(value) def insert_references(self, index, value): self.references[index] = value def get_referencedby(self): return self.referencedby def set_referencedby(self, referencedby): self.referencedby = referencedby def add_referencedby(self, value): self.referencedby.append(value) def insert_referencedby(self, index, value): self.referencedby[index] = value def get_initonly(self): return self.initonly def set_initonly(self, initonly): self.initonly = initonly def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def get_volatile(self): return self.volatile def set_volatile(self, volatile): self.volatile = volatile def get_const(self): return self.const def set_const(self, const): self.const = const def get_raise(self): return self.raisexx def set_raise(self, raisexx): self.raisexx = raisexx def get_virt(self): return self.virt def set_virt(self, virt): self.virt = virt def get_readable(self): return self.readable def set_readable(self, readable): self.readable = readable def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_explicit(self): return self.explicit def set_explicit(self, explicit): self.explicit = explicit def get_new(self): return self.new def set_new(self, new): self.new = new def get_final(self): return self.final def set_final(self, final): self.final = final def get_writable(self): return self.writable def set_writable(self, writable): self.writable = writable def get_add(self): return self.add def set_add(self, add): self.add = add def get_static(self): return self.static def set_static(self, static): self.static = static def get_remove(self): return self.remove def set_remove(self, remove): self.remove = remove def get_sealed(self): return self.sealed def set_sealed(self, sealed): self.sealed = sealed def get_mutable(self): return self.mutable def set_mutable(self, mutable): self.mutable = mutable def get_gettable(self): return self.gettable def set_gettable(self, gettable): self.gettable = gettable def get_inline(self): return self.inline def set_inline(self, inline): self.inline = inline def get_settable(self): return self.settable def set_settable(self, settable): self.settable = settable def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='memberdefType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='memberdefType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='memberdefType'): if self.initonly is not None: outfile.write(' initonly=%s' % (quote_attrib(self.initonly), )) if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) if self.volatile is not None: outfile.write(' volatile=%s' % (quote_attrib(self.volatile), )) if self.const is not None: outfile.write(' const=%s' % (quote_attrib(self.const), )) if self.raisexx is not None: outfile.write(' raise=%s' % (quote_attrib(self.raisexx), )) if self.virt is not None: outfile.write(' virt=%s' % (quote_attrib(self.virt), )) if self.readable is not None: outfile.write(' readable=%s' % (quote_attrib(self.readable), )) if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.explicit is not None: outfile.write(' explicit=%s' % (quote_attrib(self.explicit), )) if self.new is not None: outfile.write(' new=%s' % (quote_attrib(self.new), )) if self.final is not None: outfile.write(' final=%s' % (quote_attrib(self.final), )) if self.writable is not None: outfile.write(' writable=%s' % (quote_attrib(self.writable), )) if self.add is not None: outfile.write(' add=%s' % (quote_attrib(self.add), )) if self.static is not None: outfile.write(' static=%s' % (quote_attrib(self.static), )) if self.remove is not None: outfile.write(' remove=%s' % (quote_attrib(self.remove), )) if self.sealed is not None: outfile.write(' sealed=%s' % (quote_attrib(self.sealed), )) if self.mutable is not None: outfile.write(' mutable=%s' % (quote_attrib(self.mutable), )) if self.gettable is not None: outfile.write(' gettable=%s' % (quote_attrib(self.gettable), )) if self.inline is not None: outfile.write(' inline=%s' % (quote_attrib(self.inline), )) if self.settable is not None: outfile.write(' settable=%s' % (quote_attrib(self.settable), )) if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='memberdefType'): if self.templateparamlist: self.templateparamlist.export(outfile, level, namespace_, name_='templateparamlist') if self.type_: self.type_.export(outfile, level, namespace_, name_='type') if self.definition is not None: showIndent(outfile, level) outfile.write('<%sdefinition>%s</%sdefinition>\n' % (namespace_, self.format_string(quote_xml(self.definition).encode(ExternalEncoding), input_name='definition'), namespace_)) if self.argsstring is not None: showIndent(outfile, level) outfile.write('<%sargsstring>%s</%sargsstring>\n' % (namespace_, self.format_string(quote_xml(self.argsstring).encode(ExternalEncoding), input_name='argsstring'), namespace_)) if self.name is not None: showIndent(outfile, level) outfile.write('<%sname>%s</%sname>\n' % (namespace_, self.format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_)) if self.read is not None: showIndent(outfile, level) outfile.write('<%sread>%s</%sread>\n' % (namespace_, self.format_string(quote_xml(self.read).encode(ExternalEncoding), input_name='read'), namespace_)) if self.write is not None: showIndent(outfile, level) outfile.write('<%swrite>%s</%swrite>\n' % (namespace_, self.format_string(quote_xml(self.write).encode(ExternalEncoding), input_name='write'), namespace_)) if self.bitfield is not None: showIndent(outfile, level) outfile.write('<%sbitfield>%s</%sbitfield>\n' % (namespace_, self.format_string(quote_xml(self.bitfield).encode(ExternalEncoding), input_name='bitfield'), namespace_)) for reimplements_ in self.reimplements: reimplements_.export(outfile, level, namespace_, name_='reimplements') for reimplementedby_ in self.reimplementedby: reimplementedby_.export(outfile, level, namespace_, name_='reimplementedby') for param_ in self.param: param_.export(outfile, level, namespace_, name_='param') for enumvalue_ in self.enumvalue: enumvalue_.export(outfile, level, namespace_, name_='enumvalue') if self.initializer: self.initializer.export(outfile, level, namespace_, name_='initializer') if self.exceptions: self.exceptions.export(outfile, level, namespace_, name_='exceptions') if self.briefdescription: self.briefdescription.export(outfile, level, namespace_, name_='briefdescription') if self.detaileddescription: self.detaileddescription.export(outfile, level, namespace_, name_='detaileddescription') if self.inbodydescription: self.inbodydescription.export(outfile, level, namespace_, name_='inbodydescription') if self.location: self.location.export(outfile, level, namespace_, name_='location', ) for references_ in self.references: references_.export(outfile, level, namespace_, name_='references') for referencedby_ in self.referencedby: referencedby_.export(outfile, level, namespace_, name_='referencedby') def hasContent_(self): if ( self.templateparamlist is not None or self.type_ is not None or self.definition is not None or self.argsstring is not None or self.name is not None or self.read is not None or self.write is not None or self.bitfield is not None or self.reimplements is not None or self.reimplementedby is not None or self.param is not None or self.enumvalue is not None or self.initializer is not None or self.exceptions is not None or self.briefdescription is not None or self.detaileddescription is not None or self.inbodydescription is not None or self.location is not None or self.references is not None or self.referencedby is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='memberdefType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.initonly is not None: showIndent(outfile, level) outfile.write('initonly = "%s",\n' % (self.initonly,)) if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) if self.volatile is not None: showIndent(outfile, level) outfile.write('volatile = "%s",\n' % (self.volatile,)) if self.const is not None: showIndent(outfile, level) outfile.write('const = "%s",\n' % (self.const,)) if self.raisexx is not None: showIndent(outfile, level) outfile.write('raisexx = "%s",\n' % (self.raisexx,)) if self.virt is not None: showIndent(outfile, level) outfile.write('virt = "%s",\n' % (self.virt,)) if self.readable is not None: showIndent(outfile, level) outfile.write('readable = "%s",\n' % (self.readable,)) if self.prot is not None: showIndent(outfile, level) outfile.write('prot = "%s",\n' % (self.prot,)) if self.explicit is not None: showIndent(outfile, level) outfile.write('explicit = "%s",\n' % (self.explicit,)) if self.new is not None: showIndent(outfile, level) outfile.write('new = "%s",\n' % (self.new,)) if self.final is not None: showIndent(outfile, level) outfile.write('final = "%s",\n' % (self.final,)) if self.writable is not None: showIndent(outfile, level) outfile.write('writable = "%s",\n' % (self.writable,)) if self.add is not None: showIndent(outfile, level) outfile.write('add = "%s",\n' % (self.add,)) if self.static is not None: showIndent(outfile, level) outfile.write('static = "%s",\n' % (self.static,)) if self.remove is not None: showIndent(outfile, level) outfile.write('remove = "%s",\n' % (self.remove,)) if self.sealed is not None: showIndent(outfile, level) outfile.write('sealed = "%s",\n' % (self.sealed,)) if self.mutable is not None: showIndent(outfile, level) outfile.write('mutable = "%s",\n' % (self.mutable,)) if self.gettable is not None: showIndent(outfile, level) outfile.write('gettable = "%s",\n' % (self.gettable,)) if self.inline is not None: showIndent(outfile, level) outfile.write('inline = "%s",\n' % (self.inline,)) if self.settable is not None: showIndent(outfile, level) outfile.write('settable = "%s",\n' % (self.settable,)) if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): if self.templateparamlist: showIndent(outfile, level) outfile.write('templateparamlist=model_.templateparamlistType(\n') self.templateparamlist.exportLiteral(outfile, level, name_='templateparamlist') showIndent(outfile, level) outfile.write('),\n') if self.type_: showIndent(outfile, level) outfile.write('type_=model_.linkedTextType(\n') self.type_.exportLiteral(outfile, level, name_='type') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('definition=%s,\n' % quote_python(self.definition).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('argsstring=%s,\n' % quote_python(self.argsstring).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('read=%s,\n' % quote_python(self.read).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('write=%s,\n' % quote_python(self.write).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('bitfield=%s,\n' % quote_python(self.bitfield).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('reimplements=[\n') level += 1 for reimplements in self.reimplements: showIndent(outfile, level) outfile.write('model_.reimplements(\n') reimplements.exportLiteral(outfile, level, name_='reimplements') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('reimplementedby=[\n') level += 1 for reimplementedby in self.reimplementedby: showIndent(outfile, level) outfile.write('model_.reimplementedby(\n') reimplementedby.exportLiteral(outfile, level, name_='reimplementedby') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('param=[\n') level += 1 for param in self.param: showIndent(outfile, level) outfile.write('model_.param(\n') param.exportLiteral(outfile, level, name_='param') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('enumvalue=[\n') level += 1 for enumvalue in self.enumvalue: showIndent(outfile, level) outfile.write('model_.enumvalue(\n') enumvalue.exportLiteral(outfile, level, name_='enumvalue') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.initializer: showIndent(outfile, level) outfile.write('initializer=model_.linkedTextType(\n') self.initializer.exportLiteral(outfile, level, name_='initializer') showIndent(outfile, level) outfile.write('),\n') if self.exceptions: showIndent(outfile, level) outfile.write('exceptions=model_.linkedTextType(\n') self.exceptions.exportLiteral(outfile, level, name_='exceptions') showIndent(outfile, level) outfile.write('),\n') if self.briefdescription: showIndent(outfile, level) outfile.write('briefdescription=model_.descriptionType(\n') self.briefdescription.exportLiteral(outfile, level, name_='briefdescription') showIndent(outfile, level) outfile.write('),\n') if self.detaileddescription: showIndent(outfile, level) outfile.write('detaileddescription=model_.descriptionType(\n') self.detaileddescription.exportLiteral(outfile, level, name_='detaileddescription') showIndent(outfile, level) outfile.write('),\n') if self.inbodydescription: showIndent(outfile, level) outfile.write('inbodydescription=model_.descriptionType(\n') self.inbodydescription.exportLiteral(outfile, level, name_='inbodydescription') showIndent(outfile, level) outfile.write('),\n') if self.location: showIndent(outfile, level) outfile.write('location=model_.locationType(\n') self.location.exportLiteral(outfile, level, name_='location') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('references=[\n') level += 1 for references in self.references: showIndent(outfile, level) outfile.write('model_.references(\n') references.exportLiteral(outfile, level, name_='references') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('referencedby=[\n') level += 1 for referencedby in self.referencedby: showIndent(outfile, level) outfile.write('model_.referencedby(\n') referencedby.exportLiteral(outfile, level, name_='referencedby') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('initonly'): self.initonly = attrs.get('initonly').value if attrs.get('kind'): self.kind = attrs.get('kind').value if attrs.get('volatile'): self.volatile = attrs.get('volatile').value if attrs.get('const'): self.const = attrs.get('const').value if attrs.get('raise'): self.raisexx = attrs.get('raise').value if attrs.get('virt'): self.virt = attrs.get('virt').value if attrs.get('readable'): self.readable = attrs.get('readable').value if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('explicit'): self.explicit = attrs.get('explicit').value if attrs.get('new'): self.new = attrs.get('new').value if attrs.get('final'): self.final = attrs.get('final').value if attrs.get('writable'): self.writable = attrs.get('writable').value if attrs.get('add'): self.add = attrs.get('add').value if attrs.get('static'): self.static = attrs.get('static').value if attrs.get('remove'): self.remove = attrs.get('remove').value if attrs.get('sealed'): self.sealed = attrs.get('sealed').value if attrs.get('mutable'): self.mutable = attrs.get('mutable').value if attrs.get('gettable'): self.gettable = attrs.get('gettable').value if attrs.get('inline'): self.inline = attrs.get('inline').value if attrs.get('settable'): self.settable = attrs.get('settable').value if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'templateparamlist': obj_ = templateparamlistType.factory() obj_.build(child_) self.set_templateparamlist(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'type': obj_ = linkedTextType.factory() obj_.build(child_) self.set_type(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'definition': definition_ = '' for text__content_ in child_.childNodes: definition_ += text__content_.nodeValue self.definition = definition_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'argsstring': argsstring_ = '' for text__content_ in child_.childNodes: argsstring_ += text__content_.nodeValue self.argsstring = argsstring_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'name': name_ = '' for text__content_ in child_.childNodes: name_ += text__content_.nodeValue self.name = name_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'read': read_ = '' for text__content_ in child_.childNodes: read_ += text__content_.nodeValue self.read = read_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'write': write_ = '' for text__content_ in child_.childNodes: write_ += text__content_.nodeValue self.write = write_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'bitfield': bitfield_ = '' for text__content_ in child_.childNodes: bitfield_ += text__content_.nodeValue self.bitfield = bitfield_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'reimplements': obj_ = reimplementType.factory() obj_.build(child_) self.reimplements.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'reimplementedby': obj_ = reimplementType.factory() obj_.build(child_) self.reimplementedby.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'param': obj_ = paramType.factory() obj_.build(child_) self.param.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'enumvalue': obj_ = enumvalueType.factory() obj_.build(child_) self.enumvalue.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'initializer': obj_ = linkedTextType.factory() obj_.build(child_) self.set_initializer(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'exceptions': obj_ = linkedTextType.factory() obj_.build(child_) self.set_exceptions(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'briefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_briefdescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'detaileddescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_detaileddescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'inbodydescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_inbodydescription(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'location': obj_ = locationType.factory() obj_.build(child_) self.set_location(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'references': obj_ = referenceType.factory() obj_.build(child_) self.references.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'referencedby': obj_ = referenceType.factory() obj_.build(child_) self.referencedby.append(obj_) # end class memberdefType class definition(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if definition.subclass: return definition.subclass(*args_, **kwargs_) else: return definition(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='definition', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='definition') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='definition'): pass def exportChildren(self, outfile, level, namespace_='', name_='definition'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='definition'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class definition class argsstring(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if argsstring.subclass: return argsstring.subclass(*args_, **kwargs_) else: return argsstring(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='argsstring', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='argsstring') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='argsstring'): pass def exportChildren(self, outfile, level, namespace_='', name_='argsstring'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='argsstring'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class argsstring class read(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if read.subclass: return read.subclass(*args_, **kwargs_) else: return read(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='read', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='read') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='read'): pass def exportChildren(self, outfile, level, namespace_='', name_='read'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='read'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class read class write(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if write.subclass: return write.subclass(*args_, **kwargs_) else: return write(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='write', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='write') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='write'): pass def exportChildren(self, outfile, level, namespace_='', name_='write'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='write'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class write class bitfield(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if bitfield.subclass: return bitfield.subclass(*args_, **kwargs_) else: return bitfield(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='bitfield', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='bitfield') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='bitfield'): pass def exportChildren(self, outfile, level, namespace_='', name_='bitfield'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='bitfield'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class bitfield class descriptionType(GeneratedsSuper): subclass = None superclass = None def __init__(self, title=None, para=None, sect1=None, internal=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if descriptionType.subclass: return descriptionType.subclass(*args_, **kwargs_) else: return descriptionType(*args_, **kwargs_) factory = staticmethod(factory) def get_title(self): return self.title def set_title(self, title): self.title = title def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect1(self): return self.sect1 def set_sect1(self, sect1): self.sect1 = sect1 def add_sect1(self, value): self.sect1.append(value) def insert_sect1(self, index, value): self.sect1[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def export(self, outfile, level, namespace_='', name_='descriptionType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='descriptionType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='descriptionType'): pass def exportChildren(self, outfile, level, namespace_='', name_='descriptionType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect1 is not None or self.internal is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='descriptionType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect1': childobj_ = docSect1Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect1', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'internal': childobj_ = docInternalType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class descriptionType class enumvalueType(GeneratedsSuper): subclass = None superclass = None def __init__(self, prot=None, id=None, name=None, initializer=None, briefdescription=None, detaileddescription=None, mixedclass_=None, content_=None): self.prot = prot self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if enumvalueType.subclass: return enumvalueType.subclass(*args_, **kwargs_) else: return enumvalueType(*args_, **kwargs_) factory = staticmethod(factory) def get_name(self): return self.name def set_name(self, name): self.name = name def get_initializer(self): return self.initializer def set_initializer(self, initializer): self.initializer = initializer def get_briefdescription(self): return self.briefdescription def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription def get_detaileddescription(self): return self.detaileddescription def set_detaileddescription(self, detaileddescription): self.detaileddescription = detaileddescription def get_prot(self): return self.prot def set_prot(self, prot): self.prot = prot def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='enumvalueType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='enumvalueType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='enumvalueType'): if self.prot is not None: outfile.write(' prot=%s' % (quote_attrib(self.prot), )) if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='enumvalueType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.name is not None or self.initializer is not None or self.briefdescription is not None or self.detaileddescription is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='enumvalueType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.prot is not None: showIndent(outfile, level) outfile.write('prot = "%s",\n' % (self.prot,)) if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('prot'): self.prot = attrs.get('prot').value if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'name': value_ = [] for text_ in child_.childNodes: value_.append(text_.nodeValue) valuestr_ = ''.join(value_) obj_ = self.mixedclass_(MixedContainer.CategorySimple, MixedContainer.TypeString, 'name', valuestr_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'initializer': childobj_ = linkedTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'initializer', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'briefdescription': childobj_ = descriptionType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'briefdescription', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'detaileddescription': childobj_ = descriptionType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'detaileddescription', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class enumvalueType class templateparamlistType(GeneratedsSuper): subclass = None superclass = None def __init__(self, param=None): if param is None: self.param = [] else: self.param = param def factory(*args_, **kwargs_): if templateparamlistType.subclass: return templateparamlistType.subclass(*args_, **kwargs_) else: return templateparamlistType(*args_, **kwargs_) factory = staticmethod(factory) def get_param(self): return self.param def set_param(self, param): self.param = param def add_param(self, value): self.param.append(value) def insert_param(self, index, value): self.param[index] = value def export(self, outfile, level, namespace_='', name_='templateparamlistType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='templateparamlistType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='templateparamlistType'): pass def exportChildren(self, outfile, level, namespace_='', name_='templateparamlistType'): for param_ in self.param: param_.export(outfile, level, namespace_, name_='param') def hasContent_(self): if ( self.param is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='templateparamlistType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('param=[\n') level += 1 for param in self.param: showIndent(outfile, level) outfile.write('model_.param(\n') param.exportLiteral(outfile, level, name_='param') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'param': obj_ = paramType.factory() obj_.build(child_) self.param.append(obj_) # end class templateparamlistType class paramType(GeneratedsSuper): subclass = None superclass = None def __init__(self, type_=None, declname=None, defname=None, array=None, defval=None, briefdescription=None): self.type_ = type_ self.declname = declname self.defname = defname self.array = array self.defval = defval self.briefdescription = briefdescription def factory(*args_, **kwargs_): if paramType.subclass: return paramType.subclass(*args_, **kwargs_) else: return paramType(*args_, **kwargs_) factory = staticmethod(factory) def get_type(self): return self.type_ def set_type(self, type_): self.type_ = type_ def get_declname(self): return self.declname def set_declname(self, declname): self.declname = declname def get_defname(self): return self.defname def set_defname(self, defname): self.defname = defname def get_array(self): return self.array def set_array(self, array): self.array = array def get_defval(self): return self.defval def set_defval(self, defval): self.defval = defval def get_briefdescription(self): return self.briefdescription def set_briefdescription(self, briefdescription): self.briefdescription = briefdescription def export(self, outfile, level, namespace_='', name_='paramType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='paramType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='paramType'): pass def exportChildren(self, outfile, level, namespace_='', name_='paramType'): if self.type_: self.type_.export(outfile, level, namespace_, name_='type') if self.declname is not None: showIndent(outfile, level) outfile.write('<%sdeclname>%s</%sdeclname>\n' % (namespace_, self.format_string(quote_xml(self.declname).encode(ExternalEncoding), input_name='declname'), namespace_)) if self.defname is not None: showIndent(outfile, level) outfile.write('<%sdefname>%s</%sdefname>\n' % (namespace_, self.format_string(quote_xml(self.defname).encode(ExternalEncoding), input_name='defname'), namespace_)) if self.array is not None: showIndent(outfile, level) outfile.write('<%sarray>%s</%sarray>\n' % (namespace_, self.format_string(quote_xml(self.array).encode(ExternalEncoding), input_name='array'), namespace_)) if self.defval: self.defval.export(outfile, level, namespace_, name_='defval') if self.briefdescription: self.briefdescription.export(outfile, level, namespace_, name_='briefdescription') def hasContent_(self): if ( self.type_ is not None or self.declname is not None or self.defname is not None or self.array is not None or self.defval is not None or self.briefdescription is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='paramType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): if self.type_: showIndent(outfile, level) outfile.write('type_=model_.linkedTextType(\n') self.type_.exportLiteral(outfile, level, name_='type') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('declname=%s,\n' % quote_python(self.declname).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('defname=%s,\n' % quote_python(self.defname).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('array=%s,\n' % quote_python(self.array).encode(ExternalEncoding)) if self.defval: showIndent(outfile, level) outfile.write('defval=model_.linkedTextType(\n') self.defval.exportLiteral(outfile, level, name_='defval') showIndent(outfile, level) outfile.write('),\n') if self.briefdescription: showIndent(outfile, level) outfile.write('briefdescription=model_.descriptionType(\n') self.briefdescription.exportLiteral(outfile, level, name_='briefdescription') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'type': obj_ = linkedTextType.factory() obj_.build(child_) self.set_type(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'declname': declname_ = '' for text__content_ in child_.childNodes: declname_ += text__content_.nodeValue self.declname = declname_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'defname': defname_ = '' for text__content_ in child_.childNodes: defname_ += text__content_.nodeValue self.defname = defname_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'array': array_ = '' for text__content_ in child_.childNodes: array_ += text__content_.nodeValue self.array = array_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'defval': obj_ = linkedTextType.factory() obj_.build(child_) self.set_defval(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'briefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_briefdescription(obj_) # end class paramType class declname(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if declname.subclass: return declname.subclass(*args_, **kwargs_) else: return declname(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='declname', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='declname') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='declname'): pass def exportChildren(self, outfile, level, namespace_='', name_='declname'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='declname'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class declname class defname(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if defname.subclass: return defname.subclass(*args_, **kwargs_) else: return defname(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='defname', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='defname') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='defname'): pass def exportChildren(self, outfile, level, namespace_='', name_='defname'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='defname'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class defname class array(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if array.subclass: return array.subclass(*args_, **kwargs_) else: return array(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='array', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='array') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='array'): pass def exportChildren(self, outfile, level, namespace_='', name_='array'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='array'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class array class linkedTextType(GeneratedsSuper): subclass = None superclass = None def __init__(self, ref=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if linkedTextType.subclass: return linkedTextType.subclass(*args_, **kwargs_) else: return linkedTextType(*args_, **kwargs_) factory = staticmethod(factory) def get_ref(self): return self.ref def set_ref(self, ref): self.ref = ref def add_ref(self, value): self.ref.append(value) def insert_ref(self, index, value): self.ref[index] = value def export(self, outfile, level, namespace_='', name_='linkedTextType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='linkedTextType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='linkedTextType'): pass def exportChildren(self, outfile, level, namespace_='', name_='linkedTextType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.ref is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='linkedTextType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'ref': childobj_ = docRefTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'ref', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class linkedTextType class graphType(GeneratedsSuper): subclass = None superclass = None def __init__(self, node=None): if node is None: self.node = [] else: self.node = node def factory(*args_, **kwargs_): if graphType.subclass: return graphType.subclass(*args_, **kwargs_) else: return graphType(*args_, **kwargs_) factory = staticmethod(factory) def get_node(self): return self.node def set_node(self, node): self.node = node def add_node(self, value): self.node.append(value) def insert_node(self, index, value): self.node[index] = value def export(self, outfile, level, namespace_='', name_='graphType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='graphType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='graphType'): pass def exportChildren(self, outfile, level, namespace_='', name_='graphType'): for node_ in self.node: node_.export(outfile, level, namespace_, name_='node') def hasContent_(self): if ( self.node is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='graphType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('node=[\n') level += 1 for node in self.node: showIndent(outfile, level) outfile.write('model_.node(\n') node.exportLiteral(outfile, level, name_='node') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'node': obj_ = nodeType.factory() obj_.build(child_) self.node.append(obj_) # end class graphType class nodeType(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, label=None, link=None, childnode=None): self.id = id self.label = label self.link = link if childnode is None: self.childnode = [] else: self.childnode = childnode def factory(*args_, **kwargs_): if nodeType.subclass: return nodeType.subclass(*args_, **kwargs_) else: return nodeType(*args_, **kwargs_) factory = staticmethod(factory) def get_label(self): return self.label def set_label(self, label): self.label = label def get_link(self): return self.link def set_link(self, link): self.link = link def get_childnode(self): return self.childnode def set_childnode(self, childnode): self.childnode = childnode def add_childnode(self, value): self.childnode.append(value) def insert_childnode(self, index, value): self.childnode[index] = value def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='nodeType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='nodeType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='nodeType'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='nodeType'): if self.label is not None: showIndent(outfile, level) outfile.write('<%slabel>%s</%slabel>\n' % (namespace_, self.format_string(quote_xml(self.label).encode(ExternalEncoding), input_name='label'), namespace_)) if self.link: self.link.export(outfile, level, namespace_, name_='link') for childnode_ in self.childnode: childnode_.export(outfile, level, namespace_, name_='childnode') def hasContent_(self): if ( self.label is not None or self.link is not None or self.childnode is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='nodeType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('label=%s,\n' % quote_python(self.label).encode(ExternalEncoding)) if self.link: showIndent(outfile, level) outfile.write('link=model_.linkType(\n') self.link.exportLiteral(outfile, level, name_='link') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('childnode=[\n') level += 1 for childnode in self.childnode: showIndent(outfile, level) outfile.write('model_.childnode(\n') childnode.exportLiteral(outfile, level, name_='childnode') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'label': label_ = '' for text__content_ in child_.childNodes: label_ += text__content_.nodeValue self.label = label_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'link': obj_ = linkType.factory() obj_.build(child_) self.set_link(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'childnode': obj_ = childnodeType.factory() obj_.build(child_) self.childnode.append(obj_) # end class nodeType class label(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if label.subclass: return label.subclass(*args_, **kwargs_) else: return label(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='label', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='label') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='label'): pass def exportChildren(self, outfile, level, namespace_='', name_='label'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='label'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class label class childnodeType(GeneratedsSuper): subclass = None superclass = None def __init__(self, relation=None, refid=None, edgelabel=None): self.relation = relation self.refid = refid if edgelabel is None: self.edgelabel = [] else: self.edgelabel = edgelabel def factory(*args_, **kwargs_): if childnodeType.subclass: return childnodeType.subclass(*args_, **kwargs_) else: return childnodeType(*args_, **kwargs_) factory = staticmethod(factory) def get_edgelabel(self): return self.edgelabel def set_edgelabel(self, edgelabel): self.edgelabel = edgelabel def add_edgelabel(self, value): self.edgelabel.append(value) def insert_edgelabel(self, index, value): self.edgelabel[index] = value def get_relation(self): return self.relation def set_relation(self, relation): self.relation = relation def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def export(self, outfile, level, namespace_='', name_='childnodeType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='childnodeType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='childnodeType'): if self.relation is not None: outfile.write(' relation=%s' % (quote_attrib(self.relation), )) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) def exportChildren(self, outfile, level, namespace_='', name_='childnodeType'): for edgelabel_ in self.edgelabel: showIndent(outfile, level) outfile.write('<%sedgelabel>%s</%sedgelabel>\n' % (namespace_, self.format_string(quote_xml(edgelabel_).encode(ExternalEncoding), input_name='edgelabel'), namespace_)) def hasContent_(self): if ( self.edgelabel is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='childnodeType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.relation is not None: showIndent(outfile, level) outfile.write('relation = "%s",\n' % (self.relation,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('edgelabel=[\n') level += 1 for edgelabel in self.edgelabel: showIndent(outfile, level) outfile.write('%s,\n' % quote_python(edgelabel).encode(ExternalEncoding)) level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('relation'): self.relation = attrs.get('relation').value if attrs.get('refid'): self.refid = attrs.get('refid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'edgelabel': edgelabel_ = '' for text__content_ in child_.childNodes: edgelabel_ += text__content_.nodeValue self.edgelabel.append(edgelabel_) # end class childnodeType class edgelabel(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if edgelabel.subclass: return edgelabel.subclass(*args_, **kwargs_) else: return edgelabel(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='edgelabel', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='edgelabel') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='edgelabel'): pass def exportChildren(self, outfile, level, namespace_='', name_='edgelabel'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='edgelabel'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class edgelabel class linkType(GeneratedsSuper): subclass = None superclass = None def __init__(self, refid=None, external=None, valueOf_=''): self.refid = refid self.external = external self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if linkType.subclass: return linkType.subclass(*args_, **kwargs_) else: return linkType(*args_, **kwargs_) factory = staticmethod(factory) def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def get_external(self): return self.external def set_external(self, external): self.external = external def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='linkType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='linkType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='linkType'): if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.external is not None: outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), )) def exportChildren(self, outfile, level, namespace_='', name_='linkType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='linkType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) if self.external is not None: showIndent(outfile, level) outfile.write('external = %s,\n' % (self.external,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value if attrs.get('external'): self.external = attrs.get('external').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class linkType class listingType(GeneratedsSuper): subclass = None superclass = None def __init__(self, codeline=None): if codeline is None: self.codeline = [] else: self.codeline = codeline def factory(*args_, **kwargs_): if listingType.subclass: return listingType.subclass(*args_, **kwargs_) else: return listingType(*args_, **kwargs_) factory = staticmethod(factory) def get_codeline(self): return self.codeline def set_codeline(self, codeline): self.codeline = codeline def add_codeline(self, value): self.codeline.append(value) def insert_codeline(self, index, value): self.codeline[index] = value def export(self, outfile, level, namespace_='', name_='listingType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='listingType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='listingType'): pass def exportChildren(self, outfile, level, namespace_='', name_='listingType'): for codeline_ in self.codeline: codeline_.export(outfile, level, namespace_, name_='codeline') def hasContent_(self): if ( self.codeline is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='listingType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('codeline=[\n') level += 1 for codeline in self.codeline: showIndent(outfile, level) outfile.write('model_.codeline(\n') codeline.exportLiteral(outfile, level, name_='codeline') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'codeline': obj_ = codelineType.factory() obj_.build(child_) self.codeline.append(obj_) # end class listingType class codelineType(GeneratedsSuper): subclass = None superclass = None def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlight=None): self.external = external self.lineno = lineno self.refkind = refkind self.refid = refid if highlight is None: self.highlight = [] else: self.highlight = highlight def factory(*args_, **kwargs_): if codelineType.subclass: return codelineType.subclass(*args_, **kwargs_) else: return codelineType(*args_, **kwargs_) factory = staticmethod(factory) def get_highlight(self): return self.highlight def set_highlight(self, highlight): self.highlight = highlight def add_highlight(self, value): self.highlight.append(value) def insert_highlight(self, index, value): self.highlight[index] = value def get_external(self): return self.external def set_external(self, external): self.external = external def get_lineno(self): return self.lineno def set_lineno(self, lineno): self.lineno = lineno def get_refkind(self): return self.refkind def set_refkind(self, refkind): self.refkind = refkind def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def export(self, outfile, level, namespace_='', name_='codelineType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='codelineType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='codelineType'): if self.external is not None: outfile.write(' external=%s' % (quote_attrib(self.external), )) if self.lineno is not None: outfile.write(' lineno="%s"' % self.format_integer(self.lineno, input_name='lineno')) if self.refkind is not None: outfile.write(' refkind=%s' % (quote_attrib(self.refkind), )) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) def exportChildren(self, outfile, level, namespace_='', name_='codelineType'): for highlight_ in self.highlight: highlight_.export(outfile, level, namespace_, name_='highlight') def hasContent_(self): if ( self.highlight is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='codelineType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.external is not None: showIndent(outfile, level) outfile.write('external = "%s",\n' % (self.external,)) if self.lineno is not None: showIndent(outfile, level) outfile.write('lineno = %s,\n' % (self.lineno,)) if self.refkind is not None: showIndent(outfile, level) outfile.write('refkind = "%s",\n' % (self.refkind,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('highlight=[\n') level += 1 for highlight in self.highlight: showIndent(outfile, level) outfile.write('model_.highlight(\n') highlight.exportLiteral(outfile, level, name_='highlight') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('external'): self.external = attrs.get('external').value if attrs.get('lineno'): try: self.lineno = int(attrs.get('lineno').value) except ValueError, exp: raise ValueError('Bad integer attribute (lineno): %s' % exp) if attrs.get('refkind'): self.refkind = attrs.get('refkind').value if attrs.get('refid'): self.refid = attrs.get('refid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'highlight': obj_ = highlightType.factory() obj_.build(child_) self.highlight.append(obj_) # end class codelineType class highlightType(GeneratedsSuper): subclass = None superclass = None def __init__(self, classxx=None, sp=None, ref=None, mixedclass_=None, content_=None): self.classxx = classxx if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if highlightType.subclass: return highlightType.subclass(*args_, **kwargs_) else: return highlightType(*args_, **kwargs_) factory = staticmethod(factory) def get_sp(self): return self.sp def set_sp(self, sp): self.sp = sp def add_sp(self, value): self.sp.append(value) def insert_sp(self, index, value): self.sp[index] = value def get_ref(self): return self.ref def set_ref(self, ref): self.ref = ref def add_ref(self, value): self.ref.append(value) def insert_ref(self, index, value): self.ref[index] = value def get_class(self): return self.classxx def set_class(self, classxx): self.classxx = classxx def export(self, outfile, level, namespace_='', name_='highlightType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='highlightType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='highlightType'): if self.classxx is not None: outfile.write(' class=%s' % (quote_attrib(self.classxx), )) def exportChildren(self, outfile, level, namespace_='', name_='highlightType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.sp is not None or self.ref is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='highlightType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.classxx is not None: showIndent(outfile, level) outfile.write('classxx = "%s",\n' % (self.classxx,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('class'): self.classxx = attrs.get('class').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sp': value_ = [] for text_ in child_.childNodes: value_.append(text_.nodeValue) valuestr_ = ''.join(value_) obj_ = self.mixedclass_(MixedContainer.CategorySimple, MixedContainer.TypeString, 'sp', valuestr_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'ref': childobj_ = docRefTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'ref', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class highlightType class sp(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if sp.subclass: return sp.subclass(*args_, **kwargs_) else: return sp(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='sp', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='sp') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='sp'): pass def exportChildren(self, outfile, level, namespace_='', name_='sp'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='sp'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class sp class referenceType(GeneratedsSuper): subclass = None superclass = None def __init__(self, endline=None, startline=None, refid=None, compoundref=None, valueOf_='', mixedclass_=None, content_=None): self.endline = endline self.startline = startline self.refid = refid self.compoundref = compoundref if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if referenceType.subclass: return referenceType.subclass(*args_, **kwargs_) else: return referenceType(*args_, **kwargs_) factory = staticmethod(factory) def get_endline(self): return self.endline def set_endline(self, endline): self.endline = endline def get_startline(self): return self.startline def set_startline(self, startline): self.startline = startline def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def get_compoundref(self): return self.compoundref def set_compoundref(self, compoundref): self.compoundref = compoundref def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='referenceType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='referenceType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='referenceType'): if self.endline is not None: outfile.write(' endline="%s"' % self.format_integer(self.endline, input_name='endline')) if self.startline is not None: outfile.write(' startline="%s"' % self.format_integer(self.startline, input_name='startline')) if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.compoundref is not None: outfile.write(' compoundref=%s' % (self.format_string(quote_attrib(self.compoundref).encode(ExternalEncoding), input_name='compoundref'), )) def exportChildren(self, outfile, level, namespace_='', name_='referenceType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='referenceType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.endline is not None: showIndent(outfile, level) outfile.write('endline = %s,\n' % (self.endline,)) if self.startline is not None: showIndent(outfile, level) outfile.write('startline = %s,\n' % (self.startline,)) if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) if self.compoundref is not None: showIndent(outfile, level) outfile.write('compoundref = %s,\n' % (self.compoundref,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('endline'): try: self.endline = int(attrs.get('endline').value) except ValueError, exp: raise ValueError('Bad integer attribute (endline): %s' % exp) if attrs.get('startline'): try: self.startline = int(attrs.get('startline').value) except ValueError, exp: raise ValueError('Bad integer attribute (startline): %s' % exp) if attrs.get('refid'): self.refid = attrs.get('refid').value if attrs.get('compoundref'): self.compoundref = attrs.get('compoundref').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class referenceType class locationType(GeneratedsSuper): subclass = None superclass = None def __init__(self, bodystart=None, line=None, bodyend=None, bodyfile=None, file=None, valueOf_=''): self.bodystart = bodystart self.line = line self.bodyend = bodyend self.bodyfile = bodyfile self.file = file self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if locationType.subclass: return locationType.subclass(*args_, **kwargs_) else: return locationType(*args_, **kwargs_) factory = staticmethod(factory) def get_bodystart(self): return self.bodystart def set_bodystart(self, bodystart): self.bodystart = bodystart def get_line(self): return self.line def set_line(self, line): self.line = line def get_bodyend(self): return self.bodyend def set_bodyend(self, bodyend): self.bodyend = bodyend def get_bodyfile(self): return self.bodyfile def set_bodyfile(self, bodyfile): self.bodyfile = bodyfile def get_file(self): return self.file def set_file(self, file): self.file = file def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='locationType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='locationType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='locationType'): if self.bodystart is not None: outfile.write(' bodystart="%s"' % self.format_integer(self.bodystart, input_name='bodystart')) if self.line is not None: outfile.write(' line="%s"' % self.format_integer(self.line, input_name='line')) if self.bodyend is not None: outfile.write(' bodyend="%s"' % self.format_integer(self.bodyend, input_name='bodyend')) if self.bodyfile is not None: outfile.write(' bodyfile=%s' % (self.format_string(quote_attrib(self.bodyfile).encode(ExternalEncoding), input_name='bodyfile'), )) if self.file is not None: outfile.write(' file=%s' % (self.format_string(quote_attrib(self.file).encode(ExternalEncoding), input_name='file'), )) def exportChildren(self, outfile, level, namespace_='', name_='locationType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='locationType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.bodystart is not None: showIndent(outfile, level) outfile.write('bodystart = %s,\n' % (self.bodystart,)) if self.line is not None: showIndent(outfile, level) outfile.write('line = %s,\n' % (self.line,)) if self.bodyend is not None: showIndent(outfile, level) outfile.write('bodyend = %s,\n' % (self.bodyend,)) if self.bodyfile is not None: showIndent(outfile, level) outfile.write('bodyfile = %s,\n' % (self.bodyfile,)) if self.file is not None: showIndent(outfile, level) outfile.write('file = %s,\n' % (self.file,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('bodystart'): try: self.bodystart = int(attrs.get('bodystart').value) except ValueError, exp: raise ValueError('Bad integer attribute (bodystart): %s' % exp) if attrs.get('line'): try: self.line = int(attrs.get('line').value) except ValueError, exp: raise ValueError('Bad integer attribute (line): %s' % exp) if attrs.get('bodyend'): try: self.bodyend = int(attrs.get('bodyend').value) except ValueError, exp: raise ValueError('Bad integer attribute (bodyend): %s' % exp) if attrs.get('bodyfile'): self.bodyfile = attrs.get('bodyfile').value if attrs.get('file'): self.file = attrs.get('file').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class locationType class docSect1Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, title=None, para=None, sect2=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docSect1Type.subclass: return docSect1Type.subclass(*args_, **kwargs_) else: return docSect1Type(*args_, **kwargs_) factory = staticmethod(factory) def get_title(self): return self.title def set_title(self, title): self.title = title def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect2(self): return self.sect2 def set_sect2(self, sect2): self.sect2 = sect2 def add_sect2(self, value): self.sect2.append(value) def insert_sect2(self, index, value): self.sect2[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='docSect1Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docSect1Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docSect1Type'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docSect1Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect2 is not None or self.internal is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docSect1Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect2': childobj_ = docSect2Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect2', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'internal': childobj_ = docInternalS1Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect1Type class docSect2Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, title=None, para=None, sect3=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docSect2Type.subclass: return docSect2Type.subclass(*args_, **kwargs_) else: return docSect2Type(*args_, **kwargs_) factory = staticmethod(factory) def get_title(self): return self.title def set_title(self, title): self.title = title def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect3(self): return self.sect3 def set_sect3(self, sect3): self.sect3 = sect3 def add_sect3(self, value): self.sect3.append(value) def insert_sect3(self, index, value): self.sect3[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='docSect2Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docSect2Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docSect2Type'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docSect2Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect3 is not None or self.internal is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docSect2Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect3': childobj_ = docSect3Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect3', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'internal': childobj_ = docInternalS2Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect2Type class docSect3Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, title=None, para=None, sect4=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docSect3Type.subclass: return docSect3Type.subclass(*args_, **kwargs_) else: return docSect3Type(*args_, **kwargs_) factory = staticmethod(factory) def get_title(self): return self.title def set_title(self, title): self.title = title def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect4(self): return self.sect4 def set_sect4(self, sect4): self.sect4 = sect4 def add_sect4(self, value): self.sect4.append(value) def insert_sect4(self, index, value): self.sect4[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='docSect3Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docSect3Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docSect3Type'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docSect3Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.title is not None or self.para is not None or self.sect4 is not None or self.internal is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docSect3Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect4': childobj_ = docSect4Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect4', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'internal': childobj_ = docInternalS3Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect3Type class docSect4Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, title=None, para=None, internal=None, mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docSect4Type.subclass: return docSect4Type.subclass(*args_, **kwargs_) else: return docSect4Type(*args_, **kwargs_) factory = staticmethod(factory) def get_title(self): return self.title def set_title(self, title): self.title = title def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='docSect4Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docSect4Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docSect4Type'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docSect4Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.title is not None or self.para is not None or self.internal is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docSect4Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': childobj_ = docTitleType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'title', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'internal': childobj_ = docInternalS4Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'internal', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docSect4Type class docInternalType(GeneratedsSuper): subclass = None superclass = None def __init__(self, para=None, sect1=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docInternalType.subclass: return docInternalType.subclass(*args_, **kwargs_) else: return docInternalType(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect1(self): return self.sect1 def set_sect1(self, sect1): self.sect1 = sect1 def add_sect1(self, value): self.sect1.append(value) def insert_sect1(self, index, value): self.sect1[index] = value def export(self, outfile, level, namespace_='', name_='docInternalType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docInternalType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docInternalType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docInternalType'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.para is not None or self.sect1 is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docInternalType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect1': childobj_ = docSect1Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect1', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalType class docInternalS1Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, para=None, sect2=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docInternalS1Type.subclass: return docInternalS1Type.subclass(*args_, **kwargs_) else: return docInternalS1Type(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect2(self): return self.sect2 def set_sect2(self, sect2): self.sect2 = sect2 def add_sect2(self, value): self.sect2.append(value) def insert_sect2(self, index, value): self.sect2[index] = value def export(self, outfile, level, namespace_='', name_='docInternalS1Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docInternalS1Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS1Type'): pass def exportChildren(self, outfile, level, namespace_='', name_='docInternalS1Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.para is not None or self.sect2 is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docInternalS1Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect2': childobj_ = docSect2Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect2', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS1Type class docInternalS2Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docInternalS2Type.subclass: return docInternalS2Type.subclass(*args_, **kwargs_) else: return docInternalS2Type(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect3(self): return self.sect3 def set_sect3(self, sect3): self.sect3 = sect3 def add_sect3(self, value): self.sect3.append(value) def insert_sect3(self, index, value): self.sect3[index] = value def export(self, outfile, level, namespace_='', name_='docInternalS2Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docInternalS2Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS2Type'): pass def exportChildren(self, outfile, level, namespace_='', name_='docInternalS2Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.para is not None or self.sect3 is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docInternalS2Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect3': childobj_ = docSect3Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect3', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS2Type class docInternalS3Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docInternalS3Type.subclass: return docInternalS3Type.subclass(*args_, **kwargs_) else: return docInternalS3Type(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect3(self): return self.sect3 def set_sect3(self, sect3): self.sect3 = sect3 def add_sect3(self, value): self.sect3.append(value) def insert_sect3(self, index, value): self.sect3[index] = value def export(self, outfile, level, namespace_='', name_='docInternalS3Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docInternalS3Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS3Type'): pass def exportChildren(self, outfile, level, namespace_='', name_='docInternalS3Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.para is not None or self.sect3 is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docInternalS3Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect3': childobj_ = docSect4Type.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'sect3', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS3Type class docInternalS4Type(GeneratedsSuper): subclass = None superclass = None def __init__(self, para=None, mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docInternalS4Type.subclass: return docInternalS4Type.subclass(*args_, **kwargs_) else: return docInternalS4Type(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def export(self, outfile, level, namespace_='', name_='docInternalS4Type', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docInternalS4Type') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docInternalS4Type'): pass def exportChildren(self, outfile, level, namespace_='', name_='docInternalS4Type'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.para is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docInternalS4Type'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': childobj_ = docParaType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'para', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docInternalS4Type class docTitleType(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docTitleType.subclass: return docTitleType.subclass(*args_, **kwargs_) else: return docTitleType(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docTitleType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docTitleType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docTitleType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docTitleType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docTitleType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docTitleType class docParaType(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docParaType.subclass: return docParaType.subclass(*args_, **kwargs_) else: return docParaType(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docParaType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docParaType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docParaType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docParaType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docParaType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docParaType class docMarkupType(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docMarkupType.subclass: return docMarkupType.subclass(*args_, **kwargs_) else: return docMarkupType(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docMarkupType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docMarkupType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docMarkupType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docMarkupType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docMarkupType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docMarkupType class docURLLink(GeneratedsSuper): subclass = None superclass = None def __init__(self, url=None, valueOf_='', mixedclass_=None, content_=None): self.url = url if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docURLLink.subclass: return docURLLink.subclass(*args_, **kwargs_) else: return docURLLink(*args_, **kwargs_) factory = staticmethod(factory) def get_url(self): return self.url def set_url(self, url): self.url = url def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docURLLink', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docURLLink') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docURLLink'): if self.url is not None: outfile.write(' url=%s' % (self.format_string(quote_attrib(self.url).encode(ExternalEncoding), input_name='url'), )) def exportChildren(self, outfile, level, namespace_='', name_='docURLLink'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docURLLink'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.url is not None: showIndent(outfile, level) outfile.write('url = %s,\n' % (self.url,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('url'): self.url = attrs.get('url').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docURLLink class docAnchorType(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docAnchorType.subclass: return docAnchorType.subclass(*args_, **kwargs_) else: return docAnchorType(*args_, **kwargs_) factory = staticmethod(factory) def get_id(self): return self.id def set_id(self, id): self.id = id def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docAnchorType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docAnchorType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docAnchorType'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docAnchorType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docAnchorType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docAnchorType class docFormulaType(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docFormulaType.subclass: return docFormulaType.subclass(*args_, **kwargs_) else: return docFormulaType(*args_, **kwargs_) factory = staticmethod(factory) def get_id(self): return self.id def set_id(self, id): self.id = id def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docFormulaType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docFormulaType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docFormulaType'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docFormulaType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docFormulaType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docFormulaType class docIndexEntryType(GeneratedsSuper): subclass = None superclass = None def __init__(self, primaryie=None, secondaryie=None): self.primaryie = primaryie self.secondaryie = secondaryie def factory(*args_, **kwargs_): if docIndexEntryType.subclass: return docIndexEntryType.subclass(*args_, **kwargs_) else: return docIndexEntryType(*args_, **kwargs_) factory = staticmethod(factory) def get_primaryie(self): return self.primaryie def set_primaryie(self, primaryie): self.primaryie = primaryie def get_secondaryie(self): return self.secondaryie def set_secondaryie(self, secondaryie): self.secondaryie = secondaryie def export(self, outfile, level, namespace_='', name_='docIndexEntryType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docIndexEntryType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docIndexEntryType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docIndexEntryType'): if self.primaryie is not None: showIndent(outfile, level) outfile.write('<%sprimaryie>%s</%sprimaryie>\n' % (namespace_, self.format_string(quote_xml(self.primaryie).encode(ExternalEncoding), input_name='primaryie'), namespace_)) if self.secondaryie is not None: showIndent(outfile, level) outfile.write('<%ssecondaryie>%s</%ssecondaryie>\n' % (namespace_, self.format_string(quote_xml(self.secondaryie).encode(ExternalEncoding), input_name='secondaryie'), namespace_)) def hasContent_(self): if ( self.primaryie is not None or self.secondaryie is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docIndexEntryType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('primaryie=%s,\n' % quote_python(self.primaryie).encode(ExternalEncoding)) showIndent(outfile, level) outfile.write('secondaryie=%s,\n' % quote_python(self.secondaryie).encode(ExternalEncoding)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'primaryie': primaryie_ = '' for text__content_ in child_.childNodes: primaryie_ += text__content_.nodeValue self.primaryie = primaryie_ elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'secondaryie': secondaryie_ = '' for text__content_ in child_.childNodes: secondaryie_ += text__content_.nodeValue self.secondaryie = secondaryie_ # end class docIndexEntryType class docListType(GeneratedsSuper): subclass = None superclass = None def __init__(self, listitem=None): if listitem is None: self.listitem = [] else: self.listitem = listitem def factory(*args_, **kwargs_): if docListType.subclass: return docListType.subclass(*args_, **kwargs_) else: return docListType(*args_, **kwargs_) factory = staticmethod(factory) def get_listitem(self): return self.listitem def set_listitem(self, listitem): self.listitem = listitem def add_listitem(self, value): self.listitem.append(value) def insert_listitem(self, index, value): self.listitem[index] = value def export(self, outfile, level, namespace_='', name_='docListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docListType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docListType'): for listitem_ in self.listitem: listitem_.export(outfile, level, namespace_, name_='listitem') def hasContent_(self): if ( self.listitem is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('listitem=[\n') level += 1 for listitem in self.listitem: showIndent(outfile, level) outfile.write('model_.listitem(\n') listitem.exportLiteral(outfile, level, name_='listitem') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'listitem': obj_ = docListItemType.factory() obj_.build(child_) self.listitem.append(obj_) # end class docListType class docListItemType(GeneratedsSuper): subclass = None superclass = None def __init__(self, para=None): if para is None: self.para = [] else: self.para = para def factory(*args_, **kwargs_): if docListItemType.subclass: return docListItemType.subclass(*args_, **kwargs_) else: return docListItemType(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def export(self, outfile, level, namespace_='', name_='docListItemType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docListItemType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docListItemType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docListItemType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') def hasContent_(self): if ( self.para is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docListItemType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') level += 1 for para in self.para: showIndent(outfile, level) outfile.write('model_.para(\n') para.exportLiteral(outfile, level, name_='para') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) # end class docListItemType class docSimpleSectType(GeneratedsSuper): subclass = None superclass = None def __init__(self, kind=None, title=None, para=None): self.kind = kind self.title = title if para is None: self.para = [] else: self.para = para def factory(*args_, **kwargs_): if docSimpleSectType.subclass: return docSimpleSectType.subclass(*args_, **kwargs_) else: return docSimpleSectType(*args_, **kwargs_) factory = staticmethod(factory) def get_title(self): return self.title def set_title(self, title): self.title = title def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def export(self, outfile, level, namespace_='', name_='docSimpleSectType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docSimpleSectType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docSimpleSectType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) def exportChildren(self, outfile, level, namespace_='', name_='docSimpleSectType'): if self.title: self.title.export(outfile, level, namespace_, name_='title') for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') def hasContent_(self): if ( self.title is not None or self.para is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docSimpleSectType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) def exportLiteralChildren(self, outfile, level, name_): if self.title: showIndent(outfile, level) outfile.write('title=model_.docTitleType(\n') self.title.exportLiteral(outfile, level, name_='title') showIndent(outfile, level) outfile.write('),\n') showIndent(outfile, level) outfile.write('para=[\n') level += 1 for para in self.para: showIndent(outfile, level) outfile.write('model_.para(\n') para.exportLiteral(outfile, level, name_='para') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'title': obj_ = docTitleType.factory() obj_.build(child_) self.set_title(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) # end class docSimpleSectType class docVarListEntryType(GeneratedsSuper): subclass = None superclass = None def __init__(self, term=None): self.term = term def factory(*args_, **kwargs_): if docVarListEntryType.subclass: return docVarListEntryType.subclass(*args_, **kwargs_) else: return docVarListEntryType(*args_, **kwargs_) factory = staticmethod(factory) def get_term(self): return self.term def set_term(self, term): self.term = term def export(self, outfile, level, namespace_='', name_='docVarListEntryType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docVarListEntryType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docVarListEntryType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docVarListEntryType'): if self.term: self.term.export(outfile, level, namespace_, name_='term', ) def hasContent_(self): if ( self.term is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docVarListEntryType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): if self.term: showIndent(outfile, level) outfile.write('term=model_.docTitleType(\n') self.term.exportLiteral(outfile, level, name_='term') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'term': obj_ = docTitleType.factory() obj_.build(child_) self.set_term(obj_) # end class docVarListEntryType class docVariableListType(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if docVariableListType.subclass: return docVariableListType.subclass(*args_, **kwargs_) else: return docVariableListType(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docVariableListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docVariableListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docVariableListType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docVariableListType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docVariableListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docVariableListType class docRefTextType(GeneratedsSuper): subclass = None superclass = None def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None): self.refid = refid self.kindref = kindref self.external = external if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docRefTextType.subclass: return docRefTextType.subclass(*args_, **kwargs_) else: return docRefTextType(*args_, **kwargs_) factory = staticmethod(factory) def get_refid(self): return self.refid def set_refid(self, refid): self.refid = refid def get_kindref(self): return self.kindref def set_kindref(self, kindref): self.kindref = kindref def get_external(self): return self.external def set_external(self, external): self.external = external def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docRefTextType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docRefTextType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docRefTextType'): if self.refid is not None: outfile.write(' refid=%s' % (self.format_string(quote_attrib(self.refid).encode(ExternalEncoding), input_name='refid'), )) if self.kindref is not None: outfile.write(' kindref=%s' % (quote_attrib(self.kindref), )) if self.external is not None: outfile.write(' external=%s' % (self.format_string(quote_attrib(self.external).encode(ExternalEncoding), input_name='external'), )) def exportChildren(self, outfile, level, namespace_='', name_='docRefTextType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docRefTextType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.refid is not None: showIndent(outfile, level) outfile.write('refid = %s,\n' % (self.refid,)) if self.kindref is not None: showIndent(outfile, level) outfile.write('kindref = "%s",\n' % (self.kindref,)) if self.external is not None: showIndent(outfile, level) outfile.write('external = %s,\n' % (self.external,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('refid'): self.refid = attrs.get('refid').value if attrs.get('kindref'): self.kindref = attrs.get('kindref').value if attrs.get('external'): self.external = attrs.get('external').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docRefTextType class docTableType(GeneratedsSuper): subclass = None superclass = None def __init__(self, rows=None, cols=None, row=None, caption=None): self.rows = rows self.cols = cols if row is None: self.row = [] else: self.row = row self.caption = caption def factory(*args_, **kwargs_): if docTableType.subclass: return docTableType.subclass(*args_, **kwargs_) else: return docTableType(*args_, **kwargs_) factory = staticmethod(factory) def get_row(self): return self.row def set_row(self, row): self.row = row def add_row(self, value): self.row.append(value) def insert_row(self, index, value): self.row[index] = value def get_caption(self): return self.caption def set_caption(self, caption): self.caption = caption def get_rows(self): return self.rows def set_rows(self, rows): self.rows = rows def get_cols(self): return self.cols def set_cols(self, cols): self.cols = cols def export(self, outfile, level, namespace_='', name_='docTableType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docTableType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docTableType'): if self.rows is not None: outfile.write(' rows="%s"' % self.format_integer(self.rows, input_name='rows')) if self.cols is not None: outfile.write(' cols="%s"' % self.format_integer(self.cols, input_name='cols')) def exportChildren(self, outfile, level, namespace_='', name_='docTableType'): for row_ in self.row: row_.export(outfile, level, namespace_, name_='row') if self.caption: self.caption.export(outfile, level, namespace_, name_='caption') def hasContent_(self): if ( self.row is not None or self.caption is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docTableType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.rows is not None: showIndent(outfile, level) outfile.write('rows = %s,\n' % (self.rows,)) if self.cols is not None: showIndent(outfile, level) outfile.write('cols = %s,\n' % (self.cols,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('row=[\n') level += 1 for row in self.row: showIndent(outfile, level) outfile.write('model_.row(\n') row.exportLiteral(outfile, level, name_='row') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.caption: showIndent(outfile, level) outfile.write('caption=model_.docCaptionType(\n') self.caption.exportLiteral(outfile, level, name_='caption') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('rows'): try: self.rows = int(attrs.get('rows').value) except ValueError, exp: raise ValueError('Bad integer attribute (rows): %s' % exp) if attrs.get('cols'): try: self.cols = int(attrs.get('cols').value) except ValueError, exp: raise ValueError('Bad integer attribute (cols): %s' % exp) def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'row': obj_ = docRowType.factory() obj_.build(child_) self.row.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'caption': obj_ = docCaptionType.factory() obj_.build(child_) self.set_caption(obj_) # end class docTableType class docRowType(GeneratedsSuper): subclass = None superclass = None def __init__(self, entry=None): if entry is None: self.entry = [] else: self.entry = entry def factory(*args_, **kwargs_): if docRowType.subclass: return docRowType.subclass(*args_, **kwargs_) else: return docRowType(*args_, **kwargs_) factory = staticmethod(factory) def get_entry(self): return self.entry def set_entry(self, entry): self.entry = entry def add_entry(self, value): self.entry.append(value) def insert_entry(self, index, value): self.entry[index] = value def export(self, outfile, level, namespace_='', name_='docRowType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docRowType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docRowType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docRowType'): for entry_ in self.entry: entry_.export(outfile, level, namespace_, name_='entry') def hasContent_(self): if ( self.entry is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docRowType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('entry=[\n') level += 1 for entry in self.entry: showIndent(outfile, level) outfile.write('model_.entry(\n') entry.exportLiteral(outfile, level, name_='entry') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'entry': obj_ = docEntryType.factory() obj_.build(child_) self.entry.append(obj_) # end class docRowType class docEntryType(GeneratedsSuper): subclass = None superclass = None def __init__(self, thead=None, para=None): self.thead = thead if para is None: self.para = [] else: self.para = para def factory(*args_, **kwargs_): if docEntryType.subclass: return docEntryType.subclass(*args_, **kwargs_) else: return docEntryType(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_thead(self): return self.thead def set_thead(self, thead): self.thead = thead def export(self, outfile, level, namespace_='', name_='docEntryType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docEntryType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docEntryType'): if self.thead is not None: outfile.write(' thead=%s' % (quote_attrib(self.thead), )) def exportChildren(self, outfile, level, namespace_='', name_='docEntryType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') def hasContent_(self): if ( self.para is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docEntryType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.thead is not None: showIndent(outfile, level) outfile.write('thead = "%s",\n' % (self.thead,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') level += 1 for para in self.para: showIndent(outfile, level) outfile.write('model_.para(\n') para.exportLiteral(outfile, level, name_='para') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('thead'): self.thead = attrs.get('thead').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) # end class docEntryType class docCaptionType(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_='', mixedclass_=None, content_=None): if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docCaptionType.subclass: return docCaptionType.subclass(*args_, **kwargs_) else: return docCaptionType(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docCaptionType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docCaptionType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docCaptionType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docCaptionType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docCaptionType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docCaptionType class docHeadingType(GeneratedsSuper): subclass = None superclass = None def __init__(self, level=None, valueOf_='', mixedclass_=None, content_=None): self.level = level if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docHeadingType.subclass: return docHeadingType.subclass(*args_, **kwargs_) else: return docHeadingType(*args_, **kwargs_) factory = staticmethod(factory) def get_level(self): return self.level def set_level(self, level): self.level = level def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docHeadingType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docHeadingType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docHeadingType'): if self.level is not None: outfile.write(' level="%s"' % self.format_integer(self.level, input_name='level')) def exportChildren(self, outfile, level, namespace_='', name_='docHeadingType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docHeadingType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.level is not None: showIndent(outfile, level) outfile.write('level = %s,\n' % (self.level,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('level'): try: self.level = int(attrs.get('level').value) except ValueError, exp: raise ValueError('Bad integer attribute (level): %s' % exp) def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docHeadingType class docImageType(GeneratedsSuper): subclass = None superclass = None def __init__(self, width=None, type_=None, name=None, height=None, valueOf_='', mixedclass_=None, content_=None): self.width = width self.type_ = type_ self.name = name self.height = height if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docImageType.subclass: return docImageType.subclass(*args_, **kwargs_) else: return docImageType(*args_, **kwargs_) factory = staticmethod(factory) def get_width(self): return self.width def set_width(self, width): self.width = width def get_type(self): return self.type_ def set_type(self, type_): self.type_ = type_ def get_name(self): return self.name def set_name(self, name): self.name = name def get_height(self): return self.height def set_height(self, height): self.height = height def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docImageType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docImageType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docImageType'): if self.width is not None: outfile.write(' width=%s' % (self.format_string(quote_attrib(self.width).encode(ExternalEncoding), input_name='width'), )) if self.type_ is not None: outfile.write(' type=%s' % (quote_attrib(self.type_), )) if self.name is not None: outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) if self.height is not None: outfile.write(' height=%s' % (self.format_string(quote_attrib(self.height).encode(ExternalEncoding), input_name='height'), )) def exportChildren(self, outfile, level, namespace_='', name_='docImageType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docImageType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.width is not None: showIndent(outfile, level) outfile.write('width = %s,\n' % (self.width,)) if self.type_ is not None: showIndent(outfile, level) outfile.write('type_ = "%s",\n' % (self.type_,)) if self.name is not None: showIndent(outfile, level) outfile.write('name = %s,\n' % (self.name,)) if self.height is not None: showIndent(outfile, level) outfile.write('height = %s,\n' % (self.height,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('width'): self.width = attrs.get('width').value if attrs.get('type'): self.type_ = attrs.get('type').value if attrs.get('name'): self.name = attrs.get('name').value if attrs.get('height'): self.height = attrs.get('height').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docImageType class docDotFileType(GeneratedsSuper): subclass = None superclass = None def __init__(self, name=None, valueOf_='', mixedclass_=None, content_=None): self.name = name if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docDotFileType.subclass: return docDotFileType.subclass(*args_, **kwargs_) else: return docDotFileType(*args_, **kwargs_) factory = staticmethod(factory) def get_name(self): return self.name def set_name(self, name): self.name = name def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docDotFileType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docDotFileType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docDotFileType'): if self.name is not None: outfile.write(' name=%s' % (self.format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), )) def exportChildren(self, outfile, level, namespace_='', name_='docDotFileType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docDotFileType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.name is not None: showIndent(outfile, level) outfile.write('name = %s,\n' % (self.name,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('name'): self.name = attrs.get('name').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docDotFileType class docTocItemType(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None): self.id = id if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docTocItemType.subclass: return docTocItemType.subclass(*args_, **kwargs_) else: return docTocItemType(*args_, **kwargs_) factory = staticmethod(factory) def get_id(self): return self.id def set_id(self, id): self.id = id def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docTocItemType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docTocItemType') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docTocItemType'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docTocItemType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docTocItemType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docTocItemType class docTocListType(GeneratedsSuper): subclass = None superclass = None def __init__(self, tocitem=None): if tocitem is None: self.tocitem = [] else: self.tocitem = tocitem def factory(*args_, **kwargs_): if docTocListType.subclass: return docTocListType.subclass(*args_, **kwargs_) else: return docTocListType(*args_, **kwargs_) factory = staticmethod(factory) def get_tocitem(self): return self.tocitem def set_tocitem(self, tocitem): self.tocitem = tocitem def add_tocitem(self, value): self.tocitem.append(value) def insert_tocitem(self, index, value): self.tocitem[index] = value def export(self, outfile, level, namespace_='', name_='docTocListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docTocListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docTocListType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docTocListType'): for tocitem_ in self.tocitem: tocitem_.export(outfile, level, namespace_, name_='tocitem') def hasContent_(self): if ( self.tocitem is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docTocListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('tocitem=[\n') level += 1 for tocitem in self.tocitem: showIndent(outfile, level) outfile.write('model_.tocitem(\n') tocitem.exportLiteral(outfile, level, name_='tocitem') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'tocitem': obj_ = docTocItemType.factory() obj_.build(child_) self.tocitem.append(obj_) # end class docTocListType class docLanguageType(GeneratedsSuper): subclass = None superclass = None def __init__(self, langid=None, para=None): self.langid = langid if para is None: self.para = [] else: self.para = para def factory(*args_, **kwargs_): if docLanguageType.subclass: return docLanguageType.subclass(*args_, **kwargs_) else: return docLanguageType(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_langid(self): return self.langid def set_langid(self, langid): self.langid = langid def export(self, outfile, level, namespace_='', name_='docLanguageType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docLanguageType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docLanguageType'): if self.langid is not None: outfile.write(' langid=%s' % (self.format_string(quote_attrib(self.langid).encode(ExternalEncoding), input_name='langid'), )) def exportChildren(self, outfile, level, namespace_='', name_='docLanguageType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') def hasContent_(self): if ( self.para is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docLanguageType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.langid is not None: showIndent(outfile, level) outfile.write('langid = %s,\n' % (self.langid,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') level += 1 for para in self.para: showIndent(outfile, level) outfile.write('model_.para(\n') para.exportLiteral(outfile, level, name_='para') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('langid'): self.langid = attrs.get('langid').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) # end class docLanguageType class docParamListType(GeneratedsSuper): subclass = None superclass = None def __init__(self, kind=None, parameteritem=None): self.kind = kind if parameteritem is None: self.parameteritem = [] else: self.parameteritem = parameteritem def factory(*args_, **kwargs_): if docParamListType.subclass: return docParamListType.subclass(*args_, **kwargs_) else: return docParamListType(*args_, **kwargs_) factory = staticmethod(factory) def get_parameteritem(self): return self.parameteritem def set_parameteritem(self, parameteritem): self.parameteritem = parameteritem def add_parameteritem(self, value): self.parameteritem.append(value) def insert_parameteritem(self, index, value): self.parameteritem[index] = value def get_kind(self): return self.kind def set_kind(self, kind): self.kind = kind def export(self, outfile, level, namespace_='', name_='docParamListType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docParamListType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docParamListType'): if self.kind is not None: outfile.write(' kind=%s' % (quote_attrib(self.kind), )) def exportChildren(self, outfile, level, namespace_='', name_='docParamListType'): for parameteritem_ in self.parameteritem: parameteritem_.export(outfile, level, namespace_, name_='parameteritem') def hasContent_(self): if ( self.parameteritem is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docParamListType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.kind is not None: showIndent(outfile, level) outfile.write('kind = "%s",\n' % (self.kind,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('parameteritem=[\n') level += 1 for parameteritem in self.parameteritem: showIndent(outfile, level) outfile.write('model_.parameteritem(\n') parameteritem.exportLiteral(outfile, level, name_='parameteritem') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('kind'): self.kind = attrs.get('kind').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'parameteritem': obj_ = docParamListItem.factory() obj_.build(child_) self.parameteritem.append(obj_) # end class docParamListType class docParamListItem(GeneratedsSuper): subclass = None superclass = None def __init__(self, parameternamelist=None, parameterdescription=None): if parameternamelist is None: self.parameternamelist = [] else: self.parameternamelist = parameternamelist self.parameterdescription = parameterdescription def factory(*args_, **kwargs_): if docParamListItem.subclass: return docParamListItem.subclass(*args_, **kwargs_) else: return docParamListItem(*args_, **kwargs_) factory = staticmethod(factory) def get_parameternamelist(self): return self.parameternamelist def set_parameternamelist(self, parameternamelist): self.parameternamelist = parameternamelist def add_parameternamelist(self, value): self.parameternamelist.append(value) def insert_parameternamelist(self, index, value): self.parameternamelist[index] = value def get_parameterdescription(self): return self.parameterdescription def set_parameterdescription(self, parameterdescription): self.parameterdescription = parameterdescription def export(self, outfile, level, namespace_='', name_='docParamListItem', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docParamListItem') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docParamListItem'): pass def exportChildren(self, outfile, level, namespace_='', name_='docParamListItem'): for parameternamelist_ in self.parameternamelist: parameternamelist_.export(outfile, level, namespace_, name_='parameternamelist') if self.parameterdescription: self.parameterdescription.export(outfile, level, namespace_, name_='parameterdescription', ) def hasContent_(self): if ( self.parameternamelist is not None or self.parameterdescription is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docParamListItem'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('parameternamelist=[\n') level += 1 for parameternamelist in self.parameternamelist: showIndent(outfile, level) outfile.write('model_.parameternamelist(\n') parameternamelist.exportLiteral(outfile, level, name_='parameternamelist') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.parameterdescription: showIndent(outfile, level) outfile.write('parameterdescription=model_.descriptionType(\n') self.parameterdescription.exportLiteral(outfile, level, name_='parameterdescription') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'parameternamelist': obj_ = docParamNameList.factory() obj_.build(child_) self.parameternamelist.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'parameterdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_parameterdescription(obj_) # end class docParamListItem class docParamNameList(GeneratedsSuper): subclass = None superclass = None def __init__(self, parametername=None): if parametername is None: self.parametername = [] else: self.parametername = parametername def factory(*args_, **kwargs_): if docParamNameList.subclass: return docParamNameList.subclass(*args_, **kwargs_) else: return docParamNameList(*args_, **kwargs_) factory = staticmethod(factory) def get_parametername(self): return self.parametername def set_parametername(self, parametername): self.parametername = parametername def add_parametername(self, value): self.parametername.append(value) def insert_parametername(self, index, value): self.parametername[index] = value def export(self, outfile, level, namespace_='', name_='docParamNameList', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docParamNameList') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docParamNameList'): pass def exportChildren(self, outfile, level, namespace_='', name_='docParamNameList'): for parametername_ in self.parametername: parametername_.export(outfile, level, namespace_, name_='parametername') def hasContent_(self): if ( self.parametername is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docParamNameList'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('parametername=[\n') level += 1 for parametername in self.parametername: showIndent(outfile, level) outfile.write('model_.parametername(\n') parametername.exportLiteral(outfile, level, name_='parametername') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'parametername': obj_ = docParamName.factory() obj_.build(child_) self.parametername.append(obj_) # end class docParamNameList class docParamName(GeneratedsSuper): subclass = None superclass = None def __init__(self, direction=None, ref=None, mixedclass_=None, content_=None): self.direction = direction if mixedclass_ is None: self.mixedclass_ = MixedContainer else: self.mixedclass_ = mixedclass_ if content_ is None: self.content_ = [] else: self.content_ = content_ def factory(*args_, **kwargs_): if docParamName.subclass: return docParamName.subclass(*args_, **kwargs_) else: return docParamName(*args_, **kwargs_) factory = staticmethod(factory) def get_ref(self): return self.ref def set_ref(self, ref): self.ref = ref def get_direction(self): return self.direction def set_direction(self, direction): self.direction = direction def export(self, outfile, level, namespace_='', name_='docParamName', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docParamName') outfile.write('>') self.exportChildren(outfile, level + 1, namespace_, name_) outfile.write('</%s%s>\n' % (namespace_, name_)) def exportAttributes(self, outfile, level, namespace_='', name_='docParamName'): if self.direction is not None: outfile.write(' direction=%s' % (quote_attrib(self.direction), )) def exportChildren(self, outfile, level, namespace_='', name_='docParamName'): for item_ in self.content_: item_.export(outfile, level, item_.name, namespace_) def hasContent_(self): if ( self.ref is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docParamName'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.direction is not None: showIndent(outfile, level) outfile.write('direction = "%s",\n' % (self.direction,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('content_ = [\n') for item_ in self.content_: item_.exportLiteral(outfile, level, name_) showIndent(outfile, level) outfile.write('],\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('direction'): self.direction = attrs.get('direction').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'ref': childobj_ = docRefTextType.factory() childobj_.build(child_) obj_ = self.mixedclass_(MixedContainer.CategoryComplex, MixedContainer.TypeNone, 'ref', childobj_) self.content_.append(obj_) elif child_.nodeType == Node.TEXT_NODE: obj_ = self.mixedclass_(MixedContainer.CategoryText, MixedContainer.TypeNone, '', child_.nodeValue) self.content_.append(obj_) # end class docParamName class docXRefSectType(GeneratedsSuper): subclass = None superclass = None def __init__(self, id=None, xreftitle=None, xrefdescription=None): self.id = id if xreftitle is None: self.xreftitle = [] else: self.xreftitle = xreftitle self.xrefdescription = xrefdescription def factory(*args_, **kwargs_): if docXRefSectType.subclass: return docXRefSectType.subclass(*args_, **kwargs_) else: return docXRefSectType(*args_, **kwargs_) factory = staticmethod(factory) def get_xreftitle(self): return self.xreftitle def set_xreftitle(self, xreftitle): self.xreftitle = xreftitle def add_xreftitle(self, value): self.xreftitle.append(value) def insert_xreftitle(self, index, value): self.xreftitle[index] = value def get_xrefdescription(self): return self.xrefdescription def set_xrefdescription(self, xrefdescription): self.xrefdescription = xrefdescription def get_id(self): return self.id def set_id(self, id): self.id = id def export(self, outfile, level, namespace_='', name_='docXRefSectType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docXRefSectType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docXRefSectType'): if self.id is not None: outfile.write(' id=%s' % (self.format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), )) def exportChildren(self, outfile, level, namespace_='', name_='docXRefSectType'): for xreftitle_ in self.xreftitle: showIndent(outfile, level) outfile.write('<%sxreftitle>%s</%sxreftitle>\n' % (namespace_, self.format_string(quote_xml(xreftitle_).encode(ExternalEncoding), input_name='xreftitle'), namespace_)) if self.xrefdescription: self.xrefdescription.export(outfile, level, namespace_, name_='xrefdescription', ) def hasContent_(self): if ( self.xreftitle is not None or self.xrefdescription is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docXRefSectType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.id is not None: showIndent(outfile, level) outfile.write('id = %s,\n' % (self.id,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('xreftitle=[\n') level += 1 for xreftitle in self.xreftitle: showIndent(outfile, level) outfile.write('%s,\n' % quote_python(xreftitle).encode(ExternalEncoding)) level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.xrefdescription: showIndent(outfile, level) outfile.write('xrefdescription=model_.descriptionType(\n') self.xrefdescription.exportLiteral(outfile, level, name_='xrefdescription') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('id'): self.id = attrs.get('id').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'xreftitle': xreftitle_ = '' for text__content_ in child_.childNodes: xreftitle_ += text__content_.nodeValue self.xreftitle.append(xreftitle_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'xrefdescription': obj_ = descriptionType.factory() obj_.build(child_) self.set_xrefdescription(obj_) # end class docXRefSectType class docCopyType(GeneratedsSuper): subclass = None superclass = None def __init__(self, link=None, para=None, sect1=None, internal=None): self.link = link if para is None: self.para = [] else: self.para = para if sect1 is None: self.sect1 = [] else: self.sect1 = sect1 self.internal = internal def factory(*args_, **kwargs_): if docCopyType.subclass: return docCopyType.subclass(*args_, **kwargs_) else: return docCopyType(*args_, **kwargs_) factory = staticmethod(factory) def get_para(self): return self.para def set_para(self, para): self.para = para def add_para(self, value): self.para.append(value) def insert_para(self, index, value): self.para[index] = value def get_sect1(self): return self.sect1 def set_sect1(self, sect1): self.sect1 = sect1 def add_sect1(self, value): self.sect1.append(value) def insert_sect1(self, index, value): self.sect1[index] = value def get_internal(self): return self.internal def set_internal(self, internal): self.internal = internal def get_link(self): return self.link def set_link(self, link): self.link = link def export(self, outfile, level, namespace_='', name_='docCopyType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docCopyType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docCopyType'): if self.link is not None: outfile.write(' link=%s' % (self.format_string(quote_attrib(self.link).encode(ExternalEncoding), input_name='link'), )) def exportChildren(self, outfile, level, namespace_='', name_='docCopyType'): for para_ in self.para: para_.export(outfile, level, namespace_, name_='para') for sect1_ in self.sect1: sect1_.export(outfile, level, namespace_, name_='sect1') if self.internal: self.internal.export(outfile, level, namespace_, name_='internal') def hasContent_(self): if ( self.para is not None or self.sect1 is not None or self.internal is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docCopyType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.link is not None: showIndent(outfile, level) outfile.write('link = %s,\n' % (self.link,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('para=[\n') level += 1 for para in self.para: showIndent(outfile, level) outfile.write('model_.para(\n') para.exportLiteral(outfile, level, name_='para') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') showIndent(outfile, level) outfile.write('sect1=[\n') level += 1 for sect1 in self.sect1: showIndent(outfile, level) outfile.write('model_.sect1(\n') sect1.exportLiteral(outfile, level, name_='sect1') showIndent(outfile, level) outfile.write('),\n') level -= 1 showIndent(outfile, level) outfile.write('],\n') if self.internal: showIndent(outfile, level) outfile.write('internal=model_.docInternalType(\n') self.internal.exportLiteral(outfile, level, name_='internal') showIndent(outfile, level) outfile.write('),\n') def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('link'): self.link = attrs.get('link').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'para': obj_ = docParaType.factory() obj_.build(child_) self.para.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'sect1': obj_ = docSect1Type.factory() obj_.build(child_) self.sect1.append(obj_) elif child_.nodeType == Node.ELEMENT_NODE and \ nodeName_ == 'internal': obj_ = docInternalType.factory() obj_.build(child_) self.set_internal(obj_) # end class docCopyType class docCharType(GeneratedsSuper): subclass = None superclass = None def __init__(self, char=None, valueOf_=''): self.char = char self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if docCharType.subclass: return docCharType.subclass(*args_, **kwargs_) else: return docCharType(*args_, **kwargs_) factory = staticmethod(factory) def get_char(self): return self.char def set_char(self, char): self.char = char def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docCharType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docCharType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docCharType'): if self.char is not None: outfile.write(' char=%s' % (quote_attrib(self.char), )) def exportChildren(self, outfile, level, namespace_='', name_='docCharType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docCharType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): if self.char is not None: showIndent(outfile, level) outfile.write('char = "%s",\n' % (self.char,)) def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): if attrs.get('char'): self.char = attrs.get('char').value def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docCharType class docEmptyType(GeneratedsSuper): subclass = None superclass = None def __init__(self, valueOf_=''): self.valueOf_ = valueOf_ def factory(*args_, **kwargs_): if docEmptyType.subclass: return docEmptyType.subclass(*args_, **kwargs_) else: return docEmptyType(*args_, **kwargs_) factory = staticmethod(factory) def getValueOf_(self): return self.valueOf_ def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ def export(self, outfile, level, namespace_='', name_='docEmptyType', namespacedef_=''): showIndent(outfile, level) outfile.write('<%s%s %s' % (namespace_, name_, namespacedef_, )) self.exportAttributes(outfile, level, namespace_, name_='docEmptyType') if self.hasContent_(): outfile.write('>\n') self.exportChildren(outfile, level + 1, namespace_, name_) showIndent(outfile, level) outfile.write('</%s%s>\n' % (namespace_, name_)) else: outfile.write(' />\n') def exportAttributes(self, outfile, level, namespace_='', name_='docEmptyType'): pass def exportChildren(self, outfile, level, namespace_='', name_='docEmptyType'): if self.valueOf_.find('![CDATA')>-1: value=quote_xml('%s' % self.valueOf_) value=value.replace('![CDATA','<![CDATA') value=value.replace(']]',']]>') outfile.write(value) else: outfile.write(quote_xml('%s' % self.valueOf_)) def hasContent_(self): if ( self.valueOf_ is not None ): return True else: return False def exportLiteral(self, outfile, level, name_='docEmptyType'): level += 1 self.exportLiteralAttributes(outfile, level, name_) if self.hasContent_(): self.exportLiteralChildren(outfile, level, name_) def exportLiteralAttributes(self, outfile, level, name_): pass def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) self.valueOf_ = '' for child_ in node_.childNodes: nodeName_ = child_.nodeName.split(':')[-1] self.buildChildren(child_, nodeName_) def buildAttributes(self, attrs): pass def buildChildren(self, child_, nodeName_): if child_.nodeType == Node.TEXT_NODE: self.valueOf_ += child_.nodeValue elif child_.nodeType == Node.CDATA_SECTION_NODE: self.valueOf_ += '![CDATA['+child_.nodeValue+']]' # end class docEmptyType USAGE_TEXT = """ Usage: python <Parser>.py [ -s ] <in_xml_file> Options: -s Use the SAX parser, not the minidom parser. """ def usage(): print USAGE_TEXT sys.exit(1) def parse(inFileName): doc = minidom.parse(inFileName) rootNode = doc.documentElement rootObj = DoxygenType.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export(sys.stdout, 0, name_="doxygen", namespacedef_='') return rootObj def parseString(inString): doc = minidom.parseString(inString) rootNode = doc.documentElement rootObj = DoxygenType.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export(sys.stdout, 0, name_="doxygen", namespacedef_='') return rootObj def parseLiteral(inFileName): doc = minidom.parse(inFileName) rootNode = doc.documentElement rootObj = DoxygenType.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None sys.stdout.write('from compound import *\n\n') sys.stdout.write('rootObj = doxygen(\n') rootObj.exportLiteral(sys.stdout, 0, name_="doxygen") sys.stdout.write(')\n') return rootObj def main(): args = sys.argv[1:] if len(args) == 1: parse(args[0]) else: usage() if __name__ == '__main__': main() #import pdb #pdb.run('main()')
gpl-3.0
kingvuplus/Rudream-gui
lib/python/Plugins/SystemPlugins/Videomode/VideoWizard.py
12
6022
from Screens.Wizard import WizardSummary from Screens.WizardLanguage import WizardLanguage from Screens.Rc import Rc from VideoHardware import video_hw from Components.Pixmap import Pixmap, MovingPixmap, MultiPixmap from Components.config import config, ConfigBoolean, configfile from Tools.Directories import resolveFilename, SCOPE_PLUGINS from Tools.HardwareInfo import HardwareInfo config.misc.showtestcard = ConfigBoolean(default = False) class VideoWizardSummary(WizardSummary): def __init__(self, session, parent): WizardSummary.__init__(self, session, parent) def setLCDPicCallback(self): self.parent.setLCDTextCallback(self.setText) def setLCDPic(self, file): self["pic"].instance.setPixmapFromFile(file) class VideoWizard(WizardLanguage, Rc): skin = """ <screen position="fill" title="Welcome..." flags="wfNoBorder" > <panel name="WizardMarginsTemplate"/> <panel name="WizardPictureLangTemplate"/> <panel name="RemoteControlTemplate"/> <panel position="left" size="10,*" /> <panel position="right" size="10,*" /> <panel position="fill"> <widget name="text" position="top" size="*,270" font="Regular;23" valign="center" /> <panel position="fill"> <panel position="left" size="150,*"> <widget name="portpic" position="top" zPosition="10" size="150,150" transparent="1" alphatest="on"/> </panel> <panel position="fill" layout="stack"> <widget source="list" render="Listbox" position="fill" scrollbarMode="showOnDemand" > <convert type="StringList" /> </widget> <!--<widget name="config" position="fill" zPosition="1" scrollbarMode="showOnDemand" />--> </panel> </panel> </panel> </screen>""" def __init__(self, session): # FIXME anyone knows how to use relative paths from the plugin's directory? self.xmlfile = resolveFilename(SCOPE_PLUGINS, "SystemPlugins/Videomode/videowizard.xml") self.hw = video_hw WizardLanguage.__init__(self, session, showSteps = False, showStepSlider = False) Rc.__init__(self) self["wizard"] = Pixmap() self["portpic"] = Pixmap() self.port = None self.mode = None self.rate = None def createSummary(self): print "++++++++++++***++**** VideoWizard-createSummary" from Screens.Wizard import WizardSummary return VideoWizardSummary def markDone(self): self.hw.saveMode(self.port, self.mode, self.rate) config.misc.videowizardenabled.value = 0 config.misc.videowizardenabled.save() configfile.save() def listInputChannels(self): hw_type = HardwareInfo().get_device_name() has_hdmi = HardwareInfo().has_hdmi() list = [] for port in self.hw.getPortList(): if self.hw.isPortUsed(port): descr = port if descr == 'DVI' and has_hdmi: descr = 'HDMI' if port != "DVI-PC": list.append((descr,port)) list.sort(key = lambda x: x[0]) print "listInputChannels:", list return list def inputSelectionMade(self, index): print "inputSelectionMade:", index self.port = index self.inputSelect(index) def inputSelectionMoved(self): hw_type = HardwareInfo().get_device_name() has_hdmi = HardwareInfo().has_hdmi() print "input selection moved:", self.selection self.inputSelect(self.selection) if self["portpic"].instance is not None: picname = self.selection if picname == 'DVI' and has_hdmi: picname = "HDMI" self["portpic"].instance.setPixmapFromFile(resolveFilename(SCOPE_PLUGINS, "SystemPlugins/Videomode/" + picname + ".png")) def inputSelect(self, port): print "inputSelect:", port modeList = self.hw.getModeList(self.selection) print "modeList:", modeList self.port = port if (len(modeList) > 0): ratesList = self.listRates(modeList[0][0]) self.hw.setMode(port = port, mode = modeList[0][0], rate = ratesList[0][0]) def listModes(self): list = [] print "modes for port", self.port for mode in self.hw.getModeList(self.port): #if mode[0] != "PC": list.append((mode[0], mode[0])) print "modeslist:", list return list def modeSelectionMade(self, index): print "modeSelectionMade:", index self.mode = index self.modeSelect(index) def modeSelectionMoved(self): print "mode selection moved:", self.selection self.modeSelect(self.selection) def modeSelect(self, mode): ratesList = self.listRates(mode) print "ratesList:", ratesList if self.port == "DVI" and mode in ("720p", "1080i", "1080p"): self.rate = "multi" self.hw.setMode(port = self.port, mode = mode, rate = "multi") else: self.hw.setMode(port = self.port, mode = mode, rate = ratesList[0][0]) def listRates(self, querymode = None): if querymode is None: querymode = self.mode list = [] print "modes for port", self.port, "and mode", querymode for mode in self.hw.getModeList(self.port): print mode if mode[0] == querymode: for rate in mode[1]: if self.port == "DVI-PC": print "rate:", rate if rate == "640x480": list.insert(0, (rate, rate)) continue list.append((rate, rate)) return list def rateSelectionMade(self, index): print "rateSelectionMade:", index self.rate = index self.rateSelect(index) def rateSelectionMoved(self): print "rate selection moved:", self.selection self.rateSelect(self.selection) def rateSelect(self, rate): self.hw.setMode(port = self.port, mode = self.mode, rate = rate) def showTestCard(self, selection = None): if selection is None: selection = self.selection print "set config.misc.showtestcard to", {'yes': True, 'no': False}[selection] if selection == "yes": config.misc.showtestcard.value = True else: config.misc.showtestcard.value = False def keyNumberGlobal(self, number): if number in (1,2,3): if number == 1: self.hw.saveMode("DVI", "720p", "multi") elif number == 2: self.hw.saveMode("DVI", "1080i", "multi") elif number == 3: self.hw.saveMode("Scart", "Multi", "multi") self.hw.setConfiguredMode() self.close() WizardLanguage.keyNumberGlobal(self, number)
gpl-2.0
mcus/SickRage
tests/test_ssl_sni.py
3
1988
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # Author: echel0n <sickrage.tv@gmail.com> # URL: http://www.github.com/sickragetv/sickrage/ # # This file is part of SickRage. # # SickRage 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. # # SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function from __future__ import unicode_literals import os.path import sys sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib'))) sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import unittest from tests import SiCKRAGETestCase import certifi import requests import sickbeard.providers as providers from sickrage.helper.exceptions import ex class SNI_Tests(SiCKRAGETestCase): pass def test_sni(self, provider): try: requests.head(provider.url, verify=certifi.where(), timeout=5) except requests.exceptions.Timeout: pass except requests.exceptions.SSLError as error: if 'SSL3_GET_SERVER_CERTIFICATE' not in ex(error): print(error) except Exception: pass for provider in providers.sortedProviderList(): setattr(SNI_Tests, 'test_%s' % provider.name, lambda self, x=provider: test_sni(self, x)) if __name__ == "__main__": print("==================") print("STARTING - SSL TESTS") print("==================") print("######################################################################") unittest.main()
gpl-3.0
sebrandon1/nova
nova/conf/api.py
3
11106
# Copyright 2015 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg auth_opts = [ cfg.StrOpt("auth_strategy", default="keystone", choices=("keystone", "noauth2"), help=""" This determines the strategy to use for authentication: keystone or noauth2. 'noauth2' is designed for testing only, as it does no actual credential checking. 'noauth2' provides administrative credentials only if 'admin' is specified as the username. """), cfg.BoolOpt("use_forwarded_for", default=False, help=""" When True, the 'X-Forwarded-For' header is treated as the canonical remote address. When False (the default), the 'remote_address' header is used. You should only enable this if you have an HTML sanitizing proxy. """), ] metadata_opts = [ cfg.StrOpt("config_drive_skip_versions", default=("1.0 2007-01-19 2007-03-01 2007-08-29 2007-10-10 " "2007-12-15 2008-02-01 2008-09-01"), help=""" When gathering the existing metadata for a config drive, the EC2-style metadata is returned for all versions that don't appear in this option. As of the Liberty release, the available versions are: * 1.0 * 2007-01-19 * 2007-03-01 * 2007-08-29 * 2007-10-10 * 2007-12-15 * 2008-02-01 * 2008-09-01 * 2009-04-04 The option is in the format of a single string, with each version separated by a space. Possible values: * Any string that represents zero or more versions, separated by spaces. """), cfg.StrOpt("vendordata_driver", default="nova.api.metadata.vendordata_json.JsonFileVendorData", deprecated_for_removal=True, deprecated_since="13.0.0", help=""" When returning instance metadata, this is the class that is used for getting vendor metadata when that class isn't specified in the individual request. The value should be the full dot-separated path to the class to use. Possible values: * Any valid dot-separated class path that can be imported. """), cfg.ListOpt('vendordata_providers', default=[], help=""" A list of vendordata providers. vendordata providers are how deployers can provide metadata via configdrive and metadata that is specific to their deployment. There are currently two supported providers: StaticJSON and DynamicJSON. StaticJSON reads a JSON file configured by the flag vendordata_jsonfile_path and places the JSON from that file into vendor_data.json and vendor_data2.json. DynamicJSON is configured via the vendordata_dynamic_targets flag, which is documented separately. For each of the endpoints specified in that flag, a section is added to the vendor_data2.json. For more information on the requirements for implementing a vendordata dynamic endpoint, please see the vendordata.rst file in the nova developer reference. Possible values: * A list of vendordata providers, with StaticJSON and DynamicJSON being current options. Related options: * vendordata_dynamic_targets * vendordata_dynamic_ssl_certfile * vendordata_dynamic_connect_timeout * vendordata_dynamic_read_timeout """), cfg.ListOpt('vendordata_dynamic_targets', default=[], help=""" A list of targets for the dynamic vendordata provider. These targets are of the form <name>@<url>. The dynamic vendordata provider collects metadata by contacting external REST services and querying them for information about the instance. This behaviour is documented in the vendordata.rst file in the nova developer reference. """), cfg.StrOpt('vendordata_dynamic_ssl_certfile', default='', help=""" Path to an optional certificate file or CA bundle to verify dynamic vendordata REST services ssl certificates against. Possible values: * An empty string, or a path to a valid certificate file Related options: * vendordata_providers * vendordata_dynamic_targets * vendordata_dynamic_connect_timeout * vendordata_dynamic_read_timeout """), cfg.IntOpt('vendordata_dynamic_connect_timeout', default=5, min=3, help=""" Maximum wait time for an external REST service to connect. Possible values: * Any integer with a value greater than three (the TCP packet retransmission timeout). Note that instance start may be blocked during this wait time, so this value should be kept small. Related options: * vendordata_providers * vendordata_dynamic_targets * vendordata_dynamic_ssl_certfile * vendordata_dynamic_read_timeout """), cfg.IntOpt('vendordata_dynamic_read_timeout', default=5, min=0, help=""" Maximum wait time for an external REST service to return data once connected. Possible values: * Any integer. Note that instance start is blocked during this wait time, so this value should be kept small. Related options: * vendordata_providers * vendordata_dynamic_targets * vendordata_dynamic_ssl_certfile * vendordata_dynamic_connect_timeout """), cfg.IntOpt("metadata_cache_expiration", default=15, min=0, help=""" This option is the time (in seconds) to cache metadata. When set to 0, metadata caching is disabled entirely; this is generally not recommended for performance reasons. Increasing this setting should improve response times of the metadata API when under heavy load. Higher values may increase memory usage, and result in longer times for host metadata changes to take effect. """), ] file_opts = [ cfg.StrOpt("vendordata_jsonfile_path", help=""" Cloud providers may store custom data in vendor data file that will then be available to the instances via the metadata service, and to the rendering of config-drive. The default class for this, JsonFileVendorData, loads this information from a JSON file, whose path is configured by this option. If there is no path set by this option, the class returns an empty dictionary. Possible values: * Any string representing the path to the data file, or an empty string (default). """) ] osapi_opts = [ cfg.IntOpt("osapi_max_limit", default=1000, min=0, help=""" As a query can potentially return many thousands of items, you can limit the maximum number of items in a single response by setting this option. """), cfg.StrOpt("osapi_compute_link_prefix", help=""" This string is prepended to the normal URL that is returned in links to the OpenStack Compute API. If it is empty (the default), the URLs are returned unchanged. Possible values: * Any string, including an empty string (the default). """), cfg.StrOpt("osapi_glance_link_prefix", help=""" This string is prepended to the normal URL that is returned in links to Glance resources. If it is empty (the default), the URLs are returned unchanged. Possible values: * Any string, including an empty string (the default). """), ] allow_instance_snapshots_opts = [ cfg.BoolOpt("allow_instance_snapshots", default=True, help=""" Operators can turn off the ability for a user to take snapshots of their instances by setting this option to False. When disabled, any attempt to take a snapshot will result in a HTTP 400 response ("Bad Request"). """) ] # NOTE(edleafe): I would like to import the value directly from # nova.compute.vm_states, but that creates a circular import. Since this value # is not likely to be changed, I'm copy/pasting it here. BUILDING = "building" # VM only exists in DB osapi_hide_opts = [ cfg.ListOpt("osapi_hide_server_address_states", default=[BUILDING], help=""" This option is a list of all instance states for which network address information should not be returned from the API. Possible values: A list of strings, where each string is a valid VM state, as defined in nova/compute/vm_states.py. As of the Newton release, they are: * "active" * "building" * "paused" * "suspended" * "stopped" * "rescued" * "resized" * "soft-delete" * "deleted" * "error" * "shelved" * "shelved_offloaded" """) ] fping_path_opts = [ cfg.StrOpt("fping_path", default="/usr/sbin/fping", help="The full path to the fping binary.") ] os_network_opts = [ cfg.BoolOpt("enable_network_quota", deprecated_for_removal=True, deprecated_since="14.0.0", deprecated_reason=""" CRUD operations on tenant networks are only available when using nova-network and nova-network is itself deprecated.""", default=False, help=""" This option is used to enable or disable quota checking for tenant networks. Related options: * quota_networks """), cfg.BoolOpt("use_neutron_default_nets", default=False, help=""" When True, the TenantNetworkController will query the Neutron API to get the default networks to use. Related options: * neutron_default_tenant_id """), cfg.StrOpt("neutron_default_tenant_id", default="default", help=""" Tenant ID for getting the default network from Neutron API (also referred in some places as the 'project ID') to use. Related options: * use_neutron_default_nets """), cfg.IntOpt("quota_networks", deprecated_for_removal=True, deprecated_since="14.0.0", deprecated_reason=""" CRUD operations on tenant networks are only available when using nova-network and nova-network is itself deprecated.""", default=3, min=0, help=""" This option controls the number of private networks that can be created per project (or per tenant). Related options: * enable_network_quota """), ] enable_inst_pw_opts = [ cfg.BoolOpt("enable_instance_password", default=True, help=""" Enables returning of the instance password by the relevant server API calls such as create, rebuild, evacuate, or rescue. If the hypervisor does not support password injection, then the password returned will not be correct, so if your hypervisor does not support password injection, set this to False. """) ] ALL_OPTS = (auth_opts + metadata_opts + file_opts + osapi_opts + allow_instance_snapshots_opts + osapi_hide_opts + fping_path_opts + os_network_opts + enable_inst_pw_opts) def register_opts(conf): conf.register_opts(ALL_OPTS) def list_opts(): # TODO(macsz) add opt group return {"DEFAULT": ALL_OPTS}
apache-2.0
Codefans-fan/odoo
addons/survey/__init__.py
385
1037
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-TODAY OpenERP S.A. <http://www.openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import survey import controllers import wizard
agpl-3.0
DirtyUnicorns/android_external_chromium-org
tools/json_schema_compiler/code.py
82
4811
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Code(object): """A convenience object for constructing code. Logically each object should be a block of code. All methods except |Render| and |IsEmpty| return self. """ def __init__(self, indent_size=2, comment_length=80): self._code = [] self._indent_level = 0 self._indent_size = indent_size self._comment_length = comment_length def Append(self, line='', substitute=True, indent_level=None): """Appends a line of code at the current indent level or just a newline if line is not specified. Trailing whitespace is stripped. substitute: indicated whether this line should be affected by code.Substitute(). """ if indent_level is None: indent_level = self._indent_level self._code.append(Line(((' ' * indent_level) + line).rstrip(), substitute=substitute)) return self def IsEmpty(self): """Returns True if the Code object is empty. """ return not bool(self._code) def Concat(self, obj): """Concatenate another Code object onto this one. Trailing whitespace is stripped. Appends the code at the current indent level. Will fail if there are any un-interpolated format specifiers eg %s, %(something)s which helps isolate any strings that haven't been substituted. """ if not isinstance(obj, Code): raise TypeError(type(obj)) assert self is not obj for line in obj._code: try: # line % () will fail if any substitution tokens are left in line if line.substitute: line.value %= () except TypeError: raise TypeError('Unsubstituted value when concatting\n' + line.value) except ValueError: raise ValueError('Stray % character when concatting\n' + line.value) self.Append(line.value, line.substitute) return self def Cblock(self, code): """Concatenates another Code object |code| onto this one followed by a blank line, if |code| is non-empty.""" if not code.IsEmpty(): self.Concat(code).Append() return self def Sblock(self, line=None): """Starts a code block. Appends a line of code and then increases the indent level. """ if line is not None: self.Append(line) self._indent_level += self._indent_size return self def Eblock(self, line=None): """Ends a code block by decreasing and then appending a line (or a blank line if not given). """ # TODO(calamity): Decide if type checking is necessary #if not isinstance(line, basestring): # raise TypeError self._indent_level -= self._indent_size if line is not None: self.Append(line) return self def Comment(self, comment, comment_prefix='// '): """Adds the given string as a comment. Will split the comment if it's too long. Use mainly for variable length comments. Otherwise just use code.Append('// ...') for comments. Unaffected by code.Substitute(). """ max_len = self._comment_length - self._indent_level - len(comment_prefix) while len(comment) >= max_len: line = comment[0:max_len] last_space = line.rfind(' ') if last_space != -1: line = line[0:last_space] comment = comment[last_space + 1:] else: comment = comment[max_len:] self.Append(comment_prefix + line, substitute=False) self.Append(comment_prefix + comment, substitute=False) return self def Substitute(self, d): """Goes through each line and interpolates using the given dict. Raises type error if passed something that isn't a dict Use for long pieces of code using interpolation with the same variables repeatedly. This will reduce code and allow for named placeholders which are more clear. """ if not isinstance(d, dict): raise TypeError('Passed argument is not a dictionary: ' + d) for i, line in enumerate(self._code): if self._code[i].substitute: # Only need to check %s because arg is a dict and python will allow # '%s %(named)s' but just about nothing else if '%s' in self._code[i].value or '%r' in self._code[i].value: raise TypeError('"%s" or "%r" found in substitution. ' 'Named arguments only. Use "%" to escape') self._code[i].value = line.value % d self._code[i].substitute = False return self def Render(self): """Renders Code as a string. """ return '\n'.join([l.value for l in self._code]) class Line(object): """A line of code. """ def __init__(self, value, substitute=True): self.value = value self.substitute = substitute
bsd-3-clause
daviddupont69/CouchPotatoServer
libs/oauthlib/oauth1/rfc5849/utils.py
112
4269
# -*- coding: utf-8 -*- """ oauthlib.utils ~~~~~~~~~~~~~~ This module contains utility methods used by various parts of the OAuth spec. """ import string import time import urllib2 from random import getrandbits, choice from oauthlib.common import quote, unquote UNICODE_ASCII_CHARACTER_SET = (string.ascii_letters.decode('ascii') + string.digits.decode('ascii')) def filter_params(target): """Decorator which filters params to remove non-oauth_* parameters Assumes the decorated method takes a params dict or list of tuples as its first argument. """ def wrapper(params, *args, **kwargs): params = filter_oauth_params(params) return target(params, *args, **kwargs) wrapper.__doc__ = target.__doc__ return wrapper def filter_oauth_params(params): """Removes all non oauth parameters from a dict or a list of params.""" is_oauth = lambda kv: kv[0].startswith(u"oauth_") if isinstance(params, dict): return filter(is_oauth, params.items()) else: return filter(is_oauth, params) def generate_timestamp(): """Get seconds since epoch (UTC). Per `section 3.3`_ of the spec. .. _`section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3 """ return unicode(int(time.time())) def generate_nonce(): """Generate pseudorandom nonce that is unlikely to repeat. Per `section 3.3`_ of the spec. A random 64-bit number is appended to the epoch timestamp for both randomness and to decrease the likelihood of collisions. .. _`section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3 """ return unicode(getrandbits(64)) + generate_timestamp() def generate_token(length=20, chars=UNICODE_ASCII_CHARACTER_SET): """Generates a generic OAuth token According to `section 2`_ of the spec, the method of token construction is undefined. This implementation is simply a random selection of `length` choices from `chars`. Credit to Ignacio Vazquez-Abrams for his excellent `Stackoverflow answer`_ .. _`Stackoverflow answer` : http://stackoverflow.com/questions/2257441/ python-random-string-generation-with-upper-case-letters-and-digits """ return u''.join(choice(chars) for x in range(length)) def escape(u): """Escape a unicode string in an OAuth-compatible fashion. Per `section 3.6`_ of the spec. .. _`section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6 """ if not isinstance(u, unicode): raise ValueError('Only unicode objects are escapable.') # Letters, digits, and the characters '_.-' are already treated as safe # by urllib.quote(). We need to add '~' to fully support rfc5849. return quote(u, safe='~') def unescape(u): if not isinstance(u, unicode): raise ValueError('Only unicode objects are unescapable.') return unquote(u) def urlencode(query): """Encode a sequence of two-element tuples or dictionary into a URL query string. Operates using an OAuth-safe escape() method, in contrast to urllib.urlencode. """ # Convert dictionaries to list of tuples if isinstance(query, dict): query = query.items() return u"&".join([u'='.join([escape(k), escape(v)]) for k, v in query]) def parse_keqv_list(l): """A unicode-safe version of urllib2.parse_keqv_list""" encoded_list = [u.encode('utf-8') for u in l] encoded_parsed = urllib2.parse_keqv_list(encoded_list) return dict((k.decode('utf-8'), v.decode('utf-8')) for k,v in encoded_parsed.items()) def parse_http_list(u): """A unicode-safe version of urllib2.parse_http_list""" encoded_str = u.encode('utf-8') encoded_list = urllib2.parse_http_list(encoded_str) return [s.decode('utf-8') for s in encoded_list] def parse_authorization_header(authorization_header): """Parse an OAuth authorization header into a list of 2-tuples""" auth_scheme = u'OAuth ' if authorization_header.startswith(auth_scheme): authorization_header = authorization_header.replace(auth_scheme, u'', 1) items = parse_http_list(authorization_header) try: return parse_keqv_list(items).items() except ValueError: raise ValueError('Malformed authorization header')
gpl-3.0
bottompawn/kbengine
kbe/res/scripts/common/Lib/lib2to3/pygram.py
170
1114
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Export the Python grammar and symbols.""" # Python imports import os # Local imports from .pgen2 import token from .pgen2 import driver from . import pytree # The grammar file _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "PatternGrammar.txt") class Symbols(object): def __init__(self, grammar): """Initializer. Creates an attribute for each grammar symbol (nonterminal), whose value is the symbol's type (an int >= 256). """ for name, symbol in grammar.symbol2number.items(): setattr(self, name, symbol) python_grammar = driver.load_grammar(_GRAMMAR_FILE) python_symbols = Symbols(python_grammar) python_grammar_no_print_statement = python_grammar.copy() del python_grammar_no_print_statement.keywords["print"] pattern_grammar = driver.load_grammar(_PATTERN_GRAMMAR_FILE) pattern_symbols = Symbols(pattern_grammar)
lgpl-3.0
timothyjamesbecker/FusorSV
bin/FusorSV.py
1
37134
#!/usr/bin/env python import argparse import glob import gc import os import time import multiprocessing as mp #pip installed libs import numpy as np #local libs import fusorsv.svu_utils as su import fusorsv.read_utils as ru import fusorsv.fusor_utils as fusor des = """ FusorSV - A Data Fusion Method for Multi Source (VCF4.0+) Structural Variation Analysis Timothy James Becker, PhD candidate, UCONN 05/25/2016-06/19/2018\n version="""+fusor.fu.__version__ parser = argparse.ArgumentParser(description=des,formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('-r', '--ref_path',type=str, help='reference fasta needed to write vcf or g1k output files\t[None]') des = """ input directory with sample named folders and caller id tagged vcf files [EX] /path/sample/sample_S4.vcf implies that there are calls of id 4 for sample\t[None]""" parser.add_argument('-i', '--in_dir',type=str, help=des) parser.add_argument('-a', '--ctg_dir',type=str,help='assembly contig directory\t[None]') parser.add_argument('-c', '--chroms',type=str,help='comma seperated chrom listing\t[1,2,...22,X,Y,MT]') parser.add_argument('-o', '--out_dir',type=str, help='outputdirectory to save ...bam.bai/ into\t[None]') parser.add_argument('-m', '--sv_mask',type=str,help='user supplied svmask file in BED3 or internal json format\t[None]') parser.add_argument('-f', '--apply_fusion_model_path',type=str, help='apply a fusion model *.pickle.gz') parser.add_argument('-p', '--cpus',type=int,help='number of cores to use in ||\t[1]') parser.add_argument('--k_fold',type=int,help='k_fold cross validation, k=0 implies no validation\t[0]') parser.add_argument('--n_k',type=int,help='number of times to do k_fold\t[1]') parser.add_argument('--bins',type=int,help='number of requested discriminating features\t[14]') parser.add_argument('--obs',type=int,help='number of observations needed per bin\t[1000]') parser.add_argument('--min_g',type=float,help='minimum group expectation contribution\t[0.0]') parser.add_argument('--over_m',type=float,help='overlap allowed before removal in merge step\t[0.0]') parser.add_argument('--pre_cluster',action='store_true', help='cluster the calls for all samples first\t[False]') parser.add_argument('--smoothing',action='store_true', help='brkpt_smoothing algo\t[False]') parser.add_argument('--detail',action='store_true',help='provide a more detailed output\t[False]') stage_mapping = """ 1:1 mapping of caller ids to stage names (and back): stage_map_json_file -> {0:'True',-1:'fusorSV',1:'MetaSV',4:'BreakDancer',9:'cnMOPS',10:'CNVnator', 11:'Delly',13:'GATK',14:'GenomeSTRiP',17:'Hydra',18:'Lumpy',35:'BreakSeq', 36:'Pindel',38:'Tigra'}\t[../data/stage_map.json] """ parser.add_argument('-S', '--stage_map_json_file',type=str,help=stage_mapping) parser.add_argument('-E', '--stage_exclude_list',type=str,help='comma seperated id list to exclude from test/training\t[1,13,36]') parser.add_argument('-F', '--sample_folder_exclude',type=str,help='comma seperated folder names to exclude\t[None]') parser.add_argument('-M', '--cluster_overlap',type=float,help='reciprocal overlap needed for clustering\t[0.5]') parser.add_argument('-L', '--lift_over',type=str,help='liftover chain file path or default\t[./data/hg19ToHg38.over.chain.gz]') parser.add_argument('-C', '--clean', action='store_true',help='keep all kfold run data and print extra details\t[False]') parser.add_argument('-T', '--test_libs', action='store_true', help='test the installation libraries and print version\t[False]') parser.add_argument('--no_merge',action='store_true',help='set to not merge output for large sample applications\t[False]') parser.add_argument('--merge',action='store_true',help='perform a merge and exit for large sample applications\t[False]') args = parser.parse_args() if args.test_libs: #library tester should load all imports here import fusion_utils as fu x1,x2 = [[0,100,0,[],0,0,{}]],[[51,151,0,[],0,0,{}]] F = fu.LR_no_idx(x1,x2) T = [49,151,50,50] if all([T[i]==(F[i][0][1]-F[i][0][0]) for i in range(len(T))]): print('fusion_utils.so and bindings are functional!\nversion='+fu.__version__) else: print('error with library imports, check your installation') quit(0) if args.in_dir is not None: in_dir = args.in_dir if not os.path.exists(in_dir): print('VCF input path does not exist!') raise IOError elif args.merge: print('final FusorSV VCF merge starting') else: print('no VCF input') raise IOError if args.out_dir is not None: out_dir = args.out_dir else: print('no output directory specified') raise IOError if args.apply_fusion_model_path is not None: if args.apply_fusion_model_path.upper()=='DEFAULT': apply_fusion_model_path =ru.get_local_path('models/human_g1k_v37_decoy.P3.pickle.gz') else: apply_fusion_model_path = args.apply_fusion_model_path if not os.path.exists(apply_fusion_model_path): print('fusion model path does not exist!') raise IOError else: apply_fusion_model_path = None #implies you will make one with true input if args.ctg_dir is not None: ctg_dir = args.ctg_dir else: print('no contig directory specified') ctg_dir = None if args.ref_path is not None: ref_path = args.ref_path else: ref_path = '' print('ref_path not provided, will not be able to write a vcf and g1k file') write_stats = True #new default write_vcf_g1k = True #new default write_model = True #new default if args.k_fold is not None: cross_fold = args.k_fold else: cross_fold = 1 if args.n_k is not None and cross_fold > 1: n_cross = args.n_k else: n_cross = 1 if args.cpus is not None: cpus = args.cpus else: cpus = 1 if args.bins is not None: beta = args.bins else: beta = 16 if args.obs is not None: obs = args.obs else: obs = 1000 if args.min_g is not None: min_g = args.min_g else: min_g = 0.0 if args.over_m is not None: over_m = args.over_m else: over_m = 1E-10 #1bp overlap in a human genome = 3E-9 if args.chroms is not None: chroms = args.chroms.split(',') else: chroms = [str(i) for i in range(1,23)]+['X','Y','MT'] #limit to chroms of interest if args.cluster_overlap is not None: cluster_overlap = args.cluster_overlap else: cluster_overlap = 0.0 if args.lift_over is not None: if args.lift_over.upper()=='DEFAULT': #need to do -L default to get default lift_over = ru.get_local_path('liftover/hg19ToHg38.over.chain.gz') #default else: lift_over = args.lift_over #lift over file for downstream analysis else: lift_over = None #load a user defined stage mapping id or use the one provided if args.stage_map_json_file is not None: callers= ru.get_stage_map(args.stage_map_json_file) #user can supply a seperate stage map if callers == {}: #-1 is reserved for FusorSV and 0 for true callers = ru.get_stage_map(ru.get_local_path('stage_map.json')) else: callers = ru.get_stage_map(ru.get_local_path('stage_map.json')) stage_exclude_list = [1,13,36] #default exclude list if args.stage_exclude_list is not None: try: stage_exclude_list = [int(i) for i in args.stage_exclude_list.rsplit(',')] print('using stage id exclude list:%s'%stage_exclude_list) except Exception as E: print('error parsing comma seperated list, using defaults') print('defaults stage exclude list is: %s'%stage_exclude_list) #seperate merging out batched FusorSV call VCFs vcf_glob = out_dir+'/vcf/*_S-1.vcf' #fusorSV VCFS only if args.merge: tst_str = 'FULL' ref_seq = {'.'.join(ref_path.rsplit('/')[-1].rsplit('.')[0:-1]):ru.read_fasta(ref_path)} print('cluster merging tool processing samples') out_vcf = out_dir+'/vcf/all_samples_genotypes.'+tst_str+'.vcf' print('completed = %s'%su.fusorSV_vcf_multi_sample_merge(vcf_glob,out_vcf, ref_seq[ref_seq.keys()[0]], overlap=cluster_overlap)) if lift_over is not None: #now do a liftover to partition the calls with a possible new reference space su.fusorSV_vcf_liftover_samples(out_dir+'/vcf/all_samples_genotypes*.vcf*',ref_path,lift_over) #default is on n_stop = time.time() print(''.join([':::' for i in range(40)])) exit(0) # -r -i -o -M 0.5 -L --merge def get_observations(in_dir): #will look for .tar.gz file or glob the uncompressed folder #this require refactoring out HTSeq for tar archive to gzip support obs = [] return obs result_list = [] #async queue to put results for || stages def collect_results(result): result_list.append(result) #[1] File Partitioning------------------------------------------------------------------ #read and convert to SVULTB all SV caller VCF inputs #saving each partition to a seperate pickle file || by sample << partition def partition_call_sets(sample,k,O,R,B,chroms,flt,flt_exclude,caller_exclude): sname = sample[sample.rfind('/')+1:] #extract sample identifier print('reading sample %s'%sname) sname_partition_path = out_dir+'/svul/'+sname #build path S,V = su.vcf_glob_to_svultd(sample+'/*vcf',chroms,O,types=B.keys(), vcf_flt=flt,flt_exclude=flt_exclude, caller_exclude=caller_exclude) S = su.filter_call_sets2(S,R,exclude=flt_exclude) #filter svmasks Q = fusor.slice_samples([[sname,S]]) #legacy P = fusor.partition_sliced_samples(Q,B,exclude=caller_exclude) #partition success = fusor.write_partitions_by_sample(sname_partition_path,P) #write to disk return [sname,success] #report back to async queue #[1] File Partitioning------------------------------------------------------------------ #[2] Pool Partitions-------------------------------------------------------------------- #this is || by partition: t, b def merge_partitions(callers,t,b): partition_path = out_dir+'/svul/' P = fusor.read_partitions_by_caller(partition_path,callers,t,b,False) return [sname,P] #[2] Pool Partitions-------------------------------------------------------------------- #[3a] Fit the Model Partition---------------------------------------------------------------------------- def prior_model_partition(snames,t,b,k,callers,caller_exclude,min_g,brkpt_smoothing): print('starting model partition:\tt=%s\tb=%s'%(t,b)) start = time.time() P = fusor.read_partitions_by_caller(out_dir+'/svul/',callers,caller_exclude,t,b,False) #P,snames = fusor.pre_cluster_samples(P,r=0.9),['CLUSTER'] #optional preclustering T = fusor.target_by_sample(P,k) #extract the partitioned target J = fusor.all_samples_all_pairs_magnitudes(P,snames) #pool all feature magnitudes K = fusor.all_samples_all_callers_bkpts(P,snames) #pool all breakpoints D,NN = fusor.pooled_distance(J) #this is done inside the all_group_weights as well W = fusor.all_group_weights(J,k,mode='j') #pooled D,NN and all group weights E = fusor.select_groups(W,min_g) #gamma is a group selection cutoff A = fusor.pileup_group_by_sample(P,E,(k,)) #now its just one partition here if brkpt_smoothing: print('optimizing model partition with brkpt smoothing:\tt=%s\tb=%s'%(t,b)) alpha = fusor.target_filter_cutoff_exhaustive_brkpt(A,P,T,E,K) stop = time.time() print('fusion model partition:\tt=%s\tb=%s\t%s sec\tcappa=%s'%(t,b,round(stop-start,2),alpha[t][b])) else: print('optimizing model partition:\tt=%s\tb=%s'%(t,b)) alpha = fusor.target_filter_cutoff_exhaustive(A,E,T) #optimal cutoff location stop = time.time() print('fusion model partition:\tt=%s\tb=%s\t%s sec\talpha=%s'%(t,b,round(stop-start,2),alpha[t][b])) return [(t,b),J,D,E,alpha,K] #[3a] Fit the Model Partition---------------------------------------------------------------------------- #[3b] Posterior Estimation Partition--------------------------------------------------------------------- def post_model_partition(apply_fusion_model_path,snames,t,b,k,callers,caller_exclude,min_g,smoothing): start = time.time() #[1] load prior model values---------------------------------------- B,J,D,E,alpha,n,K = fusor.import_fusion_model(apply_fusion_model_path) #import the existing model if smoothing: print('starting posterior estimate on partition:\tt=%s\tb=%s'%(t,b)) #[2] load new input data partitions P = fusor.read_partitions_by_caller(out_dir+'/svul/',callers,caller_exclude,t,b,False) #all samples J_new = fusor.all_samples_all_pairs_magnitudes(P,snames) #pool all feature magnitudes #[3] construct the posterior estimator using: the prior data, new data and imputed true row==k J_post = fusor.additive_magnitude_smoothing(J,J_new,k) #k is used to swap a row J_prime into J D_post,NN_post = fusor.pooled_distance(J_post) #get the new data distance matrix W_post = fusor.all_group_weights(J_post,k,mode='j') #calculate the pooled D,NN and all group weights E_post = fusor.select_groups(W_post,min_g) #gamma is a group selection cutoff alpha_post = fusor.post_filter_cutoff(E,E_post,alpha) #updated filter estimates stop = time.time() print('posterior estimate on partition:\tt=%s\tb=%s\t%s sec\talpha=%s'%(t,b,round(stop-start,2), alpha_post[t][b])) else: print('using prior estimate on partition:\tt=%s\tb=%s'%(t,b)) J_post = {t:{b:J[t][b]}} D_post = {t:{b:D[t][b]}} E_post = {t:{b:E[t][b]}} alpha_post = {t:{b:alpha[t][b]}} K[t] = {t:{b:K[t][b]}} stop = time.time() print('prior estimate on partition:\tt=%s\tb=%s\t%s sec\talpha=%s' % (t,b,round(stop-start,2), alpha_post[t][b])) return [(t,b),J_post,D_post,E_post,alpha_post,K] #[3b] Posterior Estimation Partition-------------------------------------------------------------------- #[4] Apply Model To Samples--------------------------------------------------------------------------------- #supports both single model training and posterior estimate via additive smoothing and diagnostics: mantel def apply_model_to_samples(sample,ref_path,chroms,types,bins,callers,O, model_path,apply_fusion_model_path,k,f_id, over_m,r=0.5,smoothing=False,detail=False,verbose=False,IDX=6): sname = sample[sample.rfind('/')+1:] #extract sample identifier print('starting fusorSV discovery on sample %s'%sname) ref_seq = {'.'.join(ref_path.rsplit('/')[-1].rsplit('.')[0:-1]):ru.read_fasta(ref_path)} #~3GB hist,C = {},{} cross_fold_stats,detailed_stats = {c:{} for c in callers},{} #each single caller for t in types: for c in cross_fold_stats: if not t in cross_fold_stats[c]: cross_fold_stats[c][t] = [] B,J,J_post,D,D_post,alpha,alpha_post,K,n,n_post = {},{},{},{},{},{},{},{},0,0 #[1] apply the model here------------------------------------------------------------------------------ if apply_fusion_model_path is None:#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if verbose: print('loading base fusion model partitions for %s'%sname) B,J,D,E,alpha,n,K = fusor.import_fusion_model(model_path) #import the base model P = fusor.read_partitions_by_sample(partition_path,sname) #read all partitions for sname Q = fusor.unpartition_sliced_samples(P) #unpartition for merging later if verbose: print('projection of all call sets on %s'%sname) A = fusor.pileup_group_by_sample(P,E,(k,)) #projection of all calls for a sample F = fusor.filter_pileup_by_sample(A,alpha,leave_in=False) #filter using optimal cutof in the mode if smoothing: #now do breakpoint smoothing algorithm--------------------------------------------------------- F = fusor.best_smooth_brkpt_samples(F,K,P) #now do breakpoint smoothing algorithm--------------------------------------------------------- fusor.merge_filtered_samples(Q,F,f_id,snames,[],over_m) else:#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if verbose: print('loading base and posterior estimate partitions for %s'%sname) B,J,D,E,alpha,n,K = fusor.import_fusion_model(apply_fusion_model_path) #import prior model if smoothing: B,J_post,D_post,E_post,alpha_post,n_post,K = fusor.import_fusion_model(model_path) #import new data P = fusor.read_partitions_by_sample(partition_path,sname) #read all partitions for sname Q = fusor.unpartition_sliced_samples(P) #unpartition for merging later A = fusor.pileup_group_by_sample(P,E,(k,)) #projection of all calls for a sample if smoothing: F = fusor.filter_pileup_by_sample(A,alpha,E_post,leave_in=False) # filter cutoff in the mode else: F = fusor.filter_pileup_by_sample(A,alpha,E,leave_in=False) # filter cutoff in the mode if smoothing: #now do breakpoint smoothing algorithm--------------------------------------------------------- F = fusor.best_smooth_brkpt_samples(F,K,P) #now do breakpoint smoothing algorithm--------------------------------------------------------- fusor.merge_filtered_samples(Q,F,f_id,snames,[],over_m) #expectation priorty merge back result #[2] do some scoring and write out the sample results, returning for global performance---------------- start = time.time() for t in Q: #give the metrics for each sample and write out the result for c in set(cross_fold_stats).difference(set([f_id,k])): if verbose: print('%s%s'%(callers[c],''.join(['-' for i in range(80)]))) #other callers first cross_fold_stats[c][t] += [fusor.pretty_stats(Q,types,t,k,c,sname,r,verbose,smoothing)] if verbose: print('fusorSV%s'%(''.join(['-' for i in range(80)]))) #then fusorSV cross_fold_stats[f_id][t] += [fusor.pretty_stats(Q,types,t,k,f_id,sname,r,verbose,smoothing)] C[t] = [] if Q[t].has_key(f_id) and Q[t][f_id].has_key(sname): C[t] = Q[t][f_id][sname] for i in cross_fold_stats[f_id][t][-1][6]: C[t][i][IDX][k] = [-1] #flag the idx with the target key and -1 if verbose: print('writing VCF for %s'%sname) G = su.svult_to_genome(C,O) #start conversion back to VCF hist[sname] = su.genome_to_vcf(G,ref_seq,types,chroms,callers, out_dir+'/vcf/'+sname+'_S'+str(f_id)+'.vcf',sname,target_key=k) #VCF if detail: for c in callers: detailed_stats[c] = {} for t in types: detailed_stats[c][t] = {} for i in range(len(B[t])-1): detailed_stats[c][t][bins[t][i]] = [] for t in Q: for c in set(detailed_stats.keys()).difference(set([f_id,k])): #do the other callers if verbose: print('%s%s'%(callers[c],''.join(['-' for x in range(80)]))) T = fusor.pretty_bin_stats(Q,types,t,B,bins,k,c,sname,r,verbose,smoothing) for i in range(len(B[t])-1): detailed_stats[c][t][bins[t][i]] = [T[bins[t][i]]] if verbose: print('fusorSV%s'%(''.join(['-' for i in range(80)]))) T = fusor.pretty_bin_stats(Q,types,t,B,bins,k,f_id,sname,r,verbose,smoothing) #no fusorSV for i in range(len(B[t])-1): detailed_stats[f_id][t][bins[t][i]] = [T[bins[t][i]]] stop = time.time() if verbose: print('scoring completed for %s in %s sec'%(sname,round(stop-start,2))) return [sname,cross_fold_stats,hist,detailed_stats] #[4] Apply Model To Samples-------------------------------------------------------------------------------- if __name__ == '__main__': full_start = time.time() if not os.path.exists(out_dir): os.makedirs(out_dir) if not os.path.exists(out_dir+'/tigra_ctg_map/'): os.makedirs(out_dir+'/tigra_ctg_map/') if not os.path.exists(out_dir+'/g1k/'): os.makedirs(out_dir+'/g1k/') if not os.path.exists(out_dir+'/vcf/'): os.makedirs(out_dir+'/vcf/') if not os.path.exists(out_dir+'/svul/'): os.makedirs(out_dir+'/svul/') if not os.path.exists(out_dir+'/models/'): os.makedirs(out_dir+'/models/') if not os.path.exists(out_dir+'/meta/'): os.makedirs(out_dir+'/meta/') if not os.path.exists(out_dir+'/visual/'): os.makedirs(out_dir+'/visual/') if not os.path.exists(out_dir+'/visual/bed/'): os.makedirs(out_dir+'/visual/bed/') files = glob.glob(in_dir+'*') #get all sample directories #entry here for correcting files from a .tar.gz samples,snames = [],[] for i in files: sname = i.rsplit('/')[-1] samples += [i] snames += [i.rsplit('/')[-1]] #snames,samples = snames[0:2],samples[0:2] #testing line print('processing samples %s\n for chroms %s'%(samples,chroms)) coordinate_offset_json = ref_path.rsplit('/')[-1].rsplit('.fa')[0]+'_coordinates.json' if not os.path.isfile(out_dir+'/meta/'+coordinate_offset_json): print('making a new coordinate offset json file') ru.write_coordinate_offsets(ref_path,out_dir+'/meta/'+coordinate_offset_json) O = ru.get_coordinate_offsets(out_dir+'/meta/'+coordinate_offset_json) #must have a valid offset map R = [] #human callers work better with svmask if args.sv_mask is not None: #None if no mask desired if args.sv_mask.endswith('.bed'): sv_mask_json = args.sv_mask.rsplit('/')[-1].rsplit('.bed')[0]+'_svmask.json' if not os.path.exists(out_dir+'/meta/'+sv_mask_json): ru.bed_mask_to_json_mask(args.sv_mask,out_dir+'/meta/'+sv_mask_json) elif args.sv_mask.endswith('.json'): ru.copy_json_mask(args.sv_mask,out_dir+'/meta/'+args.sv_mask.rsplit('/')[-1]) #mask these regions------------------------------------------------------------------------------------ R += ru.get_mask_regions(out_dir+'/meta/'+sv_mask_json,O) #svmask from ref complexity print('merging the svmask regions') start = time.time() R = ru.flatten_mask_regions(R,O,complement=False) #single IRanges stop = time.time() print('svmask regions merged in %s sec'%(round(stop-start,2))) #mask these regions------------------------------------------------------------------------------------ k,flt,f_id,m_id = 0,0,-1,1 #k=true_id,flt=filter 0 is .,PASS,f_id=fusorSV_id,m_id=metaSV_id exclude_callers = stage_exclude_list #exclude caller options put any id here to exclude B = {t:[1,100,250,500,1000,5000,10000,50000,100000,1000000] for t in range(0,8)} # B = fusor.distribute_bins(Q,k,n_b=beta,m_b=obs,lower=None,upper=None,event=False) #equal power distribution B[1] = [1,50,100,1000,1000000] B[2] = [1,50,100,400,600,950,1250,1550,1950,2250,2950,3650,4800,6150,9000,18500,100000,1000000] #B[2] = [1,50,100,400,600,950,1250,1550,1950,2250,2950,3650,4800,6150,9000,18500,100000,10000000] B[3] = [1,50,1000,10000,50000,100000,250000,500000,1000000] #B[3] = [1,50,500,1000,5000,10000,50000,250000,10000000] B[5] = [1,50,2500,3500,45000,80000,115000,180000,260000,300000,375000,500000] #B[5] = [1,50,100,250,500,1000,2500,3500,45000,80000,115000,180000,260000,300000,500000,1000000] types = {0:'SUB',1:'INS',2:'DEL',3:'DUP',4:'CNV',5:'INV',6:'TRA',7:'BND'} bins = {t:su.pretty_ranges(B[t],'') for t in B} partition_path = out_dir+'/svul/' total_partitions = len(glob.glob(partition_path+'*.pickle.gz')) #entry for testing------------------------------------- # c = fusor.check_sample_full(samples,-2,-3,O,R,chroms,types=[2,3,5],flt=0,r=0.9,self_merge=True) #entry for testing------------------------------------ #||||||||||||||||||||||||||||||||||||||BY SAMPLE||||||||||||||||||||||||||||||||||||||||||||| #[1] read, parse, structure, select, partition and write out data for each sample if not done snames_svuls = {} written_svuls = glob.glob(partition_path+'*.pickle.gz') for svul in written_svuls: sname = svul.rsplit('/')[-1].rsplit('_')[0] if snames_svuls.has_key(sname): snames_svuls[sname] += 1 else: snames_svuls[sname] = 1 if total_partitions<1 or len(set(snames).difference(set(snames_svuls.keys())))>1: print('reading, parsing, partitioning and writing sample VCFs') start = time.time() p1 = mp.Pool(processes=cpus) for sample in samples: p1.apply_async(partition_call_sets, args=(sample,k,O,R,B,chroms,flt,[],exclude_callers), callback=collect_results) time.sleep(0.25) p1.close() p1.join() L = [] for i in result_list: if i is not None: L+=[i] result_list = [] gc.collect() snames = [i[0] for i in L] #passing list of sample names #only have to read in the samples once stop = time.time() total_partitions = len(glob.glob(partition_path+'*.pickle.gz')) print('finished reading %s out of %s samples generating %s partitions in %s sec'%\ (len(snames),len(samples),total_partitions,round(stop-start,2))) #||||||||||||||||||||||||||||||||||||||BY SAMPLE||||||||||||||||||||||||||||||||||||||||||||| if n_cross>1 and cross_fold>1: #for each run will permute using the k_fold divisor to partition print('employing crossfold validation measures...runs=%s\tkfold=%s'%(n_cross,cross_fold)) for n_k in range(n_cross): #default is 1 and cross_fold = 0 n_start = time.time() tst_ids = [] if cross_fold>1: tst_ids = sorted(list(np.random.choice(range(len(samples)),len(samples)/cross_fold,replace=False))) trn_ids = sorted(list(set(range(len(samples))).difference(set(tst_ids)))) tst_str = ''.join([hex(i)[2:].upper() for i in tst_ids]) #get a id sorted hex string of the ids used trn_str = ''.join([hex(i)[2:].upper() for i in trn_ids]) #get a id sorted hex string of the ids used if len(tst_str)>10: tst_str = str(hash(tst_str)) if len(trn_str)>10: trn_str = str(hash(trn_str)) #||||||||||||||||||||||||||||||||||||||BY PARTITION|||||||||||||||||||||||||||||||||||||||||| #[2]train or apply the model #load the data and build a model if one isn't already available in || if apply_fusion_model_path is None: #train a new model assuming k_fold=0 here model_path = out_dir+'/models/'+'.'.join(ref_path.rsplit('/')[-1].rsplit('.')[0:-1])+\ '.'+in_dir[0:-1].rsplit('/')[-1]+trn_str+'.pickle.gz' if not os.path.exists(model_path): #write a model if it hasn't been done yet start = time.time() #now in || for faster performance and less RAM p1 = mp.Pool(processes=cpus) for t in types: for b in range(len(B[t])-1): p1.apply_async(prior_model_partition, args=([snames[i] for i in trn_ids],t,b,k, callers,exclude_callers,min_g,False), callback=collect_results) time.sleep(0.5) p1.close() p1.join() L = [] for i in result_list: if i is not None: L+=[i] result_list = [] gc.collect() stop = time.time() print('finished modeling in %s sec'%round(stop-start,2)) J,D,E,alpha,n,K = fusor.assemble_model(L) fusor.export_fusion_model(B,J,D,E,alpha,len(snames),K,model_path) L = [] gc.collect() else: #can clip this one the || sample application is completed B,J,D,E,alpha,n,K = fusor.import_fusion_model(model_path) else: #apply an existing model and then use additive smoothing with the all new input data B,J,D,E,alpha,n,K = fusor.import_fusion_model(apply_fusion_model_path) model_path = out_dir+'/models/'+'.'.join(ref_path.rsplit('/')[-1].rsplit('.')[0:-1])+\ '.'+in_dir[0:-1].rsplit('/')[-1]+trn_str+'.post.pickle.gz' #now look at the new data and make a model for it, minus the true (estimate it) if not os.path.exists(model_path) and args.smoothing: #write a model if it hasn't been done yet start = time.time() #now in || for faster performance and less RAM p1 = mp.Pool(processes=cpus) for t in types: for b in range(len(B[t])-1): p1.apply_async(post_model_partition, args=(apply_fusion_model_path,snames,t,b,k, callers,exclude_callers,min_g, args.smoothing), callback=collect_results) time.sleep(0.5) p1.close() p1.join() L = [] for i in result_list: if i is not None: L+=[i] result_list = [] gc.collect() stop = time.time() print('finished estimation in %s sec'%round(stop-start,2)) J_post,D_post,E_post,alpha_post,n_post,K = fusor.assemble_model(L,args.smoothing) fusor.export_fusion_model(B,J_post,D_post,E_post,alpha_post,len(snames),K,model_path) L = [] gc.collect() else: #can clip this one the || sample application is completed B,J_post,D_post,E_post,alpha_post,n_post,K = fusor.import_fusion_model(apply_fusion_model_path) #||||||||||||||||||||||||||||||||||||||BY PARTITION|||||||||||||||||||||||||||||||||||||||||| #||||||||||||||||||||||||||||||||||||||BY SAMPLE||||||||||||||||||||||||||||||||||||||||||||| print('apply fusion model to sample inputs and generating fusorSV ouput') if n_cross>1 and cross_fold>1: print('scoring the crossfold run %s out of...runs=%s\tkfold=%s'%(n_k,n_cross,cross_fold)) else: tst_ids,tst_str = trn_ids,trn_str start = time.time() p1 = mp.Pool(processes=max(1,cpus/2)) for sample in [samples[i] for i in tst_ids]: p1.apply_async(apply_model_to_samples, args=(sample,ref_path,chroms,types,bins,callers,O, model_path,apply_fusion_model_path,k,f_id, over_m,0.5,args.smoothing,args.detail,args.detail,6), callback=collect_results) time.sleep(0.5) p1.close() p1.join() L = [] for i in result_list: if i is not None: L+=[i] result_list = [] gc.collect() #only have to read in the samples once stop = time.time() print('finished reading samples in %s sec'%round(stop-start,2)) #||||||||||||||||||||||||||||||||||||||BY SAMPLE||||||||||||||||||||||||||||||||||||||||||||| cross_fold_stats,hist,detailed_stats = fusor.assemble_stats(L) ref_seq = {'.'.join(ref_path.rsplit('/')[-1].rsplit('.')[0:-1]):ru.read_fasta(ref_path)} #compute cross_fold averages if apply_fusion_model_path is None: for c in cross_fold_stats: print('%s--------------------------------------------------------------'%callers[c]) for t in cross_fold_stats[c]: if len(cross_fold_stats[c][t])>0:#have all samples here to plot/look at! #idea[1] look at scatterplot with a line prec = round(np.mean([i[2] for i in cross_fold_stats[c][t]]),2) rec = round(np.mean([i[3] for i in cross_fold_stats[c][t]]),2) f1 = round(np.mean([i[4] for i in cross_fold_stats[c][t]]),2) j = round(np.mean([i[5] for i in cross_fold_stats[c][t]]),2) n = round(np.mean([i[7] for i in cross_fold_stats[c][t]]),2) m = round(np.mean([i[8] for i in cross_fold_stats[c][t]]),2) l_mu = round(np.mean([i[9] for i in cross_fold_stats[c][t]]),2) r_mu = round(np.mean([i[10] for i in cross_fold_stats[c][t]]),2) print('average for t=%s\tprec=%s\trec=%s\tf1=%s\tj=%s\tn=%s\tm=%s\tl_mu=%s\tr_mu=%s'%\ (types[t],prec,rec,f1,j,n,m,l_mu,r_mu)) #CHECK-SCORES----------------------------------------------------------------------------------------------- fusor.export_caller_performance(cross_fold_stats,callers, out_dir+'/visual/cross_fold_stats.'+tst_str+'.tsv') fusor.export_detailed_performance(detailed_stats,callers, out_dir+'/visual/detailed_stats.'+tst_str+'.tsv') fusor.export_caller_by_type_and_bin(E,alpha,callers,types,bins, out_dir+'/visual/callers_tbj.'+tst_str+'.tsv') fusor.export_distance_matrix(D,callers,types,bins, out_dir+'/visual/sim_matrix.'+tst_str+'.tsv',sim=True) #(a) check for an Rscript engine #(b) use the command parser to fire up the Rscript and check #(c) for the drawing libraries to ggplot, ect to use #------------------------------------------------------------------- vcf_glob = out_dir+'/vcf/*_S-1.vcf' #fusorSV VCFS only if not args.no_merge: if cluster_overlap > 0.0: print('cluster merging tool processing samples') out_vcf = out_dir+'/vcf/all_samples_genotypes.'+tst_str+'.vcf' print('completed = %s'%su.fusorSV_vcf_multi_sample_merge(vcf_glob,out_vcf, ref_seq[ref_seq.keys()[0]], overlap=cluster_overlap)) if lift_over is not None: #now do a liftover to partition the calls with a possible new reference space su.fusorSV_vcf_liftover_samples(out_dir+'/vcf/all_samples_genotypes*.vcf*',ref_path,lift_over) #default is on if n_cross>1 and cross_fold>1 and not args.clean: #can clean up the VCF and model files... print('cleaning interim data for run %s out of...runs=%s\tkfold=%s'%(n_k, n_cross,cross_fold)) os.remove(model_path) for vcf in glob.glob(vcf_glob): os.remove(vcf) n_stop = time.time() print('run %s in %s sec'%(n_k,round(n_stop-n_start,2))) print(''.join([':::' for i in range(40)]))
gpl-3.0
chromium/chromium
third_party/blink/tools/blinkpy/common/net/file_uploader.py
6
4675
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import mimetypes import six.moves.urllib from blinkpy.common.net.network_transaction import NetworkTransaction def get_mime_type(filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream' # FIXME: Rather than taking tuples, this function should take more structured data. def _encode_multipart_form_data(fields, files): """Encode form fields for multipart/form-data. Args: fields: A sequence of (name, value) elements for regular form fields. files: A sequence of (name, filename, value) elements for data to be uploaded as files. Returns: (content_type, body) ready for httplib.HTTP instance. Source: https://github.com/rietveld-codereview/rietveld/blob/1be266f92fbd6e01732e1bde10589bc408d65633/upload.py#L964 """ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' lines = [] for key, value in fields: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"' % key) lines.append('') if isinstance(value, unicode): value = value.encode('utf-8') lines.append(value) for key, filename, value in files: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) lines.append('Content-Type: %s' % get_mime_type(filename)) lines.append('') if isinstance(value, unicode): value = value.encode('utf-8') lines.append(value) lines.append('--' + BOUNDARY + '--') lines.append('') body = CRLF.join(lines) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body class FileUploader(object): def __init__(self, url, timeout_seconds): self._url = url self._timeout_seconds = timeout_seconds def upload_single_text_file(self, filesystem, content_type, filename): return self._upload_data(content_type, filesystem.read_text_file(filename)) def upload_as_multipart_form_data(self, filesystem, files, attrs): file_objs = [] for filename, path in files: file_objs.append(('file', filename, filesystem.read_binary_file(path))) # FIXME: We should use the same variable names for the formal and actual parameters. content_type, data = _encode_multipart_form_data(attrs, file_objs) return self._upload_data(content_type, data) def _upload_data(self, content_type, data): def callback(): # FIXME: Setting a timeout, either globally using socket.setdefaulttimeout() # or in urlopen(), doesn't appear to work on Mac 10.5 with Python 2.7. # For now we will ignore the timeout value and hope for the best. request = urllib.Request(self._url, data, {'Content-Type': content_type}) return urllib.urlopen(request) return NetworkTransaction( timeout_seconds=self._timeout_seconds).run(callback)
bsd-3-clause
jayceyxc/hue
desktop/core/ext-py/Django-1.6.10/tests/m2m_regress/models.py
105
2481
from django.contrib.auth import models as auth from django.db import models from django.utils.encoding import python_2_unicode_compatible # No related name is needed here, since symmetrical relations are not # explicitly reversible. @python_2_unicode_compatible class SelfRefer(models.Model): name = models.CharField(max_length=10) references = models.ManyToManyField('self') related = models.ManyToManyField('self') def __str__(self): return self.name @python_2_unicode_compatible class Tag(models.Model): name = models.CharField(max_length=10) def __str__(self): return self.name # Regression for #11956 -- a many to many to the base class @python_2_unicode_compatible class TagCollection(Tag): tags = models.ManyToManyField(Tag, related_name='tag_collections') def __str__(self): return self.name # A related_name is required on one of the ManyToManyField entries here because # they are both addressable as reverse relations from Tag. @python_2_unicode_compatible class Entry(models.Model): name = models.CharField(max_length=10) topics = models.ManyToManyField(Tag) related = models.ManyToManyField(Tag, related_name="similar") def __str__(self): return self.name # Two models both inheriting from a base model with a self-referential m2m field class SelfReferChild(SelfRefer): pass class SelfReferChildSibling(SelfRefer): pass # Many-to-Many relation between models, where one of the PK's isn't an Autofield class Line(models.Model): name = models.CharField(max_length=100) class Worksheet(models.Model): id = models.CharField(primary_key=True, max_length=100) lines = models.ManyToManyField(Line, blank=True, null=True) # Regression for #11226 -- A model with the same name that another one to # which it has a m2m relation. This shouldn't cause a name clash between # the automatically created m2m intermediary table FK field names when # running syncdb class User(models.Model): name = models.CharField(max_length=30) friends = models.ManyToManyField(auth.User) class BadModelWithSplit(models.Model): name = models.CharField(max_length=1) def split(self): raise RuntimeError('split should not be called') class Meta: abstract = True class RegressionModelSplit(BadModelWithSplit): """ Model with a split method should not cause an error in add_lazy_relation """ others = models.ManyToManyField('self')
apache-2.0
JingJunYin/tensorflow
tensorflow/contrib/layers/python/layers/encoders_test.py
111
5276
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.contrib.layers.python.layers.encoders.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.layers.python.layers import encoders from tensorflow.contrib.layers.python.ops import sparse_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import test def _get_const_var(name, shape, value): return variable_scope.get_variable( name, shape, initializer=init_ops.constant_initializer(value)) class EncodersTest(test.TestCase): def testBowEncoderSparse(self): with self.test_session() as sess: docs = [[0, 1], [2, 3]] enc = encoders.bow_encoder(docs, 4, 3) sess.run(variables.global_variables_initializer()) self.assertAllEqual([2, 3], enc.eval().shape) def testBowEncoderSparseTensor(self): with self.test_session() as sess: docs = [[0, 1], [2, 3]] sparse_docs = sparse_ops.dense_to_sparse_tensor(docs) enc = encoders.bow_encoder(sparse_docs, 4, 3) sess.run(variables.global_variables_initializer()) self.assertAllEqual([2, 3], enc.eval().shape) def testBowEncoderSparseEmptyRow(self): with self.test_session() as sess: docs = [[0, 1], [2, 3], [0, 0]] enc = encoders.bow_encoder(docs, 4, 5) sess.run(variables.global_variables_initializer()) self.assertAllEqual([3, 5], enc.eval().shape) def testBowEncoderDense(self): with self.test_session() as sess: docs = [[0, 1], [2, 3], [0, 0], [0, 0]] enc = encoders.bow_encoder(docs, 4, 3, sparse_lookup=False) sess.run(variables.global_variables_initializer()) self.assertAllEqual([4, 3], enc.eval().shape) def testBowEncoderSparseTensorDenseLookup(self): with self.test_session(): docs = [[0, 1]] sparse_docs = sparse_ops.dense_to_sparse_tensor(docs) with self.assertRaises(TypeError): encoders.bow_encoder(sparse_docs, 4, 3, sparse_lookup=False) def testBowEncodersSharingEmbeddings(self): with self.test_session() as sess: docs = [[0, 1], [2, 3]] enc_1 = encoders.bow_encoder(docs, 4, 3, scope='test') enc_2 = encoders.bow_encoder(docs, 4, 3, scope='test', reuse=True) sess.run(variables.global_variables_initializer()) avg_1, avg_2 = sess.run([enc_1, enc_2]) self.assertAllEqual(avg_1, avg_2) def testBowEncodersSharingEmbeddingsInheritedScopes(self): with self.test_session() as sess: docs = [[0, 1], [2, 3]] with variable_scope.variable_scope('test'): enc_1 = encoders.bow_encoder(docs, 4, 3) with variable_scope.variable_scope('test', reuse=True): enc_2 = encoders.bow_encoder(docs, 4, 3) sess.run(variables.global_variables_initializer()) avg_1, avg_2 = sess.run([enc_1, enc_2]) self.assertAllEqual(avg_1, avg_2) def testBowEncodersSharingEmbeddingsSharedScope(self): with self.test_session() as sess: docs = [[0, 1], [2, 3]] enc_1 = encoders.bow_encoder(docs, 4, 3, scope='bow') variable_scope.get_variable_scope().reuse_variables() enc_2 = encoders.bow_encoder(docs, 4, 3, scope='bow') sess.run(variables.global_variables_initializer()) avg_1, avg_2 = sess.run([enc_1, enc_2]) self.assertAllEqual(avg_1, avg_2) def testBowEncoderReuseEmbeddingsVariable(self): with self.test_session() as sess: docs = [[1, 1], [2, 3]] with variable_scope.variable_scope('test'): v = _get_const_var('embeddings', (4, 3), [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]) self.assertEqual(v.name, 'test/embeddings:0') enc = encoders.bow_encoder(docs, 4, 3, scope='test', reuse=True) sess.run(variables.global_variables_initializer()) self.assertAllClose([[3., 4., 5.], [7.5, 8.5, 9.5]], enc.eval()) def testEmbedSequence(self): with self.test_session() as sess: docs = [[1, 1], [2, 3]] with variable_scope.variable_scope('test'): v = _get_const_var('embeddings', (4, 3), [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]) self.assertEqual(v.name, 'test/embeddings:0') emb = encoders.embed_sequence(docs, 4, 3, scope='test', reuse=True) sess.run(variables.global_variables_initializer()) self.assertAllClose( [[[3., 4., 5.], [3., 4., 5.]], [[6., 7., 8.], [9., 10., 11.]]], emb.eval()) if __name__ == '__main__': test.main()
apache-2.0
tafaRU/server-tools
__unported__/fetchmail_attach_from_folder/match_algorithm/__init__.py
15
1087
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2013 Therp BV (<http://therp.nl>) # All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import base import email_exact import email_domain import openerp_standard
agpl-3.0
HyShai/youtube-dl
youtube_dl/extractor/common.py
1
42324
from __future__ import unicode_literals import base64 import datetime import hashlib import json import netrc import os import re import socket import sys import time import xml.etree.ElementTree from ..compat import ( compat_cookiejar, compat_HTTPError, compat_http_client, compat_urllib_error, compat_urllib_parse_urlparse, compat_urlparse, compat_str, ) from ..utils import ( age_restricted, clean_html, compiled_regex_type, ExtractorError, float_or_none, HEADRequest, int_or_none, RegexNotFoundError, sanitize_filename, unescapeHTML, ) _NO_DEFAULT = object() class InfoExtractor(object): """Information Extractor class. Information extractors are the classes that, given a URL, extract information about the video (or videos) the URL refers to. This information includes the real video URL, the video title, author and others. The information is stored in a dictionary which is then passed to the YoutubeDL. The YoutubeDL processes this information possibly downloading the video to the file system, among other possible outcomes. The type field determines the the type of the result. By far the most common value (and the default if _type is missing) is "video", which indicates a single video. For a video, the dictionaries must include the following fields: id: Video identifier. title: Video title, unescaped. Additionally, it must contain either a formats entry or a url one: formats: A list of dictionaries for each format available, ordered from worst to best quality. Potential fields: * url Mandatory. The URL of the video file * ext Will be calculated from url if missing * format A human-readable description of the format ("mp4 container with h264/opus"). Calculated from the format_id, width, height. and format_note fields if missing. * format_id A short description of the format ("mp4_h264_opus" or "19"). Technically optional, but strongly recommended. * format_note Additional info about the format ("3D" or "DASH video") * width Width of the video, if known * height Height of the video, if known * resolution Textual description of width and height * tbr Average bitrate of audio and video in KBit/s * abr Average audio bitrate in KBit/s * acodec Name of the audio codec in use * asr Audio sampling rate in Hertz * vbr Average video bitrate in KBit/s * fps Frame rate * vcodec Name of the video codec in use * container Name of the container format * filesize The number of bytes, if known in advance * filesize_approx An estimate for the number of bytes * player_url SWF Player URL (used for rtmpdump). * protocol The protocol that will be used for the actual download, lower-case. "http", "https", "rtsp", "rtmp", "rtmpe", "m3u8", or "m3u8_native". * preference Order number of this format. If this field is present and not None, the formats get sorted by this field, regardless of all other values. -1 for default (order by other properties), -2 or smaller for less than default. < -1000 to hide the format (if there is another one which is strictly better) * language_preference Is this in the correct requested language? 10 if it's what the URL is about, -1 for default (don't know), -10 otherwise, other values reserved for now. * quality Order number of the video quality of this format, irrespective of the file format. -1 for default (order by other properties), -2 or smaller for less than default. * source_preference Order number for this video source (quality takes higher priority) -1 for default (order by other properties), -2 or smaller for less than default. * http_method HTTP method to use for the download. * http_headers A dictionary of additional HTTP headers to add to the request. * http_post_data Additional data to send with a POST request. * stretched_ratio If given and not 1, indicates that the video's pixels are not square. width : height ratio as float. * no_resume The server does not support resuming the (HTTP or RTMP) download. Boolean. url: Final video URL. ext: Video filename extension. format: The video format, defaults to ext (used for --get-format) player_url: SWF Player URL (used for rtmpdump). The following fields are optional: alt_title: A secondary title of the video. display_id An alternative identifier for the video, not necessarily unique, but available before title. Typically, id is something like "4234987", title "Dancing naked mole rats", and display_id "dancing-naked-mole-rats" thumbnails: A list of dictionaries, with the following entries: * "id" (optional, string) - Thumbnail format ID * "url" * "preference" (optional, int) - quality of the image * "width" (optional, int) * "height" (optional, int) * "resolution" (optional, string "{width}x{height"}, deprecated) thumbnail: Full URL to a video thumbnail image. description: Full video description. uploader: Full name of the video uploader. creator: The main artist who created the video. timestamp: UNIX timestamp of the moment the video became available. upload_date: Video upload date (YYYYMMDD). If not explicitly set, calculated from timestamp. uploader_id: Nickname or id of the video uploader. location: Physical location where the video was filmed. subtitles: The subtitle file contents as a dictionary in the format {language: subtitles}. duration: Length of the video in seconds, as an integer. view_count: How many users have watched the video on the platform. like_count: Number of positive ratings of the video dislike_count: Number of negative ratings of the video comment_count: Number of comments on the video comments: A list of comments, each with one or more of the following properties (all but one of text or html optional): * "author" - human-readable name of the comment author * "author_id" - user ID of the comment author * "id" - Comment ID * "html" - Comment as HTML * "text" - Plain text of the comment * "timestamp" - UNIX timestamp of comment * "parent" - ID of the comment this one is replying to. Set to "root" to indicate that this is a comment to the original video. age_limit: Age restriction for the video, as an integer (years) webpage_url: The url to the video webpage, if given to youtube-dl it should allow to get the same result again. (It will be set by YoutubeDL if it's missing) categories: A list of categories that the video falls in, for example ["Sports", "Berlin"] is_live: True, False, or None (=unknown). Whether this video is a live stream that goes on instead of a fixed-length video. Unless mentioned otherwise, the fields should be Unicode strings. Unless mentioned otherwise, None is equivalent to absence of information. _type "playlist" indicates multiple videos. There must be a key "entries", which is a list, an iterable, or a PagedList object, each element of which is a valid dictionary by this specification. Additionally, playlists can have "title" and "id" attributes with the same semantics as videos (see above). _type "multi_video" indicates that there are multiple videos that form a single show, for examples multiple acts of an opera or TV episode. It must have an entries key like a playlist and contain all the keys required for a video at the same time. _type "url" indicates that the video must be extracted from another location, possibly by a different extractor. Its only required key is: "url" - the next URL to extract. The key "ie_key" can be set to the class name (minus the trailing "IE", e.g. "Youtube") if the extractor class is known in advance. Additionally, the dictionary may have any properties of the resolved entity known in advance, for example "title" if the title of the referred video is known ahead of time. _type "url_transparent" entities have the same specification as "url", but indicate that the given additional information is more precise than the one associated with the resolved URL. This is useful when a site employs a video service that hosts the video and its technical metadata, but that video service does not embed a useful title, description etc. Subclasses of this one should re-define the _real_initialize() and _real_extract() methods and define a _VALID_URL regexp. Probably, they should also be added to the list of extractors. Finally, the _WORKING attribute should be set to False for broken IEs in order to warn the users and skip the tests. """ _ready = False _downloader = None _WORKING = True def __init__(self, downloader=None): """Constructor. Receives an optional downloader.""" self._ready = False self.set_downloader(downloader) @classmethod def suitable(cls, url): """Receives a URL and returns True if suitable for this IE.""" # This does not use has/getattr intentionally - we want to know whether # we have cached the regexp for *this* class, whereas getattr would also # match the superclass if '_VALID_URL_RE' not in cls.__dict__: cls._VALID_URL_RE = re.compile(cls._VALID_URL) return cls._VALID_URL_RE.match(url) is not None @classmethod def _match_id(cls, url): if '_VALID_URL_RE' not in cls.__dict__: cls._VALID_URL_RE = re.compile(cls._VALID_URL) m = cls._VALID_URL_RE.match(url) assert m return m.group('id') @classmethod def working(cls): """Getter method for _WORKING.""" return cls._WORKING def initialize(self): """Initializes an instance (authentication, etc).""" if not self._ready: self._real_initialize() self._ready = True def extract(self, url): """Extracts URL information and returns it in list of dicts.""" self.initialize() return self._real_extract(url) def set_downloader(self, downloader): """Sets the downloader for this IE.""" self._downloader = downloader def _real_initialize(self): """Real initialization process. Redefine in subclasses.""" pass def _real_extract(self, url): """Real extraction process. Redefine in subclasses.""" pass @classmethod def ie_key(cls): """A string for getting the InfoExtractor with get_info_extractor""" return cls.__name__[:-2] @property def IE_NAME(self): return type(self).__name__[:-2] def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True): """ Returns the response handle """ if note is None: self.report_download_webpage(video_id) elif note is not False: if video_id is None: self.to_screen('%s' % (note,)) else: self.to_screen('%s: %s' % (video_id, note)) try: return self._downloader.urlopen(url_or_request) except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err: if errnote is False: return False if errnote is None: errnote = 'Unable to download webpage' errmsg = '%s: %s' % (errnote, compat_str(err)) if fatal: raise ExtractorError(errmsg, sys.exc_info()[2], cause=err) else: self._downloader.report_warning(errmsg) return False def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True): """ Returns a tuple (page content as string, URL handle) """ # Strip hashes from the URL (#1038) if isinstance(url_or_request, (compat_str, str)): url_or_request = url_or_request.partition('#')[0] urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal) if urlh is False: assert not fatal return False content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal) return (content, urlh) def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True, prefix=None): content_type = urlh.headers.get('Content-Type', '') webpage_bytes = urlh.read() if prefix is not None: webpage_bytes = prefix + webpage_bytes m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type) if m: encoding = m.group(1) else: m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]', webpage_bytes[:1024]) if m: encoding = m.group(1).decode('ascii') elif webpage_bytes.startswith(b'\xff\xfe'): encoding = 'utf-16' else: encoding = 'utf-8' if self._downloader.params.get('dump_intermediate_pages', False): try: url = url_or_request.get_full_url() except AttributeError: url = url_or_request self.to_screen('Dumping request to ' + url) dump = base64.b64encode(webpage_bytes).decode('ascii') self._downloader.to_screen(dump) if self._downloader.params.get('write_pages', False): try: url = url_or_request.get_full_url() except AttributeError: url = url_or_request basen = '%s_%s' % (video_id, url) if len(basen) > 240: h = '___' + hashlib.md5(basen.encode('utf-8')).hexdigest() basen = basen[:240 - len(h)] + h raw_filename = basen + '.dump' filename = sanitize_filename(raw_filename, restricted=True) self.to_screen('Saving request to ' + filename) # Working around MAX_PATH limitation on Windows (see # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx) if os.name == 'nt': absfilepath = os.path.abspath(filename) if len(absfilepath) > 259: filename = '\\\\?\\' + absfilepath with open(filename, 'wb') as outf: outf.write(webpage_bytes) try: content = webpage_bytes.decode(encoding, 'replace') except LookupError: content = webpage_bytes.decode('utf-8', 'replace') if ('<title>Access to this site is blocked</title>' in content and 'Websense' in content[:512]): msg = 'Access to this webpage has been blocked by Websense filtering software in your network.' blocked_iframe = self._html_search_regex( r'<iframe src="([^"]+)"', content, 'Websense information URL', default=None) if blocked_iframe: msg += ' Visit %s for more details' % blocked_iframe raise ExtractorError(msg, expected=True) return content def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, tries=1, timeout=5): """ Returns the data of the page as a string """ success = False try_count = 0 while success is False: try: res = self._download_webpage_handle(url_or_request, video_id, note, errnote, fatal) success = True except compat_http_client.IncompleteRead as e: try_count += 1 if try_count >= tries: raise e self._sleep(timeout, video_id) if res is False: return res else: content, _ = res return content def _download_xml(self, url_or_request, video_id, note='Downloading XML', errnote='Unable to download XML', transform_source=None, fatal=True): """Return the xml as an xml.etree.ElementTree.Element""" xml_string = self._download_webpage( url_or_request, video_id, note, errnote, fatal=fatal) if xml_string is False: return xml_string if transform_source: xml_string = transform_source(xml_string) return xml.etree.ElementTree.fromstring(xml_string.encode('utf-8')) def _download_json(self, url_or_request, video_id, note='Downloading JSON metadata', errnote='Unable to download JSON metadata', transform_source=None, fatal=True): json_string = self._download_webpage( url_or_request, video_id, note, errnote, fatal=fatal) if (not fatal) and json_string is False: return None return self._parse_json( json_string, video_id, transform_source=transform_source, fatal=fatal) def _parse_json(self, json_string, video_id, transform_source=None, fatal=True): if transform_source: json_string = transform_source(json_string) try: return json.loads(json_string) except ValueError as ve: errmsg = '%s: Failed to parse JSON ' % video_id if fatal: raise ExtractorError(errmsg, cause=ve) else: self.report_warning(errmsg + str(ve)) def report_warning(self, msg, video_id=None): idstr = '' if video_id is None else '%s: ' % video_id self._downloader.report_warning( '[%s] %s%s' % (self.IE_NAME, idstr, msg)) def to_screen(self, msg): """Print msg to screen, prefixing it with '[ie_name]'""" self._downloader.to_screen('[%s] %s' % (self.IE_NAME, msg)) def report_extraction(self, id_or_name): """Report information extraction.""" self.to_screen('%s: Extracting information' % id_or_name) def report_download_webpage(self, video_id): """Report webpage download.""" self.to_screen('%s: Downloading webpage' % video_id) def report_age_confirmation(self): """Report attempt to confirm age.""" self.to_screen('Confirming age') def report_login(self): """Report attempt to log in.""" self.to_screen('Logging in') # Methods for following #608 @staticmethod def url_result(url, ie=None, video_id=None): """Returns a url that points to a page that should be processed""" # TODO: ie should be the class used for getting the info video_info = {'_type': 'url', 'url': url, 'ie_key': ie} if video_id is not None: video_info['id'] = video_id return video_info @staticmethod def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None): """Returns a playlist""" video_info = {'_type': 'playlist', 'entries': entries} if playlist_id: video_info['id'] = playlist_id if playlist_title: video_info['title'] = playlist_title if playlist_description: video_info['description'] = playlist_description return video_info def _search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0, group=None): """ Perform a regex search on the given string, using a single or a list of patterns returning the first matching group. In case of failure return a default value or raise a WARNING or a RegexNotFoundError, depending on fatal, specifying the field name. """ if isinstance(pattern, (str, compat_str, compiled_regex_type)): mobj = re.search(pattern, string, flags) else: for p in pattern: mobj = re.search(p, string, flags) if mobj: break if os.name != 'nt': _name = '\033[0;34m%s\033[0m' % name else: _name = name if mobj: if group is None: # return the first matching group return next(g for g in mobj.groups() if g is not None) else: return mobj.group(group) elif default is not _NO_DEFAULT: return default elif fatal: raise RegexNotFoundError('Unable to extract %s' % _name) else: self._downloader.report_warning('unable to extract %s; ' 'please report this issue on http://yt-dl.org/bug' % _name) return None def _html_search_regex(self, pattern, string, name, default=_NO_DEFAULT, fatal=True, flags=0, group=None): """ Like _search_regex, but strips HTML tags and unescapes entities. """ res = self._search_regex(pattern, string, name, default, fatal, flags, group) if res: return clean_html(res).strip() else: return res def _get_login_info(self): """ Get the the login info as (username, password) It will look in the netrc file using the _NETRC_MACHINE value If there's no info available, return (None, None) """ if self._downloader is None: return (None, None) username = None password = None downloader_params = self._downloader.params # Attempt to use provided username and password or .netrc data if downloader_params.get('username', None) is not None: username = downloader_params['username'] password = downloader_params['password'] elif downloader_params.get('usenetrc', False): try: info = netrc.netrc().authenticators(self._NETRC_MACHINE) if info is not None: username = info[0] password = info[2] else: raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE) except (IOError, netrc.NetrcParseError) as err: self._downloader.report_warning('parsing .netrc: %s' % compat_str(err)) return (username, password) def _get_tfa_info(self): """ Get the two-factor authentication info TODO - asking the user will be required for sms/phone verify currently just uses the command line option If there's no info available, return None """ if self._downloader is None: return None downloader_params = self._downloader.params if downloader_params.get('twofactor', None) is not None: return downloader_params['twofactor'] return None # Helper functions for extracting OpenGraph info @staticmethod def _og_regexes(prop): content_re = r'content=(?:"([^>]+?)"|\'([^>]+?)\')' property_re = r'(?:name|property)=[\'"]og:%s[\'"]' % re.escape(prop) template = r'<meta[^>]+?%s[^>]+?%s' return [ template % (property_re, content_re), template % (content_re, property_re), ] def _og_search_property(self, prop, html, name=None, **kargs): if name is None: name = 'OpenGraph %s' % prop escaped = self._search_regex(self._og_regexes(prop), html, name, flags=re.DOTALL, **kargs) if escaped is None: return None return unescapeHTML(escaped) def _og_search_thumbnail(self, html, **kargs): return self._og_search_property('image', html, 'thumbnail url', fatal=False, **kargs) def _og_search_description(self, html, **kargs): return self._og_search_property('description', html, fatal=False, **kargs) def _og_search_title(self, html, **kargs): return self._og_search_property('title', html, **kargs) def _og_search_video_url(self, html, name='video url', secure=True, **kargs): regexes = self._og_regexes('video') + self._og_regexes('video:url') if secure: regexes = self._og_regexes('video:secure_url') + regexes return self._html_search_regex(regexes, html, name, **kargs) def _og_search_url(self, html, **kargs): return self._og_search_property('url', html, **kargs) def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs): if display_name is None: display_name = name return self._html_search_regex( r'''(?isx)<meta (?=[^>]+(?:itemprop|name|property)=(["\']?)%s\1) [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(name), html, display_name, fatal=fatal, group='content', **kwargs) def _dc_search_uploader(self, html): return self._html_search_meta('dc.creator', html, 'uploader') def _rta_search(self, html): # See http://www.rtalabel.org/index.php?content=howtofaq#single if re.search(r'(?ix)<meta\s+name="rating"\s+' r' content="RTA-5042-1996-1400-1577-RTA"', html): return 18 return 0 def _media_rating_search(self, html): # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/ rating = self._html_search_meta('rating', html) if not rating: return None RATING_TABLE = { 'safe for kids': 0, 'general': 8, '14 years': 14, 'mature': 17, 'restricted': 19, } return RATING_TABLE.get(rating.lower(), None) def _twitter_search_player(self, html): return self._html_search_meta('twitter:player', html, 'twitter card player') def _sort_formats(self, formats): if not formats: raise ExtractorError('No video formats found') def _formats_key(f): # TODO remove the following workaround from ..utils import determine_ext if not f.get('ext') and 'url' in f: f['ext'] = determine_ext(f['url']) preference = f.get('preference') if preference is None: proto = f.get('protocol') if proto is None: proto = compat_urllib_parse_urlparse(f.get('url', '')).scheme preference = 0 if proto in ['http', 'https'] else -0.1 if f.get('ext') in ['f4f', 'f4m']: # Not yet supported preference -= 0.5 if f.get('vcodec') == 'none': # audio only if self._downloader.params.get('prefer_free_formats'): ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus'] else: ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a'] ext_preference = 0 try: audio_ext_preference = ORDER.index(f['ext']) except ValueError: audio_ext_preference = -1 else: if self._downloader.params.get('prefer_free_formats'): ORDER = ['flv', 'mp4', 'webm'] else: ORDER = ['webm', 'flv', 'mp4'] try: ext_preference = ORDER.index(f['ext']) except ValueError: ext_preference = -1 audio_ext_preference = 0 return ( preference, f.get('language_preference') if f.get('language_preference') is not None else -1, f.get('quality') if f.get('quality') is not None else -1, f.get('tbr') if f.get('tbr') is not None else -1, f.get('vbr') if f.get('vbr') is not None else -1, ext_preference, f.get('height') if f.get('height') is not None else -1, f.get('width') if f.get('width') is not None else -1, f.get('abr') if f.get('abr') is not None else -1, audio_ext_preference, f.get('fps') if f.get('fps') is not None else -1, f.get('filesize') if f.get('filesize') is not None else -1, f.get('filesize_approx') if f.get('filesize_approx') is not None else -1, f.get('source_preference') if f.get('source_preference') is not None else -1, f.get('format_id'), ) formats.sort(key=_formats_key) def _check_formats(self, formats, video_id): if formats: formats[:] = filter( lambda f: self._is_valid_url( f['url'], video_id, item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'), formats) def _is_valid_url(self, url, video_id, item='video'): try: self._request_webpage( HEADRequest(url), video_id, 'Checking %s URL' % item) return True except ExtractorError as e: if isinstance(e.cause, compat_HTTPError): self.report_warning( '%s URL is invalid, skipping' % item, video_id) return False raise def http_scheme(self): """ Either "http:" or "https:", depending on the user's preferences """ return ( 'http:' if self._downloader.params.get('prefer_insecure', False) else 'https:') def _proto_relative_url(self, url, scheme=None): if url is None: return url if url.startswith('//'): if scheme is None: scheme = self.http_scheme() return scheme + url else: return url def _sleep(self, timeout, video_id, msg_template=None): if msg_template is None: msg_template = '%(video_id)s: Waiting for %(timeout)s seconds' msg = msg_template % {'video_id': video_id, 'timeout': timeout} self.to_screen(msg) time.sleep(timeout) def _extract_f4m_formats(self, manifest_url, video_id): manifest = self._download_xml( manifest_url, video_id, 'Downloading f4m manifest', 'Unable to download f4m manifest') formats = [] manifest_version = '1.0' media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media') if not media_nodes: manifest_version = '2.0' media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media') for i, media_el in enumerate(media_nodes): if manifest_version == '2.0': manifest_url = '/'.join(manifest_url.split('/')[:-1]) + '/' + media_el.attrib.get('href') tbr = int_or_none(media_el.attrib.get('bitrate')) format_id = 'f4m-%d' % (i if tbr is None else tbr) formats.append({ 'format_id': format_id, 'url': manifest_url, 'ext': 'flv', 'tbr': tbr, 'width': int_or_none(media_el.attrib.get('width')), 'height': int_or_none(media_el.attrib.get('height')), }) self._sort_formats(formats) return formats def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None, entry_protocol='m3u8', preference=None): formats = [{ 'format_id': 'm3u8-meta', 'url': m3u8_url, 'ext': ext, 'protocol': 'm3u8', 'preference': -1, 'resolution': 'multiple', 'format_note': 'Quality selection URL', }] format_url = lambda u: ( u if re.match(r'^https?://', u) else compat_urlparse.urljoin(m3u8_url, u)) m3u8_doc = self._download_webpage( m3u8_url, video_id, note='Downloading m3u8 information', errnote='Failed to download m3u8 information') last_info = None kv_rex = re.compile( r'(?P<key>[a-zA-Z_-]+)=(?P<val>"[^"]+"|[^",]+)(?:,|$)') for line in m3u8_doc.splitlines(): if line.startswith('#EXT-X-STREAM-INF:'): last_info = {} for m in kv_rex.finditer(line): v = m.group('val') if v.startswith('"'): v = v[1:-1] last_info[m.group('key')] = v elif line.startswith('#') or not line.strip(): continue else: if last_info is None: formats.append({'url': format_url(line)}) continue tbr = int_or_none(last_info.get('BANDWIDTH'), scale=1000) f = { 'format_id': 'm3u8-%d' % (tbr if tbr else len(formats)), 'url': format_url(line.strip()), 'tbr': tbr, 'ext': ext, 'protocol': entry_protocol, 'preference': preference, } codecs = last_info.get('CODECS') if codecs: # TODO: looks like video codec is not always necessarily goes first va_codecs = codecs.split(',') if va_codecs[0]: f['vcodec'] = va_codecs[0].partition('.')[0] if len(va_codecs) > 1 and va_codecs[1]: f['acodec'] = va_codecs[1].partition('.')[0] resolution = last_info.get('RESOLUTION') if resolution: width_str, height_str = resolution.split('x') f['width'] = int(width_str) f['height'] = int(height_str) formats.append(f) last_info = {} self._sort_formats(formats) return formats # TODO: improve extraction def _extract_smil_formats(self, smil_url, video_id, fatal=True): smil = self._download_xml( smil_url, video_id, 'Downloading SMIL file', 'Unable to download SMIL file', fatal=fatal) if smil is False: assert not fatal return [] base = smil.find('./head/meta').get('base') formats = [] rtmp_count = 0 for video in smil.findall('./body/switch/video'): src = video.get('src') if not src: continue bitrate = int_or_none(video.get('system-bitrate') or video.get('systemBitrate'), 1000) width = int_or_none(video.get('width')) height = int_or_none(video.get('height')) proto = video.get('proto') if not proto: if base: if base.startswith('rtmp'): proto = 'rtmp' elif base.startswith('http'): proto = 'http' ext = video.get('ext') if proto == 'm3u8': formats.extend(self._extract_m3u8_formats(src, video_id, ext)) elif proto == 'rtmp': rtmp_count += 1 streamer = video.get('streamer') or base formats.append({ 'url': streamer, 'play_path': src, 'ext': 'flv', 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate), 'tbr': bitrate, 'width': width, 'height': height, }) self._sort_formats(formats) return formats def _live_title(self, name): """ Generate the title for a live video """ now = datetime.datetime.now() now_str = now.strftime("%Y-%m-%d %H:%M") return name + ' ' + now_str def _int(self, v, name, fatal=False, **kwargs): res = int_or_none(v, **kwargs) if 'get_attr' in kwargs: print(getattr(v, kwargs['get_attr'])) if res is None: msg = 'Failed to extract %s: Could not parse value %r' % (name, v) if fatal: raise ExtractorError(msg) else: self._downloader.report_warning(msg) return res def _float(self, v, name, fatal=False, **kwargs): res = float_or_none(v, **kwargs) if res is None: msg = 'Failed to extract %s: Could not parse value %r' % (name, v) if fatal: raise ExtractorError(msg) else: self._downloader.report_warning(msg) return res def _set_cookie(self, domain, name, value, expire_time=None): cookie = compat_cookiejar.Cookie( 0, name, value, None, None, domain, None, None, '/', True, False, expire_time, '', None, None, None) self._downloader.cookiejar.set_cookie(cookie) def get_testcases(self, include_onlymatching=False): t = getattr(self, '_TEST', None) if t: assert not hasattr(self, '_TESTS'), \ '%s has _TEST and _TESTS' % type(self).__name__ tests = [t] else: tests = getattr(self, '_TESTS', []) for t in tests: if not include_onlymatching and t.get('only_matching', False): continue t['name'] = type(self).__name__[:-len('IE')] yield t def is_suitable(self, age_limit): """ Test whether the extractor is generally suitable for the given age limit (i.e. pornographic sites are not, all others usually are) """ any_restricted = False for tc in self.get_testcases(include_onlymatching=False): if 'playlist' in tc: tc = tc['playlist'][0] is_restricted = age_restricted( tc.get('info_dict', {}).get('age_limit'), age_limit) if not is_restricted: return True any_restricted = any_restricted or is_restricted return not any_restricted class SearchInfoExtractor(InfoExtractor): """ Base class for paged search queries extractors. They accept urls in the format _SEARCH_KEY(|all|[0-9]):{query} Instances should define _SEARCH_KEY and _MAX_RESULTS. """ @classmethod def _make_valid_url(cls): return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY @classmethod def suitable(cls, url): return re.match(cls._make_valid_url(), url) is not None def _real_extract(self, query): mobj = re.match(self._make_valid_url(), query) if mobj is None: raise ExtractorError('Invalid search query "%s"' % query) prefix = mobj.group('prefix') query = mobj.group('query') if prefix == '': return self._get_n_results(query, 1) elif prefix == 'all': return self._get_n_results(query, self._MAX_RESULTS) else: n = int(prefix) if n <= 0: raise ExtractorError('invalid download number %s for query "%s"' % (n, query)) elif n > self._MAX_RESULTS: self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n)) n = self._MAX_RESULTS return self._get_n_results(query, n) def _get_n_results(self, query, n): """Get a specified number of results for a query""" raise NotImplementedError("This method must be implemented by subclasses") @property def SEARCH_KEY(self): return self._SEARCH_KEY
unlicense
AlexandroPQC/sara-ani
Saranani/apps/users/models.py
1
1604
from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields): email = self.normalize_email(email) user = self.model(username=username, email=email, is_active=True, is_staff=is_staff, is_superuser=is_superuser, **extra_fields) user.set_password(password) user.save(using = self._db) return user def create_user(self, username, email, password=None, **extra_fields): return self._create_user(username, email, password, False, False, **extra_fields) def create_superuser(self, username, email, password, **extra_fields): return self._create_user(username, email, password, True, True, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=50, unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) birthday = models.DateField(null=True, blank=True) nit = models.CharField(max_length=20) avatar = models.URLField() objects = UserManager() is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def get_short_name(self): return self.username def get_full_name(self): return self.username
gpl-3.0
simonpf/root
tutorials/dataframe/tdf001_introduction.py
6
4805
## \file ## \ingroup tutorial_tdataframe ## \notebook -nodraw ## This tutorial illustrates the basic features of the TDataFrame class, ## a utility which allows to interact with data stored in TTrees following ## a functional-chain like approach. ## ## \macro_code ## ## \date May 2017 ## \author Danilo Piparo import ROOT # A simple helper function to fill a test tree: this makes the example stand-alone. fill_tree_code = ''' void fill_tree(const char *filename, const char *treeName) { TFile f(filename, "RECREATE"); TTree t(treeName, treeName); double b1; int b2; t.Branch("b1", &b1); t.Branch("b2", &b2); for (int i = 0; i < 10; ++i) { b1 = i; b2 = i * i; t.Fill(); } t.Write(); f.Close(); return; } ''' # We prepare an input tree to run on fileName = "tdf001_introduction_py.root" treeName = "myTree" ROOT.gInterpreter.Declare(fill_tree_code) ROOT.fill_tree(fileName, treeName) # We read the tree from the file and create a TDataFrame, a class that # allows us to interact with the data contained in the tree. TDF = ROOT.ROOT.Experimental.TDataFrame d = TDF(treeName, fileName) # Operations on the dataframe # We now review some *actions* which can be performed on the data frame. # All actions but ForEach return a TActionResultPtr<T>. The series of # operations on the data frame is not executed until one of those pointers # is accessed. # But first of all, let us we define now our cut-flow with two strings. # Filters can be expressed as strings. The content must be C++ code. The # name of the variables must be the name of the branches. The code is # just in time compiled. cutb1 = 'b1 < 5.' cutb1b2 = 'b2 % 2 && b1 < 4.' # `Count` action # The `Count` allows to retrieve the number of the entries that passed the # filters. Here we show how the automatic selection of the column kicks # in in case the user specifies none. entries1 = d.Filter(cutb1) \ .Filter(cutb1b2) \ .Count(); print("%s entries passed all filters" %entries1.GetValue()) entries2 = d.Filter("b1 < 5.").Count(); print("%s entries passed all filters" %entries2.GetValue()) # `Min`, `Max` and `Mean` actions # These actions allow to retrieve statistical information about the entries # passing the cuts, if any. b1b2_cut = d.Filter(cutb1b2) minVal = b1b2_cut.Min('b1') maxVal = b1b2_cut.Max('b1') meanVal = b1b2_cut.Mean('b1') nonDefmeanVal = b1b2_cut.Mean("b2") print("The mean is always included between the min and the max: %s <= %s <= %s" %(minVal.GetValue(), meanVal.GetValue(), maxVal.GetValue())) # `Histo1D` action # The `Histo1D` action allows to fill an histogram. It returns a TH1F filled # with values of the column that passed the filters. For the most common # types, the type of the values stored in the column is automatically # guessed. hist = d.Filter(cutb1).Histo1D('b1') print("Filled h %s times, mean: %s" %(hist.GetEntries(), hist.GetMean())) # Express your chain of operations with clarity! # We are discussing an example here but it is not hard to imagine much more # complex pipelines of actions acting on data. Those might require code # which is well organised, for example allowing to conditionally add filters # or again to clearly separate filters and actions without the need of # writing the entire pipeline on one line. This can be easily achieved. # We'll show this re-working the `Count` example: cutb1_result = d.Filter(cutb1); cutb1b2_result = d.Filter(cutb1b2); cutb1_cutb1b2_result = cutb1_result.Filter(cutb1b2) # Now we want to count: evts_cutb1_result = cutb1_result.Count() evts_cutb1b2_result = cutb1b2_result.Count() evts_cutb1_cutb1b2_result = cutb1_cutb1b2_result.Count() print("Events passing cutb1: %s" %evts_cutb1_result.GetValue()) print("Events passing cutb1b2: %s" %evts_cutb1b2_result.GetValue()) print("Events passing both: %s" %evts_cutb1_cutb1b2_result.GetValue()) # Calculating quantities starting from existing columns # Often, operations need to be carried out on quantities calculated starting # from the ones present in the columns. We'll create in this example a third # column the values of which are the sum of the *b1* and *b2* ones, entry by # entry. The way in which the new quantity is defined is via a runable. # It is important to note two aspects at this point: # - The value is created on the fly only if the entry passed the existing # filters. # - The newly created column behaves as the one present on the file on disk. # - The operation creates a new value, without modifying anything. De facto, # this is like having a general container at disposal able to accommodate # any value of any type. # Let's dive in an example: entries_sum = d.Define('sum', 'b2 + b1') \ .Filter('sum > 4.2') \ .Count() print(entries_sum.GetValue())
lgpl-2.1
repotvsupertuga/tvsupertuga.repository
instal/script.module.schism.common/lib/js2py/legecy_translators/jsparser.py
42
9809
""" The process of translating JS will go like that: # TOP = 'imports and scope set' 1. Remove all the comments 2. Replace number, string and regexp literals with markers 4. Remove global Functions and move their translation to the TOP. Also add register code there. 5. Replace inline functions with lvals 6. Remove List and Object literals and replace them with lvals 7. Find and remove var declarations, generate python register code that would go on TOP. Here we should be left with global code only where 1 line of js code = 1 line of python code. Routine translating this code should be called glob_translate: 1. Search for outer structures and translate them using glob and inside using exps_translate exps_translate routine: 1. Remove outer {} 2. Split lines at ; 3. Convert line by line using exp_translate 4. In case of error in 3 try to insert ; according to ECMA rules and repeat 3. exp_translate routine: It takes a single line of JS code and returns a SINGLE line of Python code. Note var is not present here because it was removed in previous stages. If case of parsing errors it must return a pos of error. 1. Convert all assignment operations to put operations, this may be hard :( 2. Convert all gets and calls to get and callprop. 3. Convert unary operators like typeof, new, !, delete. Delete can be handled by replacing last get method with delete. 4. Convert remaining operators that are not handled by python eg: === and , lval format PyJsLvalNR marker PyJs(TYPE_NAME)(NR) TODO 1. Number literal replacement 2. Array literal replacement 3. Object literal replacement 5. Function replacement 4. Literal replacement translators """ from utils import * OP_METHODS = {'*': '__mul__', '/': '__div__', '%': '__mod__', '+': '__add__', '-': '__sub__', '<<': '__lshift__', '>>': '__rshift__', '&': '__and__', '^': '__xor__', '|': '__or__'} def dbg(source): try: with open('C:\Users\Piotrek\Desktop\dbg.py','w') as f: f.write(source) except: pass def indent(lines, ind=4): return ind*' '+lines.replace('\n', '\n'+ind*' ').rstrip(' ') def inject_before_lval(source, lval, code): if source.count(lval)>1: dbg(source) print print lval raise RuntimeError('To many lvals (%s)' % lval) elif not source.count(lval): dbg(source) print print lval assert lval not in source raise RuntimeError('No lval found "%s"' % lval) end = source.index(lval) inj = source.rfind('\n', 0, end) ind = inj while source[ind+1]==' ': ind+=1 ind -= inj return source[:inj+1]+ indent(code, ind) + source[inj+1:] def bracket_split(source, brackets=('()','{}','[]'), strip=False): """DOES NOT RETURN EMPTY STRINGS (can only return empty bracket content if strip=True)""" starts = [e[0] for e in brackets] in_bracket = 0 n = 0 last = 0 while n<len(source): e = source[n] if not in_bracket and e in starts: in_bracket = 1 start = n b_start, b_end = brackets[starts.index(e)] elif in_bracket: if e==b_start: in_bracket += 1 elif e==b_end: in_bracket -= 1 if not in_bracket: if source[last:start]: yield source[last:start] last = n+1 yield source[start+strip:n+1-strip] n+=1 if source[last:]: yield source[last:] def pass_bracket(source, start, bracket='()'): """Returns content of brackets with brackets and first pos after brackets if source[start] is followed by some optional white space and brackets. Otherwise None""" e = bracket_split(source[start:],[bracket], False) try: cand = e.next() except StopIteration: return None, None if not cand.strip(): #white space... try: res = e.next() return res, start + len(cand) + len(res) except StopIteration: return None, None elif cand[-1] == bracket[1]: return cand, start + len(cand) else: return None, None def startswith_keyword(start, keyword): start = start.lstrip() if start.startswith(keyword): if len(keyword)<len(start): if start[len(keyword)] in IDENTIFIER_PART: return False return True return False def endswith_keyword(ending, keyword): ending = ending.rstrip() if ending.endswith(keyword): if len(keyword)<len(ending): if ending[len(ending)-len(keyword)-1] in IDENTIFIER_PART: return False return True return False def pass_white(source, start): n = start while n<len(source): if source[n] in SPACE: n += 1 else: break return n def except_token(source, start, token, throw=True): """Token can be only a single char. Returns position after token if found. Otherwise raises syntax error if throw otherwise returns None""" start = pass_white(source, start) if start<len(source) and source[start]==token: return start+1 if throw: raise SyntaxError('Missing token. Expected %s'%token) return None def except_keyword(source, start, keyword): """ Returns position after keyword if found else None Note: skips white space""" start = pass_white(source, start) kl = len(keyword) #keyword len if kl+start > len(source): return None if source[start:start+kl] != keyword: return None if kl+start<len(source) and source[start+kl] in IDENTIFIER_PART: return None return start + kl def parse_identifier(source, start, throw=True): """passes white space from start and returns first identifier, if identifier invalid and throw raises SyntaxError otherwise returns None""" start = pass_white(source, start) end = start if not end<len(source): if throw: raise SyntaxError('Missing identifier!') return None if source[end] not in IDENTIFIER_START: if throw: raise SyntaxError('Invalid identifier start: "%s"'%source[end]) return None end += 1 while end < len(source) and source[end] in IDENTIFIER_PART: end += 1 if not is_valid_lval(source[start:end]): if throw: raise SyntaxError('Invalid identifier name: "%s"'%source[start:end]) return None return source[start:end], end def argsplit(args, sep=','): """used to split JS args (it is not that simple as it seems because sep can be inside brackets). pass args *without* brackets! Used also to parse array and object elements, and more""" parsed_len = 0 last = 0 splits = [] for e in bracket_split(args, brackets=['()', '[]', '{}']): if e[0] not in ['(', '[', '{']: for i, char in enumerate(e): if char==sep: splits.append(args[last:parsed_len+i]) last = parsed_len + i + 1 parsed_len += len(e) splits.append(args[last:]) return splits def split_add_ops(text): """Specialized function splitting text at add/sub operators. Operands are *not* translated. Example result ['op1', '+', 'op2', '-', 'op3']""" n = 0 text = text.replace('++', '##').replace('--', '@@') #text does not normally contain any of these spotted = False # set to true if noticed anything other than +- or white space last = 0 while n<len(text): e = text[n] if e=='+' or e=='-': if spotted: yield text[last:n].replace('##', '++').replace('@@', '--') yield e last = n+1 spotted = False elif e=='/' or e=='*' or e=='%': spotted = False elif e!=' ': spotted = True n+=1 yield text[last:n].replace('##', '++').replace('@@', '--') def split_at_any(text, lis, translate=False, not_before=[], not_after=[], validitate=None): """ doc """ lis.sort(key=lambda x: len(x), reverse=True) last = 0 n = 0 text_len = len(text) while n<text_len: if any(text[:n].endswith(e) for e in not_before): #Cant end with end before n+=1 continue for e in lis: s = len(e) if s+n>text_len: continue if validitate and not validitate(e, text[:n], text[n+s:]): continue if any(text[n+s:].startswith(e) for e in not_after): #Cant end with end before n+=1 break if e==text[n:n+s]: yield text[last:n] if not translate else translate(text[last:n]) yield e n+=s last = n break else: n+=1 yield text[last:n] if not translate else translate(text[last:n]) def split_at_single(text, sep, not_before=[], not_after=[]): """Works like text.split(sep) but separated fragments cant end with not_before or start with not_after""" n = 0 lt, s= len(text), len(sep) last = 0 while n<lt: if not s+n>lt: if sep==text[n:n+s]: if any(text[last:n].endswith(e) for e in not_before): pass elif any(text[n+s:].startswith(e) for e in not_after): pass else: yield text[last:n] last = n+s n += s-1 n+=1 yield text[last:]
gpl-2.0
krishnazure/Flask
Work/Trivia - Module 5/env/Lib/site-packages/pip/_vendor/requests/packages/chardet/euctwprober.py
2994
1676
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is mozilla.org code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from .mbcharsetprober import MultiByteCharSetProber from .codingstatemachine import CodingStateMachine from .chardistribution import EUCTWDistributionAnalysis from .mbcssm import EUCTWSMModel class EUCTWProber(MultiByteCharSetProber): def __init__(self): MultiByteCharSetProber.__init__(self) self._mCodingSM = CodingStateMachine(EUCTWSMModel) self._mDistributionAnalyzer = EUCTWDistributionAnalysis() self.reset() def get_charset_name(self): return "EUC-TW"
apache-2.0