repo_name
stringlengths
5
100
path
stringlengths
4
299
copies
stringlengths
1
5
size
stringlengths
4
7
content
stringlengths
666
1.03M
license
stringclasses
15 values
hash
int64
-9,223,351,895,964,839,000
9,223,297,778B
line_mean
float64
3.17
100
line_max
int64
7
1k
alpha_frac
float64
0.25
0.98
autogenerated
bool
1 class
ahmedbodi/AutobahnPython
examples/asyncio/websocket/echo/client_coroutines.py
13
2044
############################################################################### ## ## Copyright (C) 2013-2014 Tavendo GmbH ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ############################################################################### from autobahn.asyncio.websocket import WebSocketClientProtocol, \ WebSocketClientFactory import asyncio class MyClientProtocol(WebSocketClientProtocol): def onConnect(self, response): print("Server connected: {0}".format(response.peer)) @asyncio.coroutine def onOpen(self): print("WebSocket connection open.") ## start sending messages every second .. while True: self.sendMessage(u"Hello, world!".encode('utf8')) self.sendMessage(b"\x00\x01\x03\x04", isBinary = True) yield from asyncio.sleep(1) def onMessage(self, payload, isBinary): if isBinary: print("Binary message received: {0} bytes".format(len(payload))) else: print("Text message received: {0}".format(payload.decode('utf8'))) def onClose(self, wasClean, code, reason): print("WebSocket connection closed: {0}".format(reason)) if __name__ == '__main__': import asyncio factory = WebSocketClientFactory("ws://localhost:9000", debug = False) factory.protocol = MyClientProtocol loop = asyncio.get_event_loop() coro = loop.create_connection(factory, '127.0.0.1', 9000) loop.run_until_complete(coro) loop.run_forever() loop.close()
apache-2.0
7,822,061,744,094,950,000
31.444444
79
0.623288
false
ifduyue/django
django/core/checks/registry.py
13
3108
from itertools import chain from django.utils.itercompat import is_iterable class Tags: """ Built-in tags for internal checks. """ admin = 'admin' caches = 'caches' compatibility = 'compatibility' database = 'database' models = 'models' security = 'security' signals = 'signals' templates = 'templates' urls = 'urls' class CheckRegistry: def __init__(self): self.registered_checks = set() self.deployment_checks = set() def register(self, check=None, *tags, **kwargs): """ Can be used as a function or a decorator. Register given function `f` labeled with given `tags`. The function should receive **kwargs and return list of Errors and Warnings. Example:: registry = CheckRegistry() @registry.register('mytag', 'anothertag') def my_check(apps, **kwargs): # ... perform checks and collect `errors` ... return errors # or registry.register(my_check, 'mytag', 'anothertag') """ kwargs.setdefault('deploy', False) def inner(check): check.tags = tags checks = self.deployment_checks if kwargs['deploy'] else self.registered_checks checks.add(check) return check if callable(check): return inner(check) else: if check: tags += (check, ) return inner def run_checks(self, app_configs=None, tags=None, include_deployment_checks=False): """ Run all registered checks and return list of Errors and Warnings. """ errors = [] checks = self.get_checks(include_deployment_checks) if tags is not None: checks = [check for check in checks if not set(check.tags).isdisjoint(tags)] else: # By default, 'database'-tagged checks are not run as they do more # than mere static code analysis. checks = [check for check in checks if Tags.database not in check.tags] for check in checks: new_errors = check(app_configs=app_configs) assert is_iterable(new_errors), ( "The function %r did not return a list. All functions registered " "with the checks registry must return a list." % check) errors.extend(new_errors) return errors def tag_exists(self, tag, include_deployment_checks=False): return tag in self.tags_available(include_deployment_checks) def tags_available(self, deployment_checks=False): return set(chain.from_iterable( check.tags for check in self.get_checks(deployment_checks) )) def get_checks(self, include_deployment_checks=False): checks = list(self.registered_checks) if include_deployment_checks: checks.extend(self.deployment_checks) return checks registry = CheckRegistry() register = registry.register run_checks = registry.run_checks tag_exists = registry.tag_exists
bsd-3-clause
-2,035,686,896,372,967,700
30.714286
91
0.602317
false
kmike/scikit-learn
sklearn/utils/__init__.py
3
10094
""" The :mod:`sklearn.utils` module includes various utilites. """ from collections import Sequence import numpy as np from scipy.sparse import issparse import warnings from .murmurhash import murmurhash3_32 from .validation import (as_float_array, check_arrays, safe_asarray, assert_all_finite, array2d, atleast2d_or_csc, atleast2d_or_csr, warn_if_not_float, check_random_state) from .class_weight import compute_class_weight __all__ = ["murmurhash3_32", "as_float_array", "check_arrays", "safe_asarray", "assert_all_finite", "array2d", "atleast2d_or_csc", "atleast2d_or_csr", "warn_if_not_float", "check_random_state", "compute_class_weight"] # Make sure that DeprecationWarning get printed warnings.simplefilter("always", DeprecationWarning) class deprecated(object): """Decorator to mark a function or class as deprecated. Issue a warning when the function is called/the class is instantiated and adds a warning to the docstring. The optional extra argument will be appended to the deprecation message and the docstring. Note: to use this with the default value for extra, put in an empty of parentheses: >>> from sklearn.utils import deprecated >>> deprecated() # doctest: +ELLIPSIS <sklearn.utils.deprecated object at ...> >>> @deprecated() ... def some_function(): pass """ # Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary, # but with many changes. def __init__(self, extra=''): """ Parameters ---------- extra: string to be added to the deprecation messages """ self.extra = extra def __call__(self, obj): if isinstance(obj, type): return self._decorate_class(obj) else: return self._decorate_fun(obj) def _decorate_class(self, cls): msg = "Class %s is deprecated" % cls.__name__ if self.extra: msg += "; %s" % self.extra # FIXME: we should probably reset __new__ for full generality init = cls.__init__ def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return init(*args, **kwargs) cls.__init__ = wrapped wrapped.__name__ = '__init__' wrapped.__doc__ = self._update_doc(init.__doc__) wrapped.deprecated_original = init return cls def _decorate_fun(self, fun): """Decorate function fun""" msg = "Function %s is deprecated" % fun.__name__ if self.extra: msg += "; %s" % self.extra def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return fun(*args, **kwargs) wrapped.__name__ = fun.__name__ wrapped.__dict__ = fun.__dict__ wrapped.__doc__ = self._update_doc(fun.__doc__) return wrapped def _update_doc(self, olddoc): newdoc = "DEPRECATED" if self.extra: newdoc = "%s: %s" % (newdoc, self.extra) if olddoc: newdoc = "%s\n\n%s" % (newdoc, olddoc) return newdoc def safe_mask(X, mask): """Return a mask which is safe to use on X. Parameters ---------- X : {array-like, sparse matrix} Data on which to apply mask. mask: array Mask to be used on X. Returns ------- mask """ mask = np.asanyarray(mask) if np.issubdtype(mask.dtype, np.int): return mask if hasattr(X, "toarray"): ind = np.arange(mask.shape[0]) mask = ind[mask] return mask def resample(*arrays, **options): """Resample arrays or sparse matrices in a consistent way The default strategy implements one step of the bootstrapping procedure. Parameters ---------- `*arrays` : sequence of arrays or scipy.sparse matrices with same shape[0] replace : boolean, True by default Implements resampling with replacement. If False, this will implement (sliced) random permutations. n_samples : int, None by default Number of samples to generate. If left to None this is automatically set to the first dimension of the arrays. random_state : int or RandomState instance Control the shuffling for reproducible behavior. Returns ------- Sequence of resampled views of the collections. The original arrays are not impacted. Examples -------- It is possible to mix sparse and dense arrays in the same run:: >>> X = [[1., 0.], [2., 1.], [0., 0.]] >>> y = np.array([0, 1, 2]) >>> from scipy.sparse import coo_matrix >>> X_sparse = coo_matrix(X) >>> from sklearn.utils import resample >>> X, X_sparse, y = resample(X, X_sparse, y, random_state=0) >>> X array([[ 1., 0.], [ 2., 1.], [ 1., 0.]]) >>> X_sparse # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE <3x2 sparse matrix of type '<... 'numpy.float64'>' with 4 stored elements in Compressed Sparse Row format> >>> X_sparse.toarray() array([[ 1., 0.], [ 2., 1.], [ 1., 0.]]) >>> y array([0, 1, 0]) >>> resample(y, n_samples=2, random_state=0) array([0, 1]) See also -------- :class:`sklearn.cross_validation.Bootstrap` :func:`sklearn.utils.shuffle` """ random_state = check_random_state(options.pop('random_state', None)) replace = options.pop('replace', True) max_n_samples = options.pop('n_samples', None) if options: raise ValueError("Unexpected kw arguments: %r" % options.keys()) if len(arrays) == 0: return None first = arrays[0] n_samples = first.shape[0] if hasattr(first, 'shape') else len(first) if max_n_samples is None: max_n_samples = n_samples if max_n_samples > n_samples: raise ValueError("Cannot sample %d out of arrays with dim %d" % ( max_n_samples, n_samples)) arrays = check_arrays(*arrays, sparse_format='csr') if replace: indices = random_state.randint(0, n_samples, size=(max_n_samples,)) else: indices = np.arange(n_samples) random_state.shuffle(indices) indices = indices[:max_n_samples] resampled_arrays = [] for array in arrays: array = array[indices] resampled_arrays.append(array) if len(resampled_arrays) == 1: # syntactic sugar for the unit argument case return resampled_arrays[0] else: return resampled_arrays def shuffle(*arrays, **options): """Shuffle arrays or sparse matrices in a consistent way This is a convenience alias to ``resample(*arrays, replace=False)`` to do random permutations of the collections. Parameters ---------- `*arrays` : sequence of arrays or scipy.sparse matrices with same shape[0] random_state : int or RandomState instance Control the shuffling for reproducible behavior. n_samples : int, None by default Number of samples to generate. If left to None this is automatically set to the first dimension of the arrays. Returns ------- Sequence of shuffled views of the collections. The original arrays are not impacted. Examples -------- It is possible to mix sparse and dense arrays in the same run:: >>> X = [[1., 0.], [2., 1.], [0., 0.]] >>> y = np.array([0, 1, 2]) >>> from scipy.sparse import coo_matrix >>> X_sparse = coo_matrix(X) >>> from sklearn.utils import shuffle >>> X, X_sparse, y = shuffle(X, X_sparse, y, random_state=0) >>> X array([[ 0., 0.], [ 2., 1.], [ 1., 0.]]) >>> X_sparse # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE <3x2 sparse matrix of type '<... 'numpy.float64'>' with 3 stored elements in Compressed Sparse Row format> >>> X_sparse.toarray() array([[ 0., 0.], [ 2., 1.], [ 1., 0.]]) >>> y array([2, 1, 0]) >>> shuffle(y, n_samples=2, random_state=0) array([0, 1]) See also -------- :func:`sklearn.utils.resample` """ options['replace'] = False return resample(*arrays, **options) def safe_sqr(X, copy=True): """Element wise squaring of array-likes and sparse matrices. Parameters ---------- X : array like, matrix, sparse matrix Returns ------- X ** 2 : element wise square """ X = safe_asarray(X) if issparse(X): if copy: X = X.copy() X.data **= 2 else: if copy: X = X ** 2 else: X **= 2 return X def gen_even_slices(n, n_packs): """Generator to create n_packs slices going up to n. Examples -------- >>> from sklearn.utils import gen_even_slices >>> list(gen_even_slices(10, 1)) [slice(0, 10, None)] >>> list(gen_even_slices(10, 10)) #doctest: +ELLIPSIS [slice(0, 1, None), slice(1, 2, None), ..., slice(9, 10, None)] >>> list(gen_even_slices(10, 5)) #doctest: +ELLIPSIS [slice(0, 2, None), slice(2, 4, None), ..., slice(8, 10, None)] >>> list(gen_even_slices(10, 3)) [slice(0, 4, None), slice(4, 7, None), slice(7, 10, None)] """ start = 0 for pack_num in range(n_packs): this_n = n // n_packs if pack_num < n % n_packs: this_n += 1 if this_n > 0: end = start + this_n yield slice(start, end, None) start = end def tosequence(x): """Cast iterable x to a Sequence, avoiding a copy if possible.""" if isinstance(x, np.ndarray): return np.asarray(x) elif isinstance(x, Sequence): return x else: return list(x) class ConvergenceWarning(Warning): "Custom warning to capture convergence problems"
bsd-3-clause
2,334,709,577,611,160,600
26.883978
79
0.56806
false
houlixin/BBB-TISDK
linux-devkit/sysroots/i686-arago-linux/usr/lib/python2.7/encodings/cp1250.py
593
13942
""" Python Character Mapping Codec cp1250 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1250.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp1250', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( u'\x00' # 0x00 -> NULL u'\x01' # 0x01 -> START OF HEADING u'\x02' # 0x02 -> START OF TEXT u'\x03' # 0x03 -> END OF TEXT u'\x04' # 0x04 -> END OF TRANSMISSION u'\x05' # 0x05 -> ENQUIRY u'\x06' # 0x06 -> ACKNOWLEDGE u'\x07' # 0x07 -> BELL u'\x08' # 0x08 -> BACKSPACE u'\t' # 0x09 -> HORIZONTAL TABULATION u'\n' # 0x0A -> LINE FEED u'\x0b' # 0x0B -> VERTICAL TABULATION u'\x0c' # 0x0C -> FORM FEED u'\r' # 0x0D -> CARRIAGE RETURN u'\x0e' # 0x0E -> SHIFT OUT u'\x0f' # 0x0F -> SHIFT IN u'\x10' # 0x10 -> DATA LINK ESCAPE u'\x11' # 0x11 -> DEVICE CONTROL ONE u'\x12' # 0x12 -> DEVICE CONTROL TWO u'\x13' # 0x13 -> DEVICE CONTROL THREE u'\x14' # 0x14 -> DEVICE CONTROL FOUR u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE u'\x16' # 0x16 -> SYNCHRONOUS IDLE u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK u'\x18' # 0x18 -> CANCEL u'\x19' # 0x19 -> END OF MEDIUM u'\x1a' # 0x1A -> SUBSTITUTE u'\x1b' # 0x1B -> ESCAPE u'\x1c' # 0x1C -> FILE SEPARATOR u'\x1d' # 0x1D -> GROUP SEPARATOR u'\x1e' # 0x1E -> RECORD SEPARATOR u'\x1f' # 0x1F -> UNIT SEPARATOR u' ' # 0x20 -> SPACE u'!' # 0x21 -> EXCLAMATION MARK u'"' # 0x22 -> QUOTATION MARK u'#' # 0x23 -> NUMBER SIGN u'$' # 0x24 -> DOLLAR SIGN u'%' # 0x25 -> PERCENT SIGN u'&' # 0x26 -> AMPERSAND u"'" # 0x27 -> APOSTROPHE u'(' # 0x28 -> LEFT PARENTHESIS u')' # 0x29 -> RIGHT PARENTHESIS u'*' # 0x2A -> ASTERISK u'+' # 0x2B -> PLUS SIGN u',' # 0x2C -> COMMA u'-' # 0x2D -> HYPHEN-MINUS u'.' # 0x2E -> FULL STOP u'/' # 0x2F -> SOLIDUS u'0' # 0x30 -> DIGIT ZERO u'1' # 0x31 -> DIGIT ONE u'2' # 0x32 -> DIGIT TWO u'3' # 0x33 -> DIGIT THREE u'4' # 0x34 -> DIGIT FOUR u'5' # 0x35 -> DIGIT FIVE u'6' # 0x36 -> DIGIT SIX u'7' # 0x37 -> DIGIT SEVEN u'8' # 0x38 -> DIGIT EIGHT u'9' # 0x39 -> DIGIT NINE u':' # 0x3A -> COLON u';' # 0x3B -> SEMICOLON u'<' # 0x3C -> LESS-THAN SIGN u'=' # 0x3D -> EQUALS SIGN u'>' # 0x3E -> GREATER-THAN SIGN u'?' # 0x3F -> QUESTION MARK u'@' # 0x40 -> COMMERCIAL AT u'A' # 0x41 -> LATIN CAPITAL LETTER A u'B' # 0x42 -> LATIN CAPITAL LETTER B u'C' # 0x43 -> LATIN CAPITAL LETTER C u'D' # 0x44 -> LATIN CAPITAL LETTER D u'E' # 0x45 -> LATIN CAPITAL LETTER E u'F' # 0x46 -> LATIN CAPITAL LETTER F u'G' # 0x47 -> LATIN CAPITAL LETTER G u'H' # 0x48 -> LATIN CAPITAL LETTER H u'I' # 0x49 -> LATIN CAPITAL LETTER I u'J' # 0x4A -> LATIN CAPITAL LETTER J u'K' # 0x4B -> LATIN CAPITAL LETTER K u'L' # 0x4C -> LATIN CAPITAL LETTER L u'M' # 0x4D -> LATIN CAPITAL LETTER M u'N' # 0x4E -> LATIN CAPITAL LETTER N u'O' # 0x4F -> LATIN CAPITAL LETTER O u'P' # 0x50 -> LATIN CAPITAL LETTER P u'Q' # 0x51 -> LATIN CAPITAL LETTER Q u'R' # 0x52 -> LATIN CAPITAL LETTER R u'S' # 0x53 -> LATIN CAPITAL LETTER S u'T' # 0x54 -> LATIN CAPITAL LETTER T u'U' # 0x55 -> LATIN CAPITAL LETTER U u'V' # 0x56 -> LATIN CAPITAL LETTER V u'W' # 0x57 -> LATIN CAPITAL LETTER W u'X' # 0x58 -> LATIN CAPITAL LETTER X u'Y' # 0x59 -> LATIN CAPITAL LETTER Y u'Z' # 0x5A -> LATIN CAPITAL LETTER Z u'[' # 0x5B -> LEFT SQUARE BRACKET u'\\' # 0x5C -> REVERSE SOLIDUS u']' # 0x5D -> RIGHT SQUARE BRACKET u'^' # 0x5E -> CIRCUMFLEX ACCENT u'_' # 0x5F -> LOW LINE u'`' # 0x60 -> GRAVE ACCENT u'a' # 0x61 -> LATIN SMALL LETTER A u'b' # 0x62 -> LATIN SMALL LETTER B u'c' # 0x63 -> LATIN SMALL LETTER C u'd' # 0x64 -> LATIN SMALL LETTER D u'e' # 0x65 -> LATIN SMALL LETTER E u'f' # 0x66 -> LATIN SMALL LETTER F u'g' # 0x67 -> LATIN SMALL LETTER G u'h' # 0x68 -> LATIN SMALL LETTER H u'i' # 0x69 -> LATIN SMALL LETTER I u'j' # 0x6A -> LATIN SMALL LETTER J u'k' # 0x6B -> LATIN SMALL LETTER K u'l' # 0x6C -> LATIN SMALL LETTER L u'm' # 0x6D -> LATIN SMALL LETTER M u'n' # 0x6E -> LATIN SMALL LETTER N u'o' # 0x6F -> LATIN SMALL LETTER O u'p' # 0x70 -> LATIN SMALL LETTER P u'q' # 0x71 -> LATIN SMALL LETTER Q u'r' # 0x72 -> LATIN SMALL LETTER R u's' # 0x73 -> LATIN SMALL LETTER S u't' # 0x74 -> LATIN SMALL LETTER T u'u' # 0x75 -> LATIN SMALL LETTER U u'v' # 0x76 -> LATIN SMALL LETTER V u'w' # 0x77 -> LATIN SMALL LETTER W u'x' # 0x78 -> LATIN SMALL LETTER X u'y' # 0x79 -> LATIN SMALL LETTER Y u'z' # 0x7A -> LATIN SMALL LETTER Z u'{' # 0x7B -> LEFT CURLY BRACKET u'|' # 0x7C -> VERTICAL LINE u'}' # 0x7D -> RIGHT CURLY BRACKET u'~' # 0x7E -> TILDE u'\x7f' # 0x7F -> DELETE u'\u20ac' # 0x80 -> EURO SIGN u'\ufffe' # 0x81 -> UNDEFINED u'\u201a' # 0x82 -> SINGLE LOW-9 QUOTATION MARK u'\ufffe' # 0x83 -> UNDEFINED u'\u201e' # 0x84 -> DOUBLE LOW-9 QUOTATION MARK u'\u2026' # 0x85 -> HORIZONTAL ELLIPSIS u'\u2020' # 0x86 -> DAGGER u'\u2021' # 0x87 -> DOUBLE DAGGER u'\ufffe' # 0x88 -> UNDEFINED u'\u2030' # 0x89 -> PER MILLE SIGN u'\u0160' # 0x8A -> LATIN CAPITAL LETTER S WITH CARON u'\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK u'\u015a' # 0x8C -> LATIN CAPITAL LETTER S WITH ACUTE u'\u0164' # 0x8D -> LATIN CAPITAL LETTER T WITH CARON u'\u017d' # 0x8E -> LATIN CAPITAL LETTER Z WITH CARON u'\u0179' # 0x8F -> LATIN CAPITAL LETTER Z WITH ACUTE u'\ufffe' # 0x90 -> UNDEFINED u'\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK u'\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK u'\u201c' # 0x93 -> LEFT DOUBLE QUOTATION MARK u'\u201d' # 0x94 -> RIGHT DOUBLE QUOTATION MARK u'\u2022' # 0x95 -> BULLET u'\u2013' # 0x96 -> EN DASH u'\u2014' # 0x97 -> EM DASH u'\ufffe' # 0x98 -> UNDEFINED u'\u2122' # 0x99 -> TRADE MARK SIGN u'\u0161' # 0x9A -> LATIN SMALL LETTER S WITH CARON u'\u203a' # 0x9B -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK u'\u015b' # 0x9C -> LATIN SMALL LETTER S WITH ACUTE u'\u0165' # 0x9D -> LATIN SMALL LETTER T WITH CARON u'\u017e' # 0x9E -> LATIN SMALL LETTER Z WITH CARON u'\u017a' # 0x9F -> LATIN SMALL LETTER Z WITH ACUTE u'\xa0' # 0xA0 -> NO-BREAK SPACE u'\u02c7' # 0xA1 -> CARON u'\u02d8' # 0xA2 -> BREVE u'\u0141' # 0xA3 -> LATIN CAPITAL LETTER L WITH STROKE u'\xa4' # 0xA4 -> CURRENCY SIGN u'\u0104' # 0xA5 -> LATIN CAPITAL LETTER A WITH OGONEK u'\xa6' # 0xA6 -> BROKEN BAR u'\xa7' # 0xA7 -> SECTION SIGN u'\xa8' # 0xA8 -> DIAERESIS u'\xa9' # 0xA9 -> COPYRIGHT SIGN u'\u015e' # 0xAA -> LATIN CAPITAL LETTER S WITH CEDILLA u'\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xac' # 0xAC -> NOT SIGN u'\xad' # 0xAD -> SOFT HYPHEN u'\xae' # 0xAE -> REGISTERED SIGN u'\u017b' # 0xAF -> LATIN CAPITAL LETTER Z WITH DOT ABOVE u'\xb0' # 0xB0 -> DEGREE SIGN u'\xb1' # 0xB1 -> PLUS-MINUS SIGN u'\u02db' # 0xB2 -> OGONEK u'\u0142' # 0xB3 -> LATIN SMALL LETTER L WITH STROKE u'\xb4' # 0xB4 -> ACUTE ACCENT u'\xb5' # 0xB5 -> MICRO SIGN u'\xb6' # 0xB6 -> PILCROW SIGN u'\xb7' # 0xB7 -> MIDDLE DOT u'\xb8' # 0xB8 -> CEDILLA u'\u0105' # 0xB9 -> LATIN SMALL LETTER A WITH OGONEK u'\u015f' # 0xBA -> LATIN SMALL LETTER S WITH CEDILLA u'\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK u'\u013d' # 0xBC -> LATIN CAPITAL LETTER L WITH CARON u'\u02dd' # 0xBD -> DOUBLE ACUTE ACCENT u'\u013e' # 0xBE -> LATIN SMALL LETTER L WITH CARON u'\u017c' # 0xBF -> LATIN SMALL LETTER Z WITH DOT ABOVE u'\u0154' # 0xC0 -> LATIN CAPITAL LETTER R WITH ACUTE u'\xc1' # 0xC1 -> LATIN CAPITAL LETTER A WITH ACUTE u'\xc2' # 0xC2 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX u'\u0102' # 0xC3 -> LATIN CAPITAL LETTER A WITH BREVE u'\xc4' # 0xC4 -> LATIN CAPITAL LETTER A WITH DIAERESIS u'\u0139' # 0xC5 -> LATIN CAPITAL LETTER L WITH ACUTE u'\u0106' # 0xC6 -> LATIN CAPITAL LETTER C WITH ACUTE u'\xc7' # 0xC7 -> LATIN CAPITAL LETTER C WITH CEDILLA u'\u010c' # 0xC8 -> LATIN CAPITAL LETTER C WITH CARON u'\xc9' # 0xC9 -> LATIN CAPITAL LETTER E WITH ACUTE u'\u0118' # 0xCA -> LATIN CAPITAL LETTER E WITH OGONEK u'\xcb' # 0xCB -> LATIN CAPITAL LETTER E WITH DIAERESIS u'\u011a' # 0xCC -> LATIN CAPITAL LETTER E WITH CARON u'\xcd' # 0xCD -> LATIN CAPITAL LETTER I WITH ACUTE u'\xce' # 0xCE -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX u'\u010e' # 0xCF -> LATIN CAPITAL LETTER D WITH CARON u'\u0110' # 0xD0 -> LATIN CAPITAL LETTER D WITH STROKE u'\u0143' # 0xD1 -> LATIN CAPITAL LETTER N WITH ACUTE u'\u0147' # 0xD2 -> LATIN CAPITAL LETTER N WITH CARON u'\xd3' # 0xD3 -> LATIN CAPITAL LETTER O WITH ACUTE u'\xd4' # 0xD4 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX u'\u0150' # 0xD5 -> LATIN CAPITAL LETTER O WITH DOUBLE ACUTE u'\xd6' # 0xD6 -> LATIN CAPITAL LETTER O WITH DIAERESIS u'\xd7' # 0xD7 -> MULTIPLICATION SIGN u'\u0158' # 0xD8 -> LATIN CAPITAL LETTER R WITH CARON u'\u016e' # 0xD9 -> LATIN CAPITAL LETTER U WITH RING ABOVE u'\xda' # 0xDA -> LATIN CAPITAL LETTER U WITH ACUTE u'\u0170' # 0xDB -> LATIN CAPITAL LETTER U WITH DOUBLE ACUTE u'\xdc' # 0xDC -> LATIN CAPITAL LETTER U WITH DIAERESIS u'\xdd' # 0xDD -> LATIN CAPITAL LETTER Y WITH ACUTE u'\u0162' # 0xDE -> LATIN CAPITAL LETTER T WITH CEDILLA u'\xdf' # 0xDF -> LATIN SMALL LETTER SHARP S u'\u0155' # 0xE0 -> LATIN SMALL LETTER R WITH ACUTE u'\xe1' # 0xE1 -> LATIN SMALL LETTER A WITH ACUTE u'\xe2' # 0xE2 -> LATIN SMALL LETTER A WITH CIRCUMFLEX u'\u0103' # 0xE3 -> LATIN SMALL LETTER A WITH BREVE u'\xe4' # 0xE4 -> LATIN SMALL LETTER A WITH DIAERESIS u'\u013a' # 0xE5 -> LATIN SMALL LETTER L WITH ACUTE u'\u0107' # 0xE6 -> LATIN SMALL LETTER C WITH ACUTE u'\xe7' # 0xE7 -> LATIN SMALL LETTER C WITH CEDILLA u'\u010d' # 0xE8 -> LATIN SMALL LETTER C WITH CARON u'\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE u'\u0119' # 0xEA -> LATIN SMALL LETTER E WITH OGONEK u'\xeb' # 0xEB -> LATIN SMALL LETTER E WITH DIAERESIS u'\u011b' # 0xEC -> LATIN SMALL LETTER E WITH CARON u'\xed' # 0xED -> LATIN SMALL LETTER I WITH ACUTE u'\xee' # 0xEE -> LATIN SMALL LETTER I WITH CIRCUMFLEX u'\u010f' # 0xEF -> LATIN SMALL LETTER D WITH CARON u'\u0111' # 0xF0 -> LATIN SMALL LETTER D WITH STROKE u'\u0144' # 0xF1 -> LATIN SMALL LETTER N WITH ACUTE u'\u0148' # 0xF2 -> LATIN SMALL LETTER N WITH CARON u'\xf3' # 0xF3 -> LATIN SMALL LETTER O WITH ACUTE u'\xf4' # 0xF4 -> LATIN SMALL LETTER O WITH CIRCUMFLEX u'\u0151' # 0xF5 -> LATIN SMALL LETTER O WITH DOUBLE ACUTE u'\xf6' # 0xF6 -> LATIN SMALL LETTER O WITH DIAERESIS u'\xf7' # 0xF7 -> DIVISION SIGN u'\u0159' # 0xF8 -> LATIN SMALL LETTER R WITH CARON u'\u016f' # 0xF9 -> LATIN SMALL LETTER U WITH RING ABOVE u'\xfa' # 0xFA -> LATIN SMALL LETTER U WITH ACUTE u'\u0171' # 0xFB -> LATIN SMALL LETTER U WITH DOUBLE ACUTE u'\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS u'\xfd' # 0xFD -> LATIN SMALL LETTER Y WITH ACUTE u'\u0163' # 0xFE -> LATIN SMALL LETTER T WITH CEDILLA u'\u02d9' # 0xFF -> DOT ABOVE ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
gpl-2.0
-6,356,832,018,515,183,000
44.413681
119
0.550351
false
dataxu/ansible
lib/ansible/modules/system/kernel_blacklist.py
125
4009
#!/usr/bin/python # encoding: utf-8 -*- # Copyright: (c) 2013, Matthias Vogelgesang <matthias.vogelgesang@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: kernel_blacklist author: - Matthias Vogelgesang (@matze) version_added: '1.4' short_description: Blacklist kernel modules description: - Add or remove kernel modules from blacklist. options: name: description: - Name of kernel module to black- or whitelist. required: true state: description: - Whether the module should be present in the blacklist or absent. choices: [ absent, present ] default: present blacklist_file: description: - If specified, use this blacklist file instead of C(/etc/modprobe.d/blacklist-ansible.conf). ''' EXAMPLES = ''' - name: Blacklist the nouveau driver module kernel_blacklist: name: nouveau state: present ''' import os import re from ansible.module_utils.basic import AnsibleModule class Blacklist(object): def __init__(self, module, filename, checkmode): self.filename = filename self.module = module self.checkmode = checkmode def create_file(self): if not self.checkmode and not os.path.exists(self.filename): open(self.filename, 'a').close() return True elif self.checkmode and not os.path.exists(self.filename): self.filename = os.devnull return True else: return False def get_pattern(self): return r'^blacklist\s*' + self.module + '$' def readlines(self): f = open(self.filename, 'r') lines = f.readlines() f.close() return lines def module_listed(self): lines = self.readlines() pattern = self.get_pattern() for line in lines: stripped = line.strip() if stripped.startswith('#'): continue if re.match(pattern, stripped): return True return False def remove_module(self): lines = self.readlines() pattern = self.get_pattern() if self.checkmode: f = open(os.devnull, 'w') else: f = open(self.filename, 'w') for line in lines: if not re.match(pattern, line.strip()): f.write(line) f.close() def add_module(self): if self.checkmode: f = open(os.devnull, 'a') else: f = open(self.filename, 'a') f.write('blacklist %s\n' % self.module) f.close() def main(): module = AnsibleModule( argument_spec=dict( name=dict(type='str', required=True), state=dict(type='str', default='present', choices=['absent', 'present']), blacklist_file=dict(type='str') ), supports_check_mode=True, ) args = dict(changed=False, failed=False, name=module.params['name'], state=module.params['state']) filename = '/etc/modprobe.d/blacklist-ansible.conf' if module.params['blacklist_file']: filename = module.params['blacklist_file'] blacklist = Blacklist(args['name'], filename, module.check_mode) if blacklist.create_file(): args['changed'] = True else: args['changed'] = False if blacklist.module_listed(): if args['state'] == 'absent': blacklist.remove_module() args['changed'] = True else: if args['state'] == 'present': blacklist.add_module() args['changed'] = True module.exit_json(**args) if __name__ == '__main__': main()
gpl-3.0
8,498,771,084,445,727,000
24.864516
92
0.575206
false
163gal/Time-Line
libs_arm/wx/_controls.py
2
332374
# This file was created automatically by SWIG 1.3.29. # Don't modify this file, modify the SWIG interface instead. import _controls_ import new new_instancemethod = new.instancemethod def _swig_setattr_nondynamic(self,class_type,name,value,static=1): if (name == "thisown"): return self.this.own(value) if (name == "this"): if type(value).__name__ == 'PySwigObject': self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name,None) if method: return method(self,value) if (not static) or hasattr(self,name): self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self,class_type,name,value): return _swig_setattr_nondynamic(self,class_type,name,value,0) def _swig_getattr(self,class_type,name): if (name == "thisown"): return self.this.own() method = class_type.__swig_getmethods__.get(name,None) if method: return method(self) raise AttributeError,name def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) import types try: _object = types.ObjectType _newclass = 1 except AttributeError: class _object : pass _newclass = 0 del types def _swig_setattr_nondynamic_method(set): def set_attr(self,name,value): if (name == "thisown"): return self.this.own(value) if hasattr(self,name) or (name == "this"): set(self,name,value) else: raise AttributeError("You cannot add attributes to %s" % self) return set_attr import _core wx = _core #--------------------------------------------------------------------------- BU_LEFT = _controls_.BU_LEFT BU_TOP = _controls_.BU_TOP BU_RIGHT = _controls_.BU_RIGHT BU_BOTTOM = _controls_.BU_BOTTOM BU_ALIGN_MASK = _controls_.BU_ALIGN_MASK BU_EXACTFIT = _controls_.BU_EXACTFIT BU_AUTODRAW = _controls_.BU_AUTODRAW BU_NOTEXT = _controls_.BU_NOTEXT class AnyButton(_core.Control): """Proxy of C++ AnyButton class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self): raise AttributeError, "No constructor defined" __repr__ = _swig_repr def SetBitmap(*args, **kwargs): """SetBitmap(self, Bitmap bitmap, int dir=LEFT)""" return _controls_.AnyButton_SetBitmap(*args, **kwargs) def GetBitmap(*args, **kwargs): """GetBitmap(self) -> Bitmap""" return _controls_.AnyButton_GetBitmap(*args, **kwargs) Bitmap = property(GetBitmap,SetBitmap) def SetBitmapLabel(*args, **kwargs): """SetBitmapLabel(self, Bitmap bitmap)""" return _controls_.AnyButton_SetBitmapLabel(*args, **kwargs) def SetBitmapPressed(*args, **kwargs): """SetBitmapPressed(self, Bitmap bitmap)""" return _controls_.AnyButton_SetBitmapPressed(*args, **kwargs) def SetBitmapDisabled(*args, **kwargs): """SetBitmapDisabled(self, Bitmap bitmap)""" return _controls_.AnyButton_SetBitmapDisabled(*args, **kwargs) def SetBitmapCurrent(*args, **kwargs): """SetBitmapCurrent(self, Bitmap bitmap)""" return _controls_.AnyButton_SetBitmapCurrent(*args, **kwargs) def SetBitmapFocus(*args, **kwargs): """SetBitmapFocus(self, Bitmap bitmap)""" return _controls_.AnyButton_SetBitmapFocus(*args, **kwargs) def GetBitmapLabel(*args, **kwargs): """GetBitmapLabel(self) -> Bitmap""" return _controls_.AnyButton_GetBitmapLabel(*args, **kwargs) def GetBitmapPressed(*args, **kwargs): """GetBitmapPressed(self) -> Bitmap""" return _controls_.AnyButton_GetBitmapPressed(*args, **kwargs) def GetBitmapDisabled(*args, **kwargs): """GetBitmapDisabled(self) -> Bitmap""" return _controls_.AnyButton_GetBitmapDisabled(*args, **kwargs) def GetBitmapCurrent(*args, **kwargs): """GetBitmapCurrent(self) -> Bitmap""" return _controls_.AnyButton_GetBitmapCurrent(*args, **kwargs) def GetBitmapFocus(*args, **kwargs): """GetBitmapFocus(self) -> Bitmap""" return _controls_.AnyButton_GetBitmapFocus(*args, **kwargs) BitmapLabel = property(GetBitmapLabel,SetBitmapLabel) BitmapPressed = property(GetBitmapPressed,SetBitmapPressed) BitmapDisabled = property(GetBitmapDisabled,SetBitmapDisabled) BitmapCurrent = property(GetBitmapCurrent,SetBitmapCurrent) BitmapFocus = property(GetBitmapFocus,SetBitmapFocus) def GetBitmapSelected(*args, **kwargs): """GetBitmapSelected(self) -> Bitmap""" return _controls_.AnyButton_GetBitmapSelected(*args, **kwargs) def GetBitmapHover(*args, **kwargs): """GetBitmapHover(self) -> Bitmap""" return _controls_.AnyButton_GetBitmapHover(*args, **kwargs) def SetBitmapSelected(*args, **kwargs): """SetBitmapSelected(self, Bitmap bitmap)""" return _controls_.AnyButton_SetBitmapSelected(*args, **kwargs) def SetBitmapHover(*args, **kwargs): """SetBitmapHover(self, Bitmap bitmap)""" return _controls_.AnyButton_SetBitmapHover(*args, **kwargs) BitmapSelected = property(GetBitmapSelected,SetBitmapSelected) BitmapHover = property(GetBitmapHover,SetBitmapHover) def SetBitmapMargins(*args): """ SetBitmapMargins(self, int x, int y) SetBitmapMargins(self, Size sz) """ return _controls_.AnyButton_SetBitmapMargins(*args) def GetBitmapMargins(*args, **kwargs): """GetBitmapMargins(self) -> Size""" return _controls_.AnyButton_GetBitmapMargins(*args, **kwargs) BitmapMargins = property(GetBitmapMargins,SetBitmapMargins) def SetBitmapPosition(*args, **kwargs): """SetBitmapPosition(self, int dir)""" return _controls_.AnyButton_SetBitmapPosition(*args, **kwargs) def DontShowLabel(*args, **kwargs): """DontShowLabel(self) -> bool""" return _controls_.AnyButton_DontShowLabel(*args, **kwargs) def ShowsLabel(*args, **kwargs): """ShowsLabel(self) -> bool""" return _controls_.AnyButton_ShowsLabel(*args, **kwargs) _controls_.AnyButton_swigregister(AnyButton) cvar = _controls_.cvar ButtonNameStr = cvar.ButtonNameStr class Button(AnyButton): """ A button is a control that contains a text string, and is one of the most common elements of a GUI. It may be placed on a dialog box or panel, or indeed almost any other window. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=ButtonNameStr) -> Button Create and show a button. The preferred way to create standard buttons is to use a standard ID and an empty label. In this case wxWigets will automatically use a stock label that corresponds to the ID given. These labels may vary across platforms as the platform itself will provide the label if possible. In addition, the button will be decorated with stock icons under GTK+ 2. """ _controls_.Button_swiginit(self,_controls_.new_Button(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=ButtonNameStr) -> bool Acutally create the GUI Button for 2-phase creation. """ return _controls_.Button_Create(*args, **kwargs) def SetAuthNeeded(*args, **kwargs): """SetAuthNeeded(self, bool show=True)""" return _controls_.Button_SetAuthNeeded(*args, **kwargs) def GetAuthNeeded(*args, **kwargs): """GetAuthNeeded(self) -> bool""" return _controls_.Button_GetAuthNeeded(*args, **kwargs) def SetDefault(*args, **kwargs): """ SetDefault(self) -> Window This sets the button to be the default item for the panel or dialog box. """ return _controls_.Button_SetDefault(*args, **kwargs) def GetDefaultSize(*args, **kwargs): """ GetDefaultSize() -> Size Returns the default button size for this platform. """ return _controls_.Button_GetDefaultSize(*args, **kwargs) GetDefaultSize = staticmethod(GetDefaultSize) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.Button_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) _controls_.Button_swigregister(Button) def PreButton(*args, **kwargs): """ PreButton() -> Button Precreate a Button for 2-phase creation. """ val = _controls_.new_PreButton(*args, **kwargs) return val def Button_GetDefaultSize(*args): """ Button_GetDefaultSize() -> Size Returns the default button size for this platform. """ return _controls_.Button_GetDefaultSize(*args) def Button_GetClassDefaultAttributes(*args, **kwargs): """ Button_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.Button_GetClassDefaultAttributes(*args, **kwargs) class BitmapButton(Button): """ A Button that contains a bitmap. A bitmap button can be supplied with a single bitmap, and wxWidgets will draw all button states using this bitmap. If the application needs more control, additional bitmaps for the selected state, unpressed focused state, and greyed-out state may be supplied. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap, Point pos=DefaultPosition, Size size=DefaultSize, long style=BU_AUTODRAW, Validator validator=DefaultValidator, String name=ButtonNameStr) -> BitmapButton Create and show a button with a bitmap for the label. """ _controls_.BitmapButton_swiginit(self,_controls_.new_BitmapButton(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap, Point pos=DefaultPosition, Size size=DefaultSize, long style=BU_AUTODRAW, Validator validator=DefaultValidator, String name=ButtonNameStr) -> bool Acutally create the GUI BitmapButton for 2-phase creation. """ return _controls_.BitmapButton_Create(*args, **kwargs) _controls_.BitmapButton_swigregister(BitmapButton) def PreBitmapButton(*args, **kwargs): """ PreBitmapButton() -> BitmapButton Precreate a BitmapButton for 2-phase creation. """ val = _controls_.new_PreBitmapButton(*args, **kwargs) return val #--------------------------------------------------------------------------- CHK_2STATE = _controls_.CHK_2STATE CHK_3STATE = _controls_.CHK_3STATE CHK_ALLOW_3RD_STATE_FOR_USER = _controls_.CHK_ALLOW_3RD_STATE_FOR_USER class CheckBox(_core.Control): """ A checkbox is a labelled box which by default is either on (the checkmark is visible) or off (no checkmark). Optionally (When the wx.CHK_3STATE style flag is set) it can have a third state, called the mixed or undetermined state. Often this is used as a "Does Not Apply" state. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=CheckBoxNameStr) -> CheckBox Creates and shows a CheckBox control """ _controls_.CheckBox_swiginit(self,_controls_.new_CheckBox(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=CheckBoxNameStr) -> bool Actually create the GUI CheckBox for 2-phase creation. """ return _controls_.CheckBox_Create(*args, **kwargs) def GetValue(*args, **kwargs): """ GetValue(self) -> bool Gets the state of a 2-state CheckBox. Returns True if it is checked, False otherwise. """ return _controls_.CheckBox_GetValue(*args, **kwargs) def IsChecked(*args, **kwargs): """ IsChecked(self) -> bool Similar to GetValue, but raises an exception if it is not a 2-state CheckBox. """ return _controls_.CheckBox_IsChecked(*args, **kwargs) def SetValue(*args, **kwargs): """ SetValue(self, bool state) Set the state of a 2-state CheckBox. Pass True for checked, False for unchecked. """ return _controls_.CheckBox_SetValue(*args, **kwargs) def Get3StateValue(*args, **kwargs): """ Get3StateValue(self) -> int Returns wx.CHK_UNCHECKED when the CheckBox is unchecked, wx.CHK_CHECKED when it is checked and wx.CHK_UNDETERMINED when it's in the undetermined state. Raises an exceptiion when the function is used with a 2-state CheckBox. """ return _controls_.CheckBox_Get3StateValue(*args, **kwargs) def Set3StateValue(*args, **kwargs): """ Set3StateValue(self, int state) Sets the CheckBox to the given state. The state parameter can be one of the following: wx.CHK_UNCHECKED (Check is off), wx.CHK_CHECKED (the Check is on) or wx.CHK_UNDETERMINED (Check is mixed). Raises an exception when the CheckBox is a 2-state checkbox and setting the state to wx.CHK_UNDETERMINED. """ return _controls_.CheckBox_Set3StateValue(*args, **kwargs) def Is3State(*args, **kwargs): """ Is3State(self) -> bool Returns whether or not the CheckBox is a 3-state CheckBox. """ return _controls_.CheckBox_Is3State(*args, **kwargs) def Is3rdStateAllowedForUser(*args, **kwargs): """ Is3rdStateAllowedForUser(self) -> bool Returns whether or not the user can set the CheckBox to the third state. """ return _controls_.CheckBox_Is3rdStateAllowedForUser(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.CheckBox_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) ThreeStateValue = property(Get3StateValue,Set3StateValue,doc="See `Get3StateValue` and `Set3StateValue`") Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`") _controls_.CheckBox_swigregister(CheckBox) CheckBoxNameStr = cvar.CheckBoxNameStr def PreCheckBox(*args, **kwargs): """ PreCheckBox() -> CheckBox Precreate a CheckBox for 2-phase creation. """ val = _controls_.new_PreCheckBox(*args, **kwargs) return val def CheckBox_GetClassDefaultAttributes(*args, **kwargs): """ CheckBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.CheckBox_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- class Choice(_core.ControlWithItems): """ A Choice control is used to select one of a list of strings. Unlike a `wx.ListBox`, only the selection is visible until the user pulls down the menu of choices. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, List choices=EmptyList, long style=0, Validator validator=DefaultValidator, String name=ChoiceNameStr) -> Choice Create and show a Choice control """ _controls_.Choice_swiginit(self,_controls_.new_Choice(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, List choices=EmptyList, long style=0, Validator validator=DefaultValidator, String name=ChoiceNameStr) -> bool Actually create the GUI Choice control for 2-phase creation """ return _controls_.Choice_Create(*args, **kwargs) def GetCurrentSelection(*args, **kwargs): """ GetCurrentSelection(self) -> int Unlike `GetSelection` which only returns the accepted selection value, i.e. the selection in the control once the user closes the dropdown list, this function returns the current selection. That is, while the dropdown list is shown, it returns the currently selected item in it. When it is not shown, its result is the same as for the other function. """ return _controls_.Choice_GetCurrentSelection(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.Choice_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) CurrentSelection = property(GetCurrentSelection,doc="See `GetCurrentSelection`") _controls_.Choice_swigregister(Choice) ChoiceNameStr = cvar.ChoiceNameStr def PreChoice(*args, **kwargs): """ PreChoice() -> Choice Precreate a Choice control for 2-phase creation. """ val = _controls_.new_PreChoice(*args, **kwargs) return val def Choice_GetClassDefaultAttributes(*args, **kwargs): """ Choice_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.Choice_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- class ComboBox(_core.Control,_core.ItemContainer,_core.TextEntry): """ A combobox is like a combination of an edit control and a listbox. It can be displayed as static list with editable or read-only text field; or a drop-down list with text field. A combobox permits a single selection only. Combobox items are numbered from zero. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, List choices=EmptyList, long style=0, Validator validator=DefaultValidator, String name=ComboBoxNameStr) -> ComboBox Constructor, creates and shows a ComboBox control. """ _controls_.ComboBox_swiginit(self,_controls_.new_ComboBox(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, List choices=EmptyList, long style=0, Validator validator=DefaultValidator, String name=ChoiceNameStr) -> bool Actually create the GUI wxComboBox control for 2-phase creation """ return _controls_.ComboBox_Create(*args, **kwargs) def SetMark(*args, **kwargs): """ SetMark(self, long from, long to) Selects the text between the two positions in the combobox text field. """ return _controls_.ComboBox_SetMark(*args, **kwargs) def GetMark(*args, **kwargs): """ GetMark(self) -> (from, to) Gets the positions of the begining and ending of the selection mark in the combobox text field. """ return _controls_.ComboBox_GetMark(*args, **kwargs) def IsEmpty(*args, **kwargs): """IsEmpty(self) -> bool""" return _controls_.ComboBox_IsEmpty(*args, **kwargs) def IsListEmpty(*args, **kwargs): """IsListEmpty(self) -> bool""" return _controls_.ComboBox_IsListEmpty(*args, **kwargs) def IsTextEmpty(*args, **kwargs): """IsTextEmpty(self) -> bool""" return _controls_.ComboBox_IsTextEmpty(*args, **kwargs) def Popup(*args, **kwargs): """Popup(self)""" return _controls_.ComboBox_Popup(*args, **kwargs) def Dismiss(*args, **kwargs): """Dismiss(self)""" return _controls_.ComboBox_Dismiss(*args, **kwargs) def GetCurrentSelection(*args, **kwargs): """ GetCurrentSelection(self) -> int Unlike `GetSelection` which only returns the accepted selection value, i.e. the selection in the control once the user closes the dropdown list, this function returns the current selection. That is, while the dropdown list is shown, it returns the currently selected item in it. When it is not shown, its result is the same as for the other function. """ return _controls_.ComboBox_GetCurrentSelection(*args, **kwargs) def SetStringSelection(*args, **kwargs): """ SetStringSelection(self, String string) -> bool Select the item with the specifed string """ return _controls_.ComboBox_SetStringSelection(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ComboBox_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) CurrentSelection = property(GetCurrentSelection) Mark = property(GetMark,SetMark) _controls_.ComboBox_swigregister(ComboBox) ComboBoxNameStr = cvar.ComboBoxNameStr def PreComboBox(*args, **kwargs): """ PreComboBox() -> ComboBox Precreate a ComboBox control for 2-phase creation. """ val = _controls_.new_PreComboBox(*args, **kwargs) return val def ComboBox_GetClassDefaultAttributes(*args, **kwargs): """ ComboBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ComboBox_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- GA_HORIZONTAL = _controls_.GA_HORIZONTAL GA_VERTICAL = _controls_.GA_VERTICAL GA_SMOOTH = _controls_.GA_SMOOTH GA_PROGRESSBAR = 0 # obsolete class Gauge(_core.Control): """Proxy of C++ Gauge class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, int range=100, Point pos=DefaultPosition, Size size=DefaultSize, long style=GA_HORIZONTAL, Validator validator=DefaultValidator, String name=GaugeNameStr) -> Gauge """ _controls_.Gauge_swiginit(self,_controls_.new_Gauge(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, int range=100, Point pos=DefaultPosition, Size size=DefaultSize, long style=GA_HORIZONTAL, Validator validator=DefaultValidator, String name=GaugeNameStr) -> bool """ return _controls_.Gauge_Create(*args, **kwargs) def SetRange(*args, **kwargs): """SetRange(self, int range)""" return _controls_.Gauge_SetRange(*args, **kwargs) def GetRange(*args, **kwargs): """GetRange(self) -> int""" return _controls_.Gauge_GetRange(*args, **kwargs) def SetValue(*args, **kwargs): """SetValue(self, int pos)""" return _controls_.Gauge_SetValue(*args, **kwargs) def GetValue(*args, **kwargs): """GetValue(self) -> int""" return _controls_.Gauge_GetValue(*args, **kwargs) def Pulse(*args, **kwargs): """Pulse(self)""" return _controls_.Gauge_Pulse(*args, **kwargs) def IsVertical(*args, **kwargs): """IsVertical(self) -> bool""" return _controls_.Gauge_IsVertical(*args, **kwargs) def SetShadowWidth(*args, **kwargs): """SetShadowWidth(self, int w)""" return _controls_.Gauge_SetShadowWidth(*args, **kwargs) def GetShadowWidth(*args, **kwargs): """GetShadowWidth(self) -> int""" return _controls_.Gauge_GetShadowWidth(*args, **kwargs) def SetBezelFace(*args, **kwargs): """SetBezelFace(self, int w)""" return _controls_.Gauge_SetBezelFace(*args, **kwargs) def GetBezelFace(*args, **kwargs): """GetBezelFace(self) -> int""" return _controls_.Gauge_GetBezelFace(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.Gauge_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) BezelFace = property(GetBezelFace,SetBezelFace,doc="See `GetBezelFace` and `SetBezelFace`") Range = property(GetRange,SetRange,doc="See `GetRange` and `SetRange`") ShadowWidth = property(GetShadowWidth,SetShadowWidth,doc="See `GetShadowWidth` and `SetShadowWidth`") Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`") _controls_.Gauge_swigregister(Gauge) GaugeNameStr = cvar.GaugeNameStr def PreGauge(*args, **kwargs): """PreGauge() -> Gauge""" val = _controls_.new_PreGauge(*args, **kwargs) return val def Gauge_GetClassDefaultAttributes(*args, **kwargs): """ Gauge_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.Gauge_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- class StaticBox(_core.Control): """Proxy of C++ StaticBox class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=StaticBoxNameStr) -> StaticBox """ _controls_.StaticBox_swiginit(self,_controls_.new_StaticBox(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=StaticBoxNameStr) -> bool """ return _controls_.StaticBox_Create(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.StaticBox_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) _controls_.StaticBox_swigregister(StaticBox) StaticBitmapNameStr = cvar.StaticBitmapNameStr StaticBoxNameStr = cvar.StaticBoxNameStr StaticTextNameStr = cvar.StaticTextNameStr StaticLineNameStr = cvar.StaticLineNameStr def PreStaticBox(*args, **kwargs): """PreStaticBox() -> StaticBox""" val = _controls_.new_PreStaticBox(*args, **kwargs) return val def StaticBox_GetClassDefaultAttributes(*args, **kwargs): """ StaticBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.StaticBox_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- class StaticLine(_core.Control): """Proxy of C++ StaticLine class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=LI_HORIZONTAL, String name=StaticLineNameStr) -> StaticLine """ _controls_.StaticLine_swiginit(self,_controls_.new_StaticLine(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=LI_HORIZONTAL, String name=StaticLineNameStr) -> bool """ return _controls_.StaticLine_Create(*args, **kwargs) def IsVertical(*args, **kwargs): """IsVertical(self) -> bool""" return _controls_.StaticLine_IsVertical(*args, **kwargs) def GetDefaultSize(*args, **kwargs): """GetDefaultSize() -> int""" return _controls_.StaticLine_GetDefaultSize(*args, **kwargs) GetDefaultSize = staticmethod(GetDefaultSize) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.StaticLine_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) _controls_.StaticLine_swigregister(StaticLine) def PreStaticLine(*args, **kwargs): """PreStaticLine() -> StaticLine""" val = _controls_.new_PreStaticLine(*args, **kwargs) return val def StaticLine_GetDefaultSize(*args): """StaticLine_GetDefaultSize() -> int""" return _controls_.StaticLine_GetDefaultSize(*args) def StaticLine_GetClassDefaultAttributes(*args, **kwargs): """ StaticLine_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.StaticLine_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- ST_NO_AUTORESIZE = _controls_.ST_NO_AUTORESIZE ST_ELLIPSIZE_START = _controls_.ST_ELLIPSIZE_START ST_ELLIPSIZE_MIDDLE = _controls_.ST_ELLIPSIZE_MIDDLE ST_ELLIPSIZE_END = _controls_.ST_ELLIPSIZE_END class StaticText(_core.Control): """Proxy of C++ StaticText class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=StaticTextNameStr) -> StaticText """ _controls_.StaticText_swiginit(self,_controls_.new_StaticText(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=StaticTextNameStr) -> bool """ return _controls_.StaticText_Create(*args, **kwargs) def Wrap(*args, **kwargs): """ Wrap(self, int width) This functions wraps the control's label so that each of its lines becomes at most ``width`` pixels wide if possible (the lines are broken at words boundaries so it might not be the case if words are too long). If ``width`` is negative, no wrapping is done. """ return _controls_.StaticText_Wrap(*args, **kwargs) def IsEllipsized(*args, **kwargs): """IsEllipsized(self) -> bool""" return _controls_.StaticText_IsEllipsized(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.StaticText_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) _controls_.StaticText_swigregister(StaticText) def PreStaticText(*args, **kwargs): """PreStaticText() -> StaticText""" val = _controls_.new_PreStaticText(*args, **kwargs) return val def StaticText_GetClassDefaultAttributes(*args, **kwargs): """ StaticText_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.StaticText_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- class StaticBitmap(_core.Control): """Proxy of C++ StaticBitmap class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=StaticBitmapNameStr) -> StaticBitmap """ _controls_.StaticBitmap_swiginit(self,_controls_.new_StaticBitmap(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Bitmap bitmap=wxNullBitmap, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=StaticBitmapNameStr) -> bool """ return _controls_.StaticBitmap_Create(*args, **kwargs) def GetBitmap(*args, **kwargs): """GetBitmap(self) -> Bitmap""" return _controls_.StaticBitmap_GetBitmap(*args, **kwargs) def SetBitmap(*args, **kwargs): """SetBitmap(self, Bitmap bitmap)""" return _controls_.StaticBitmap_SetBitmap(*args, **kwargs) def SetIcon(*args, **kwargs): """SetIcon(self, Icon icon)""" return _controls_.StaticBitmap_SetIcon(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.StaticBitmap_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) _controls_.StaticBitmap_swigregister(StaticBitmap) def PreStaticBitmap(*args, **kwargs): """PreStaticBitmap() -> StaticBitmap""" val = _controls_.new_PreStaticBitmap(*args, **kwargs) return val def StaticBitmap_GetClassDefaultAttributes(*args, **kwargs): """ StaticBitmap_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.StaticBitmap_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- class ListBox(_core.ControlWithItems): """Proxy of C++ ListBox class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray, long style=0, Validator validator=DefaultValidator, String name=ListBoxNameStr) -> ListBox """ _controls_.ListBox_swiginit(self,_controls_.new_ListBox(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray, long style=0, Validator validator=DefaultValidator, String name=ListBoxNameStr) -> bool """ return _controls_.ListBox_Create(*args, **kwargs) def Insert(*args, **kwargs): """ Insert(self, String item, int pos, PyObject clientData=None) Insert an item into the control before the item at the ``pos`` index, optionally associating some data object with the item. """ return _controls_.ListBox_Insert(*args, **kwargs) def InsertItems(*args, **kwargs): """InsertItems(self, wxArrayString items, unsigned int pos)""" return _controls_.ListBox_InsertItems(*args, **kwargs) def Set(*args, **kwargs): """ Set(self, List strings) Replace all the items in the control """ return _controls_.ListBox_Set(*args, **kwargs) def IsSelected(*args, **kwargs): """IsSelected(self, int n) -> bool""" return _controls_.ListBox_IsSelected(*args, **kwargs) def SetSelection(*args, **kwargs): """SetSelection(self, int n, bool select=True)""" return _controls_.ListBox_SetSelection(*args, **kwargs) def Select(*args, **kwargs): """ Select(self, int n) This is the same as `SetSelection` and exists only because it is slightly more natural for controls which support multiple selection. """ return _controls_.ListBox_Select(*args, **kwargs) def Deselect(*args, **kwargs): """Deselect(self, int n)""" return _controls_.ListBox_Deselect(*args, **kwargs) def DeselectAll(*args, **kwargs): """DeselectAll(self, int itemToLeaveSelected=-1)""" return _controls_.ListBox_DeselectAll(*args, **kwargs) def SetStringSelection(*args, **kwargs): """SetStringSelection(self, String s, bool select=True) -> bool""" return _controls_.ListBox_SetStringSelection(*args, **kwargs) def GetSelections(*args, **kwargs): """GetSelections(self) -> PyObject""" return _controls_.ListBox_GetSelections(*args, **kwargs) def SetFirstItem(*args, **kwargs): """SetFirstItem(self, int n)""" return _controls_.ListBox_SetFirstItem(*args, **kwargs) def SetFirstItemStr(*args, **kwargs): """SetFirstItemStr(self, String s)""" return _controls_.ListBox_SetFirstItemStr(*args, **kwargs) def EnsureVisible(*args, **kwargs): """EnsureVisible(self, int n)""" return _controls_.ListBox_EnsureVisible(*args, **kwargs) def AppendAndEnsureVisible(*args, **kwargs): """AppendAndEnsureVisible(self, String s)""" return _controls_.ListBox_AppendAndEnsureVisible(*args, **kwargs) def HitTest(*args, **kwargs): """ HitTest(self, Point pt) -> int Test where the given (in client coords) point lies """ return _controls_.ListBox_HitTest(*args, **kwargs) def SetItemForegroundColour(*args, **kwargs): """SetItemForegroundColour(self, int item, Colour c)""" return _controls_.ListBox_SetItemForegroundColour(*args, **kwargs) def SetItemBackgroundColour(*args, **kwargs): """SetItemBackgroundColour(self, int item, Colour c)""" return _controls_.ListBox_SetItemBackgroundColour(*args, **kwargs) def SetItemFont(*args, **kwargs): """SetItemFont(self, int item, Font f)""" return _controls_.ListBox_SetItemFont(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ListBox_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) Selections = property(GetSelections,doc="See `GetSelections`") _controls_.ListBox_swigregister(ListBox) ListBoxNameStr = cvar.ListBoxNameStr def PreListBox(*args, **kwargs): """PreListBox() -> ListBox""" val = _controls_.new_PreListBox(*args, **kwargs) return val def ListBox_GetClassDefaultAttributes(*args, **kwargs): """ ListBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ListBox_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- class CheckListBox(ListBox): """Proxy of C++ CheckListBox class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray, long style=0, Validator validator=DefaultValidator, String name=ListBoxNameStr) -> CheckListBox """ _controls_.CheckListBox_swiginit(self,_controls_.new_CheckListBox(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray, long style=0, Validator validator=DefaultValidator, String name=ListBoxNameStr) -> bool """ return _controls_.CheckListBox_Create(*args, **kwargs) def IsChecked(*args, **kwargs): """IsChecked(self, unsigned int index) -> bool""" return _controls_.CheckListBox_IsChecked(*args, **kwargs) def Check(*args, **kwargs): """Check(self, unsigned int index, int check=True)""" return _controls_.CheckListBox_Check(*args, **kwargs) def GetChecked(self): """ GetChecked(self) Return a tuple of integers corresponding to the checked items in the control, based on `IsChecked`. """ return tuple([i for i in range(self.Count) if self.IsChecked(i)]) def GetCheckedStrings(self): """ GetCheckedStrings(self) Return a tuple of strings corresponding to the checked items of the control, based on `GetChecked`. """ return tuple([self.GetString(i) for i in self.GetChecked()]) def SetChecked(self, indexes): """ SetChecked(self, indexes) Sets the checked state of items if the index of the item is found in the indexes sequence. """ for i in indexes: assert 0 <= i < self.Count, "Index (%s) out of range" % i for i in range(self.Count): self.Check(i, i in indexes) def SetCheckedStrings(self, strings): """ SetCheckedStrings(self, indexes) Sets the checked state of items if the item's string is found in the strings sequence. """ for s in strings: assert s in self.GetStrings(), "String ('%s') not found" % s for i in range(self.Count): self.Check(i, self.GetString(i) in strings) Checked = property(GetChecked,SetChecked) CheckedStrings = property(GetCheckedStrings,SetCheckedStrings) _controls_.CheckListBox_swigregister(CheckListBox) def PreCheckListBox(*args, **kwargs): """PreCheckListBox() -> CheckListBox""" val = _controls_.new_PreCheckListBox(*args, **kwargs) return val #--------------------------------------------------------------------------- TE_NO_VSCROLL = _controls_.TE_NO_VSCROLL TE_AUTO_SCROLL = _controls_.TE_AUTO_SCROLL TE_READONLY = _controls_.TE_READONLY TE_MULTILINE = _controls_.TE_MULTILINE TE_PROCESS_TAB = _controls_.TE_PROCESS_TAB TE_LEFT = _controls_.TE_LEFT TE_CENTER = _controls_.TE_CENTER TE_RIGHT = _controls_.TE_RIGHT TE_CENTRE = _controls_.TE_CENTRE TE_RICH = _controls_.TE_RICH TE_PROCESS_ENTER = _controls_.TE_PROCESS_ENTER TE_PASSWORD = _controls_.TE_PASSWORD TE_AUTO_URL = _controls_.TE_AUTO_URL TE_NOHIDESEL = _controls_.TE_NOHIDESEL TE_DONTWRAP = _controls_.TE_DONTWRAP TE_CHARWRAP = _controls_.TE_CHARWRAP TE_WORDWRAP = _controls_.TE_WORDWRAP TE_BESTWRAP = _controls_.TE_BESTWRAP TE_RICH2 = _controls_.TE_RICH2 TE_CAPITALIZE = _controls_.TE_CAPITALIZE TE_LINEWRAP = TE_CHARWRAP PROCESS_ENTER = TE_PROCESS_ENTER PASSWORD = TE_PASSWORD TEXT_ALIGNMENT_DEFAULT = _controls_.TEXT_ALIGNMENT_DEFAULT TEXT_ALIGNMENT_LEFT = _controls_.TEXT_ALIGNMENT_LEFT TEXT_ALIGNMENT_CENTRE = _controls_.TEXT_ALIGNMENT_CENTRE TEXT_ALIGNMENT_CENTER = _controls_.TEXT_ALIGNMENT_CENTER TEXT_ALIGNMENT_RIGHT = _controls_.TEXT_ALIGNMENT_RIGHT TEXT_ALIGNMENT_JUSTIFIED = _controls_.TEXT_ALIGNMENT_JUSTIFIED TEXT_ATTR_TEXT_COLOUR = _controls_.TEXT_ATTR_TEXT_COLOUR TEXT_ATTR_BACKGROUND_COLOUR = _controls_.TEXT_ATTR_BACKGROUND_COLOUR TEXT_ATTR_FONT_FACE = _controls_.TEXT_ATTR_FONT_FACE TEXT_ATTR_FONT_SIZE = _controls_.TEXT_ATTR_FONT_SIZE TEXT_ATTR_FONT_WEIGHT = _controls_.TEXT_ATTR_FONT_WEIGHT TEXT_ATTR_FONT_ITALIC = _controls_.TEXT_ATTR_FONT_ITALIC TEXT_ATTR_FONT_UNDERLINE = _controls_.TEXT_ATTR_FONT_UNDERLINE TEXT_ATTR_FONT_STRIKETHROUGH = _controls_.TEXT_ATTR_FONT_STRIKETHROUGH TEXT_ATTR_FONT_ENCODING = _controls_.TEXT_ATTR_FONT_ENCODING TEXT_ATTR_FONT_FAMILY = _controls_.TEXT_ATTR_FONT_FAMILY TEXT_ATTR_FONT = _controls_.TEXT_ATTR_FONT TEXT_ATTR_ALIGNMENT = _controls_.TEXT_ATTR_ALIGNMENT TEXT_ATTR_LEFT_INDENT = _controls_.TEXT_ATTR_LEFT_INDENT TEXT_ATTR_RIGHT_INDENT = _controls_.TEXT_ATTR_RIGHT_INDENT TEXT_ATTR_TABS = _controls_.TEXT_ATTR_TABS TEXT_ATTR_PARA_SPACING_AFTER = _controls_.TEXT_ATTR_PARA_SPACING_AFTER TEXT_ATTR_LINE_SPACING = _controls_.TEXT_ATTR_LINE_SPACING TEXT_ATTR_CHARACTER_STYLE_NAME = _controls_.TEXT_ATTR_CHARACTER_STYLE_NAME TEXT_ATTR_PARAGRAPH_STYLE_NAME = _controls_.TEXT_ATTR_PARAGRAPH_STYLE_NAME TEXT_ATTR_LIST_STYLE_NAME = _controls_.TEXT_ATTR_LIST_STYLE_NAME TEXT_ATTR_BULLET_STYLE = _controls_.TEXT_ATTR_BULLET_STYLE TEXT_ATTR_BULLET_NUMBER = _controls_.TEXT_ATTR_BULLET_NUMBER TEXT_ATTR_BULLET_TEXT = _controls_.TEXT_ATTR_BULLET_TEXT TEXT_ATTR_BULLET_NAME = _controls_.TEXT_ATTR_BULLET_NAME TEXT_ATTR_BULLET = _controls_.TEXT_ATTR_BULLET TEXT_ATTR_URL = _controls_.TEXT_ATTR_URL TEXT_ATTR_PAGE_BREAK = _controls_.TEXT_ATTR_PAGE_BREAK TEXT_ATTR_EFFECTS = _controls_.TEXT_ATTR_EFFECTS TEXT_ATTR_OUTLINE_LEVEL = _controls_.TEXT_ATTR_OUTLINE_LEVEL TEXT_ATTR_CHARACTER = _controls_.TEXT_ATTR_CHARACTER TEXT_ATTR_PARAGRAPH = _controls_.TEXT_ATTR_PARAGRAPH TEXT_ATTR_ALL = _controls_.TEXT_ATTR_ALL TEXT_ATTR_BULLET_STYLE_NONE = _controls_.TEXT_ATTR_BULLET_STYLE_NONE TEXT_ATTR_BULLET_STYLE_ARABIC = _controls_.TEXT_ATTR_BULLET_STYLE_ARABIC TEXT_ATTR_BULLET_STYLE_LETTERS_UPPER = _controls_.TEXT_ATTR_BULLET_STYLE_LETTERS_UPPER TEXT_ATTR_BULLET_STYLE_LETTERS_LOWER = _controls_.TEXT_ATTR_BULLET_STYLE_LETTERS_LOWER TEXT_ATTR_BULLET_STYLE_ROMAN_UPPER = _controls_.TEXT_ATTR_BULLET_STYLE_ROMAN_UPPER TEXT_ATTR_BULLET_STYLE_ROMAN_LOWER = _controls_.TEXT_ATTR_BULLET_STYLE_ROMAN_LOWER TEXT_ATTR_BULLET_STYLE_SYMBOL = _controls_.TEXT_ATTR_BULLET_STYLE_SYMBOL TEXT_ATTR_BULLET_STYLE_BITMAP = _controls_.TEXT_ATTR_BULLET_STYLE_BITMAP TEXT_ATTR_BULLET_STYLE_PARENTHESES = _controls_.TEXT_ATTR_BULLET_STYLE_PARENTHESES TEXT_ATTR_BULLET_STYLE_PERIOD = _controls_.TEXT_ATTR_BULLET_STYLE_PERIOD TEXT_ATTR_BULLET_STYLE_STANDARD = _controls_.TEXT_ATTR_BULLET_STYLE_STANDARD TEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS = _controls_.TEXT_ATTR_BULLET_STYLE_RIGHT_PARENTHESIS TEXT_ATTR_BULLET_STYLE_OUTLINE = _controls_.TEXT_ATTR_BULLET_STYLE_OUTLINE TEXT_ATTR_BULLET_STYLE_ALIGN_LEFT = _controls_.TEXT_ATTR_BULLET_STYLE_ALIGN_LEFT TEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT = _controls_.TEXT_ATTR_BULLET_STYLE_ALIGN_RIGHT TEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE = _controls_.TEXT_ATTR_BULLET_STYLE_ALIGN_CENTRE TEXT_ATTR_EFFECT_NONE = _controls_.TEXT_ATTR_EFFECT_NONE TEXT_ATTR_EFFECT_CAPITALS = _controls_.TEXT_ATTR_EFFECT_CAPITALS TEXT_ATTR_EFFECT_SMALL_CAPITALS = _controls_.TEXT_ATTR_EFFECT_SMALL_CAPITALS TEXT_ATTR_EFFECT_STRIKETHROUGH = _controls_.TEXT_ATTR_EFFECT_STRIKETHROUGH TEXT_ATTR_EFFECT_DOUBLE_STRIKETHROUGH = _controls_.TEXT_ATTR_EFFECT_DOUBLE_STRIKETHROUGH TEXT_ATTR_EFFECT_SHADOW = _controls_.TEXT_ATTR_EFFECT_SHADOW TEXT_ATTR_EFFECT_EMBOSS = _controls_.TEXT_ATTR_EFFECT_EMBOSS TEXT_ATTR_EFFECT_OUTLINE = _controls_.TEXT_ATTR_EFFECT_OUTLINE TEXT_ATTR_EFFECT_ENGRAVE = _controls_.TEXT_ATTR_EFFECT_ENGRAVE TEXT_ATTR_EFFECT_SUPERSCRIPT = _controls_.TEXT_ATTR_EFFECT_SUPERSCRIPT TEXT_ATTR_EFFECT_SUBSCRIPT = _controls_.TEXT_ATTR_EFFECT_SUBSCRIPT TEXT_ATTR_LINE_SPACING_NORMAL = _controls_.TEXT_ATTR_LINE_SPACING_NORMAL TEXT_ATTR_LINE_SPACING_HALF = _controls_.TEXT_ATTR_LINE_SPACING_HALF TEXT_ATTR_LINE_SPACING_TWICE = _controls_.TEXT_ATTR_LINE_SPACING_TWICE OutOfRangeTextCoord = _controls_.OutOfRangeTextCoord InvalidTextCoord = _controls_.InvalidTextCoord TEXT_TYPE_ANY = _controls_.TEXT_TYPE_ANY class TextAttr(object): """Proxy of C++ TextAttr class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Colour colText=wxNullColour, Colour colBack=wxNullColour, Font font=wxNullFont, int alignment=TEXT_ALIGNMENT_DEFAULT) -> TextAttr """ _controls_.TextAttr_swiginit(self,_controls_.new_TextAttr(*args, **kwargs)) __swig_destroy__ = _controls_.delete_TextAttr __del__ = lambda self : None; def Init(*args, **kwargs): """Init(self)""" return _controls_.TextAttr_Init(*args, **kwargs) def Copy(*args, **kwargs): """Copy(self, TextAttr attr)""" return _controls_.TextAttr_Copy(*args, **kwargs) def EqPartial(*args, **kwargs): """EqPartial(self, TextAttr attr) -> bool""" return _controls_.TextAttr_EqPartial(*args, **kwargs) def GetFontAttributes(*args, **kwargs): """GetFontAttributes(self, Font font, int flags=TEXT_ATTR_FONT) -> bool""" return _controls_.TextAttr_GetFontAttributes(*args, **kwargs) def SetTextColour(*args, **kwargs): """SetTextColour(self, Colour colText)""" return _controls_.TextAttr_SetTextColour(*args, **kwargs) def SetBackgroundColour(*args, **kwargs): """SetBackgroundColour(self, Colour colBack)""" return _controls_.TextAttr_SetBackgroundColour(*args, **kwargs) def SetAlignment(*args, **kwargs): """SetAlignment(self, int alignment)""" return _controls_.TextAttr_SetAlignment(*args, **kwargs) def SetTabs(*args, **kwargs): """SetTabs(self, wxArrayInt tabs)""" return _controls_.TextAttr_SetTabs(*args, **kwargs) def SetLeftIndent(*args, **kwargs): """SetLeftIndent(self, int indent, int subIndent=0)""" return _controls_.TextAttr_SetLeftIndent(*args, **kwargs) def SetRightIndent(*args, **kwargs): """SetRightIndent(self, int indent)""" return _controls_.TextAttr_SetRightIndent(*args, **kwargs) def SetFontSize(*args, **kwargs): """SetFontSize(self, int pointSize)""" return _controls_.TextAttr_SetFontSize(*args, **kwargs) def SetFontStyle(*args, **kwargs): """SetFontStyle(self, int fontStyle)""" return _controls_.TextAttr_SetFontStyle(*args, **kwargs) def SetFontWeight(*args, **kwargs): """SetFontWeight(self, int fontWeight)""" return _controls_.TextAttr_SetFontWeight(*args, **kwargs) def SetFontFaceName(*args, **kwargs): """SetFontFaceName(self, String faceName)""" return _controls_.TextAttr_SetFontFaceName(*args, **kwargs) def SetFontUnderlined(*args, **kwargs): """SetFontUnderlined(self, bool underlined)""" return _controls_.TextAttr_SetFontUnderlined(*args, **kwargs) def SetFontStrikethrough(*args, **kwargs): """SetFontStrikethrough(self, bool strikethrough)""" return _controls_.TextAttr_SetFontStrikethrough(*args, **kwargs) def SetFontEncoding(*args, **kwargs): """SetFontEncoding(self, int encoding)""" return _controls_.TextAttr_SetFontEncoding(*args, **kwargs) def SetFontFamily(*args, **kwargs): """SetFontFamily(self, int family)""" return _controls_.TextAttr_SetFontFamily(*args, **kwargs) def SetFont(*args, **kwargs): """SetFont(self, Font font, int flags=TEXT_ATTR_FONT)""" return _controls_.TextAttr_SetFont(*args, **kwargs) def SetFlags(*args, **kwargs): """SetFlags(self, long flags)""" return _controls_.TextAttr_SetFlags(*args, **kwargs) def SetCharacterStyleName(*args, **kwargs): """SetCharacterStyleName(self, String name)""" return _controls_.TextAttr_SetCharacterStyleName(*args, **kwargs) def SetParagraphStyleName(*args, **kwargs): """SetParagraphStyleName(self, String name)""" return _controls_.TextAttr_SetParagraphStyleName(*args, **kwargs) def SetListStyleName(*args, **kwargs): """SetListStyleName(self, String name)""" return _controls_.TextAttr_SetListStyleName(*args, **kwargs) def SetParagraphSpacingAfter(*args, **kwargs): """SetParagraphSpacingAfter(self, int spacing)""" return _controls_.TextAttr_SetParagraphSpacingAfter(*args, **kwargs) def SetParagraphSpacingBefore(*args, **kwargs): """SetParagraphSpacingBefore(self, int spacing)""" return _controls_.TextAttr_SetParagraphSpacingBefore(*args, **kwargs) def SetLineSpacing(*args, **kwargs): """SetLineSpacing(self, int spacing)""" return _controls_.TextAttr_SetLineSpacing(*args, **kwargs) def SetBulletStyle(*args, **kwargs): """SetBulletStyle(self, int style)""" return _controls_.TextAttr_SetBulletStyle(*args, **kwargs) def SetBulletNumber(*args, **kwargs): """SetBulletNumber(self, int n)""" return _controls_.TextAttr_SetBulletNumber(*args, **kwargs) def SetBulletText(*args, **kwargs): """SetBulletText(self, String text)""" return _controls_.TextAttr_SetBulletText(*args, **kwargs) def SetBulletFont(*args, **kwargs): """SetBulletFont(self, String bulletFont)""" return _controls_.TextAttr_SetBulletFont(*args, **kwargs) def SetBulletName(*args, **kwargs): """SetBulletName(self, String name)""" return _controls_.TextAttr_SetBulletName(*args, **kwargs) def SetURL(*args, **kwargs): """SetURL(self, String url)""" return _controls_.TextAttr_SetURL(*args, **kwargs) def SetPageBreak(*args, **kwargs): """SetPageBreak(self, bool pageBreak=True)""" return _controls_.TextAttr_SetPageBreak(*args, **kwargs) def SetTextEffects(*args, **kwargs): """SetTextEffects(self, int effects)""" return _controls_.TextAttr_SetTextEffects(*args, **kwargs) def SetTextEffectFlags(*args, **kwargs): """SetTextEffectFlags(self, int effects)""" return _controls_.TextAttr_SetTextEffectFlags(*args, **kwargs) def SetOutlineLevel(*args, **kwargs): """SetOutlineLevel(self, int level)""" return _controls_.TextAttr_SetOutlineLevel(*args, **kwargs) def GetTextColour(*args, **kwargs): """GetTextColour(self) -> Colour""" return _controls_.TextAttr_GetTextColour(*args, **kwargs) def GetBackgroundColour(*args, **kwargs): """GetBackgroundColour(self) -> Colour""" return _controls_.TextAttr_GetBackgroundColour(*args, **kwargs) def GetAlignment(*args, **kwargs): """GetAlignment(self) -> int""" return _controls_.TextAttr_GetAlignment(*args, **kwargs) def GetTabs(*args, **kwargs): """GetTabs(self) -> wxArrayInt""" return _controls_.TextAttr_GetTabs(*args, **kwargs) def GetLeftIndent(*args, **kwargs): """GetLeftIndent(self) -> long""" return _controls_.TextAttr_GetLeftIndent(*args, **kwargs) def GetLeftSubIndent(*args, **kwargs): """GetLeftSubIndent(self) -> long""" return _controls_.TextAttr_GetLeftSubIndent(*args, **kwargs) def GetRightIndent(*args, **kwargs): """GetRightIndent(self) -> long""" return _controls_.TextAttr_GetRightIndent(*args, **kwargs) def GetFlags(*args, **kwargs): """GetFlags(self) -> long""" return _controls_.TextAttr_GetFlags(*args, **kwargs) def GetFontSize(*args, **kwargs): """GetFontSize(self) -> int""" return _controls_.TextAttr_GetFontSize(*args, **kwargs) def GetFontStyle(*args, **kwargs): """GetFontStyle(self) -> int""" return _controls_.TextAttr_GetFontStyle(*args, **kwargs) def GetFontWeight(*args, **kwargs): """GetFontWeight(self) -> int""" return _controls_.TextAttr_GetFontWeight(*args, **kwargs) def GetFontUnderlined(*args, **kwargs): """GetFontUnderlined(self) -> bool""" return _controls_.TextAttr_GetFontUnderlined(*args, **kwargs) def GetFontStrikethrough(*args, **kwargs): """GetFontStrikethrough(self) -> bool""" return _controls_.TextAttr_GetFontStrikethrough(*args, **kwargs) def GetFontFaceName(*args, **kwargs): """GetFontFaceName(self) -> String""" return _controls_.TextAttr_GetFontFaceName(*args, **kwargs) def GetFontEncoding(*args, **kwargs): """GetFontEncoding(self) -> int""" return _controls_.TextAttr_GetFontEncoding(*args, **kwargs) def GetFontFamily(*args, **kwargs): """GetFontFamily(self) -> int""" return _controls_.TextAttr_GetFontFamily(*args, **kwargs) def GetFont(*args, **kwargs): """GetFont(self) -> Font""" return _controls_.TextAttr_GetFont(*args, **kwargs) CreateFont = GetFont def GetCharacterStyleName(*args, **kwargs): """GetCharacterStyleName(self) -> String""" return _controls_.TextAttr_GetCharacterStyleName(*args, **kwargs) def GetParagraphStyleName(*args, **kwargs): """GetParagraphStyleName(self) -> String""" return _controls_.TextAttr_GetParagraphStyleName(*args, **kwargs) def GetListStyleName(*args, **kwargs): """GetListStyleName(self) -> String""" return _controls_.TextAttr_GetListStyleName(*args, **kwargs) def GetParagraphSpacingAfter(*args, **kwargs): """GetParagraphSpacingAfter(self) -> int""" return _controls_.TextAttr_GetParagraphSpacingAfter(*args, **kwargs) def GetParagraphSpacingBefore(*args, **kwargs): """GetParagraphSpacingBefore(self) -> int""" return _controls_.TextAttr_GetParagraphSpacingBefore(*args, **kwargs) def GetLineSpacing(*args, **kwargs): """GetLineSpacing(self) -> int""" return _controls_.TextAttr_GetLineSpacing(*args, **kwargs) def GetBulletStyle(*args, **kwargs): """GetBulletStyle(self) -> int""" return _controls_.TextAttr_GetBulletStyle(*args, **kwargs) def GetBulletNumber(*args, **kwargs): """GetBulletNumber(self) -> int""" return _controls_.TextAttr_GetBulletNumber(*args, **kwargs) def GetBulletText(*args, **kwargs): """GetBulletText(self) -> String""" return _controls_.TextAttr_GetBulletText(*args, **kwargs) def GetBulletFont(*args, **kwargs): """GetBulletFont(self) -> String""" return _controls_.TextAttr_GetBulletFont(*args, **kwargs) def GetBulletName(*args, **kwargs): """GetBulletName(self) -> String""" return _controls_.TextAttr_GetBulletName(*args, **kwargs) def GetURL(*args, **kwargs): """GetURL(self) -> String""" return _controls_.TextAttr_GetURL(*args, **kwargs) def GetTextEffects(*args, **kwargs): """GetTextEffects(self) -> int""" return _controls_.TextAttr_GetTextEffects(*args, **kwargs) def GetTextEffectFlags(*args, **kwargs): """GetTextEffectFlags(self) -> int""" return _controls_.TextAttr_GetTextEffectFlags(*args, **kwargs) def GetOutlineLevel(*args, **kwargs): """GetOutlineLevel(self) -> int""" return _controls_.TextAttr_GetOutlineLevel(*args, **kwargs) def HasTextColour(*args, **kwargs): """HasTextColour(self) -> bool""" return _controls_.TextAttr_HasTextColour(*args, **kwargs) def HasBackgroundColour(*args, **kwargs): """HasBackgroundColour(self) -> bool""" return _controls_.TextAttr_HasBackgroundColour(*args, **kwargs) def HasAlignment(*args, **kwargs): """HasAlignment(self) -> bool""" return _controls_.TextAttr_HasAlignment(*args, **kwargs) def HasTabs(*args, **kwargs): """HasTabs(self) -> bool""" return _controls_.TextAttr_HasTabs(*args, **kwargs) def HasLeftIndent(*args, **kwargs): """HasLeftIndent(self) -> bool""" return _controls_.TextAttr_HasLeftIndent(*args, **kwargs) def HasRightIndent(*args, **kwargs): """HasRightIndent(self) -> bool""" return _controls_.TextAttr_HasRightIndent(*args, **kwargs) def HasFontWeight(*args, **kwargs): """HasFontWeight(self) -> bool""" return _controls_.TextAttr_HasFontWeight(*args, **kwargs) def HasFontSize(*args, **kwargs): """HasFontSize(self) -> bool""" return _controls_.TextAttr_HasFontSize(*args, **kwargs) def HasFontItalic(*args, **kwargs): """HasFontItalic(self) -> bool""" return _controls_.TextAttr_HasFontItalic(*args, **kwargs) def HasFontUnderlined(*args, **kwargs): """HasFontUnderlined(self) -> bool""" return _controls_.TextAttr_HasFontUnderlined(*args, **kwargs) def HasFontStrikethrough(*args, **kwargs): """HasFontStrikethrough(self) -> bool""" return _controls_.TextAttr_HasFontStrikethrough(*args, **kwargs) def HasFontFaceName(*args, **kwargs): """HasFontFaceName(self) -> bool""" return _controls_.TextAttr_HasFontFaceName(*args, **kwargs) def HasFontEncoding(*args, **kwargs): """HasFontEncoding(self) -> bool""" return _controls_.TextAttr_HasFontEncoding(*args, **kwargs) def HasFontFamily(*args, **kwargs): """HasFontFamily(self) -> bool""" return _controls_.TextAttr_HasFontFamily(*args, **kwargs) def HasFont(*args, **kwargs): """HasFont(self) -> bool""" return _controls_.TextAttr_HasFont(*args, **kwargs) def HasParagraphSpacingAfter(*args, **kwargs): """HasParagraphSpacingAfter(self) -> bool""" return _controls_.TextAttr_HasParagraphSpacingAfter(*args, **kwargs) def HasParagraphSpacingBefore(*args, **kwargs): """HasParagraphSpacingBefore(self) -> bool""" return _controls_.TextAttr_HasParagraphSpacingBefore(*args, **kwargs) def HasLineSpacing(*args, **kwargs): """HasLineSpacing(self) -> bool""" return _controls_.TextAttr_HasLineSpacing(*args, **kwargs) def HasCharacterStyleName(*args, **kwargs): """HasCharacterStyleName(self) -> bool""" return _controls_.TextAttr_HasCharacterStyleName(*args, **kwargs) def HasParagraphStyleName(*args, **kwargs): """HasParagraphStyleName(self) -> bool""" return _controls_.TextAttr_HasParagraphStyleName(*args, **kwargs) def HasListStyleName(*args, **kwargs): """HasListStyleName(self) -> bool""" return _controls_.TextAttr_HasListStyleName(*args, **kwargs) def HasBulletStyle(*args, **kwargs): """HasBulletStyle(self) -> bool""" return _controls_.TextAttr_HasBulletStyle(*args, **kwargs) def HasBulletNumber(*args, **kwargs): """HasBulletNumber(self) -> bool""" return _controls_.TextAttr_HasBulletNumber(*args, **kwargs) def HasBulletText(*args, **kwargs): """HasBulletText(self) -> bool""" return _controls_.TextAttr_HasBulletText(*args, **kwargs) def HasBulletName(*args, **kwargs): """HasBulletName(self) -> bool""" return _controls_.TextAttr_HasBulletName(*args, **kwargs) def HasURL(*args, **kwargs): """HasURL(self) -> bool""" return _controls_.TextAttr_HasURL(*args, **kwargs) def HasPageBreak(*args, **kwargs): """HasPageBreak(self) -> bool""" return _controls_.TextAttr_HasPageBreak(*args, **kwargs) def HasTextEffects(*args, **kwargs): """HasTextEffects(self) -> bool""" return _controls_.TextAttr_HasTextEffects(*args, **kwargs) def HasTextEffect(*args, **kwargs): """HasTextEffect(self, int effect) -> bool""" return _controls_.TextAttr_HasTextEffect(*args, **kwargs) def HasOutlineLevel(*args, **kwargs): """HasOutlineLevel(self) -> bool""" return _controls_.TextAttr_HasOutlineLevel(*args, **kwargs) def HasFlag(*args, **kwargs): """HasFlag(self, long flag) -> bool""" return _controls_.TextAttr_HasFlag(*args, **kwargs) def RemoveFlag(*args, **kwargs): """RemoveFlag(self, long flag)""" return _controls_.TextAttr_RemoveFlag(*args, **kwargs) def AddFlag(*args, **kwargs): """AddFlag(self, long flag)""" return _controls_.TextAttr_AddFlag(*args, **kwargs) def IsCharacterStyle(*args, **kwargs): """IsCharacterStyle(self) -> bool""" return _controls_.TextAttr_IsCharacterStyle(*args, **kwargs) def IsParagraphStyle(*args, **kwargs): """IsParagraphStyle(self) -> bool""" return _controls_.TextAttr_IsParagraphStyle(*args, **kwargs) def IsDefault(*args, **kwargs): """IsDefault(self) -> bool""" return _controls_.TextAttr_IsDefault(*args, **kwargs) def Apply(*args, **kwargs): """Apply(self, TextAttr style, TextAttr compareWith=None) -> bool""" return _controls_.TextAttr_Apply(*args, **kwargs) def Merge(*args, **kwargs): """Merge(self, TextAttr overlay)""" return _controls_.TextAttr_Merge(*args, **kwargs) def Combine(*args, **kwargs): """Combine(TextAttr attr, TextAttr attrDef, TextCtrl text) -> TextAttr""" return _controls_.TextAttr_Combine(*args, **kwargs) Combine = staticmethod(Combine) def TabsEq(*args, **kwargs): """TabsEq(wxArrayInt tabs1, wxArrayInt tabs2) -> bool""" return _controls_.TextAttr_TabsEq(*args, **kwargs) TabsEq = staticmethod(TabsEq) def RemoveStyle(*args, **kwargs): """RemoveStyle(TextAttr destStyle, TextAttr style) -> bool""" return _controls_.TextAttr_RemoveStyle(*args, **kwargs) RemoveStyle = staticmethod(RemoveStyle) def CombineBitlists(*args, **kwargs): """CombineBitlists(int valueA, int valueB, int flagsA, int flagsB) -> bool""" return _controls_.TextAttr_CombineBitlists(*args, **kwargs) CombineBitlists = staticmethod(CombineBitlists) def BitlistsEqPartial(*args, **kwargs): """BitlistsEqPartial(int valueA, int valueB, int flags) -> bool""" return _controls_.TextAttr_BitlistsEqPartial(*args, **kwargs) BitlistsEqPartial = staticmethod(BitlistsEqPartial) def SplitParaCharStyles(*args, **kwargs): """SplitParaCharStyles(TextAttr style, TextAttr parStyle, TextAttr charStyle) -> bool""" return _controls_.TextAttr_SplitParaCharStyles(*args, **kwargs) SplitParaCharStyles = staticmethod(SplitParaCharStyles) Alignment = property(GetAlignment,SetAlignment) BackgroundColour = property(GetBackgroundColour,SetBackgroundColour) Flags = property(GetFlags,SetFlags) Font = property(GetFont,SetFont) LeftIndent = property(GetLeftIndent,SetLeftIndent) LeftSubIndent = property(GetLeftSubIndent) RightIndent = property(GetRightIndent,SetRightIndent) Tabs = property(GetTabs,SetTabs) TextColour = property(GetTextColour,SetTextColour) FontSize = property(GetFontSize,SetFontSize) FontStyle = property(GetFontStyle,SetFontStyle) FontWeight = property(GetFontWeight,SetFontWeight) FontUnderlined = property(GetFontUnderlined,SetFontUnderlined) FontFaceName = property(GetFontFaceName,SetFontFaceName) FontEncoding = property(GetFontEncoding,SetFontEncoding) FontFamily = property(GetFontFamily,SetFontFamily) CharacterStyleName = property(GetCharacterStyleName,SetCharacterStyleName) ParagraphStyleName = property(GetParagraphStyleName,SetParagraphStyleName) ListStyleName = property(GetListStyleName,SetListStyleName) ParagraphSpacingAfter = property(GetParagraphSpacingAfter,SetParagraphSpacingAfter) ParagraphSpacingBefore = property(GetParagraphSpacingBefore,SetParagraphSpacingBefore) LineSpacing = property(GetLineSpacing,SetLineSpacing) BulletStyle = property(GetBulletStyle,SetBulletStyle) BulletNumber = property(GetBulletNumber,SetBulletNumber) BulletText = property(GetBulletText,SetBulletText) BulletFont = property(GetBulletFont,SetBulletFont) BulletName = property(GetBulletName,SetBulletName) URL = property(GetURL,SetURL) TextEffects = property(GetTextEffects,SetTextEffects) TextEffectFlags = property(GetTextEffectFlags,SetTextEffectFlags) OutlineLevel = property(GetOutlineLevel,SetOutlineLevel) _controls_.TextAttr_swigregister(TextAttr) TextCtrlNameStr = cvar.TextCtrlNameStr def TextAttr_Combine(*args, **kwargs): """TextAttr_Combine(TextAttr attr, TextAttr attrDef, TextCtrl text) -> TextAttr""" return _controls_.TextAttr_Combine(*args, **kwargs) def TextAttr_TabsEq(*args, **kwargs): """TextAttr_TabsEq(wxArrayInt tabs1, wxArrayInt tabs2) -> bool""" return _controls_.TextAttr_TabsEq(*args, **kwargs) def TextAttr_RemoveStyle(*args, **kwargs): """TextAttr_RemoveStyle(TextAttr destStyle, TextAttr style) -> bool""" return _controls_.TextAttr_RemoveStyle(*args, **kwargs) def TextAttr_CombineBitlists(*args, **kwargs): """TextAttr_CombineBitlists(int valueA, int valueB, int flagsA, int flagsB) -> bool""" return _controls_.TextAttr_CombineBitlists(*args, **kwargs) def TextAttr_BitlistsEqPartial(*args, **kwargs): """TextAttr_BitlistsEqPartial(int valueA, int valueB, int flags) -> bool""" return _controls_.TextAttr_BitlistsEqPartial(*args, **kwargs) def TextAttr_SplitParaCharStyles(*args, **kwargs): """TextAttr_SplitParaCharStyles(TextAttr style, TextAttr parStyle, TextAttr charStyle) -> bool""" return _controls_.TextAttr_SplitParaCharStyles(*args, **kwargs) class TextCtrl(_core.TextCtrlBase): """Proxy of C++ TextCtrl class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=TextCtrlNameStr) -> TextCtrl """ _controls_.TextCtrl_swiginit(self,_controls_.new_TextCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=TextCtrlNameStr) -> bool """ return _controls_.TextCtrl_Create(*args, **kwargs) def IsSingleLine(*args, **kwargs): """IsSingleLine(self) -> bool""" return _controls_.TextCtrl_IsSingleLine(*args, **kwargs) def IsMultiLine(*args, **kwargs): """IsMultiLine(self) -> bool""" return _controls_.TextCtrl_IsMultiLine(*args, **kwargs) def EmulateKeyPress(*args, **kwargs): """EmulateKeyPress(self, KeyEvent event) -> bool""" return _controls_.TextCtrl_EmulateKeyPress(*args, **kwargs) def MacCheckSpelling(*args, **kwargs): """MacCheckSpelling(self, bool check)""" return _controls_.TextCtrl_MacCheckSpelling(*args, **kwargs) def SendTextUpdatedEvent(*args, **kwargs): """SendTextUpdatedEvent(self)""" return _controls_.TextCtrl_SendTextUpdatedEvent(*args, **kwargs) def write(*args, **kwargs): """write(self, String text)""" return _controls_.TextCtrl_write(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.TextCtrl_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) _controls_.TextCtrl_swigregister(TextCtrl) def PreTextCtrl(*args, **kwargs): """PreTextCtrl() -> TextCtrl""" val = _controls_.new_PreTextCtrl(*args, **kwargs) return val def TextCtrl_GetClassDefaultAttributes(*args, **kwargs): """ TextCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.TextCtrl_GetClassDefaultAttributes(*args, **kwargs) wxEVT_COMMAND_TEXT_UPDATED = _controls_.wxEVT_COMMAND_TEXT_UPDATED wxEVT_COMMAND_TEXT_ENTER = _controls_.wxEVT_COMMAND_TEXT_ENTER wxEVT_COMMAND_TEXT_URL = _controls_.wxEVT_COMMAND_TEXT_URL wxEVT_COMMAND_TEXT_MAXLEN = _controls_.wxEVT_COMMAND_TEXT_MAXLEN class TextUrlEvent(_core.CommandEvent): """Proxy of C++ TextUrlEvent class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self, int winid, MouseEvent evtMouse, long start, long end) -> TextUrlEvent""" _controls_.TextUrlEvent_swiginit(self,_controls_.new_TextUrlEvent(*args, **kwargs)) def GetMouseEvent(*args, **kwargs): """GetMouseEvent(self) -> MouseEvent""" return _controls_.TextUrlEvent_GetMouseEvent(*args, **kwargs) def GetURLStart(*args, **kwargs): """GetURLStart(self) -> long""" return _controls_.TextUrlEvent_GetURLStart(*args, **kwargs) def GetURLEnd(*args, **kwargs): """GetURLEnd(self) -> long""" return _controls_.TextUrlEvent_GetURLEnd(*args, **kwargs) MouseEvent = property(GetMouseEvent,doc="See `GetMouseEvent`") URLEnd = property(GetURLEnd,doc="See `GetURLEnd`") URLStart = property(GetURLStart,doc="See `GetURLStart`") _controls_.TextUrlEvent_swigregister(TextUrlEvent) EVT_TEXT = wx.PyEventBinder( wxEVT_COMMAND_TEXT_UPDATED, 1) EVT_TEXT_ENTER = wx.PyEventBinder( wxEVT_COMMAND_TEXT_ENTER, 1) EVT_TEXT_URL = wx.PyEventBinder( wxEVT_COMMAND_TEXT_URL, 1) EVT_TEXT_MAXLEN = wx.PyEventBinder( wxEVT_COMMAND_TEXT_MAXLEN, 1) #--------------------------------------------------------------------------- class ScrollBar(_core.Control): """Proxy of C++ ScrollBar class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=SB_HORIZONTAL, Validator validator=DefaultValidator, String name=ScrollBarNameStr) -> ScrollBar """ _controls_.ScrollBar_swiginit(self,_controls_.new_ScrollBar(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=SB_HORIZONTAL, Validator validator=DefaultValidator, String name=ScrollBarNameStr) -> bool Do the 2nd phase and create the GUI control. """ return _controls_.ScrollBar_Create(*args, **kwargs) def GetThumbPosition(*args, **kwargs): """GetThumbPosition(self) -> int""" return _controls_.ScrollBar_GetThumbPosition(*args, **kwargs) def GetThumbSize(*args, **kwargs): """GetThumbSize(self) -> int""" return _controls_.ScrollBar_GetThumbSize(*args, **kwargs) GetThumbLength = GetThumbSize def GetPageSize(*args, **kwargs): """GetPageSize(self) -> int""" return _controls_.ScrollBar_GetPageSize(*args, **kwargs) def GetRange(*args, **kwargs): """GetRange(self) -> int""" return _controls_.ScrollBar_GetRange(*args, **kwargs) def IsVertical(*args, **kwargs): """IsVertical(self) -> bool""" return _controls_.ScrollBar_IsVertical(*args, **kwargs) def SetThumbPosition(*args, **kwargs): """SetThumbPosition(self, int viewStart)""" return _controls_.ScrollBar_SetThumbPosition(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ScrollBar_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) PageSize = property(GetPageSize,doc="See `GetPageSize`") Range = property(GetRange,doc="See `GetRange`") ThumbPosition = property(GetThumbPosition,SetThumbPosition,doc="See `GetThumbPosition` and `SetThumbPosition`") ThumbSize = property(GetThumbSize,doc="See `GetThumbSize`") _controls_.ScrollBar_swigregister(ScrollBar) ScrollBarNameStr = cvar.ScrollBarNameStr def PreScrollBar(*args, **kwargs): """PreScrollBar() -> ScrollBar""" val = _controls_.new_PreScrollBar(*args, **kwargs) return val def ScrollBar_GetClassDefaultAttributes(*args, **kwargs): """ ScrollBar_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ScrollBar_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- SP_HORIZONTAL = _controls_.SP_HORIZONTAL SP_VERTICAL = _controls_.SP_VERTICAL SP_ARROW_KEYS = _controls_.SP_ARROW_KEYS SP_WRAP = _controls_.SP_WRAP class SpinButton(_core.Control): """Proxy of C++ SpinButton class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=SP_HORIZONTAL, String name=SPIN_BUTTON_NAME) -> SpinButton """ _controls_.SpinButton_swiginit(self,_controls_.new_SpinButton(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=SP_HORIZONTAL, String name=SPIN_BUTTON_NAME) -> bool """ return _controls_.SpinButton_Create(*args, **kwargs) def GetValue(*args, **kwargs): """GetValue(self) -> int""" return _controls_.SpinButton_GetValue(*args, **kwargs) def GetMin(*args, **kwargs): """GetMin(self) -> int""" return _controls_.SpinButton_GetMin(*args, **kwargs) def GetMax(*args, **kwargs): """GetMax(self) -> int""" return _controls_.SpinButton_GetMax(*args, **kwargs) def SetValue(*args, **kwargs): """SetValue(self, int val)""" return _controls_.SpinButton_SetValue(*args, **kwargs) def SetMin(*args, **kwargs): """SetMin(self, int minVal)""" return _controls_.SpinButton_SetMin(*args, **kwargs) def SetMax(*args, **kwargs): """SetMax(self, int maxVal)""" return _controls_.SpinButton_SetMax(*args, **kwargs) def SetRange(*args, **kwargs): """SetRange(self, int minVal, int maxVal)""" return _controls_.SpinButton_SetRange(*args, **kwargs) def IsVertical(*args, **kwargs): """IsVertical(self) -> bool""" return _controls_.SpinButton_IsVertical(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.SpinButton_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) Max = property(GetMax,SetMax,doc="See `GetMax` and `SetMax`") Min = property(GetMin,SetMin,doc="See `GetMin` and `SetMin`") Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`") _controls_.SpinButton_swigregister(SpinButton) SPIN_BUTTON_NAME = cvar.SPIN_BUTTON_NAME SpinCtrlNameStr = cvar.SpinCtrlNameStr def PreSpinButton(*args, **kwargs): """PreSpinButton() -> SpinButton""" val = _controls_.new_PreSpinButton(*args, **kwargs) return val def SpinButton_GetClassDefaultAttributes(*args, **kwargs): """ SpinButton_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.SpinButton_GetClassDefaultAttributes(*args, **kwargs) class SpinCtrl(_core.Control): """Proxy of C++ SpinCtrl class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxSP_ARROW_KEYS|wxALIGN_RIGHT, int min=0, int max=100, int initial=0, String name=SpinCtrlNameStr) -> SpinCtrl """ _controls_.SpinCtrl_swiginit(self,_controls_.new_SpinCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=SP_ARROW_KEYS, int min=0, int max=100, int initial=0, String name=SpinCtrlNameStr) -> bool """ return _controls_.SpinCtrl_Create(*args, **kwargs) def GetValue(*args, **kwargs): """GetValue(self) -> int""" return _controls_.SpinCtrl_GetValue(*args, **kwargs) def SetValue(*args, **kwargs): """SetValue(self, int value)""" return _controls_.SpinCtrl_SetValue(*args, **kwargs) def SetValueString(*args, **kwargs): """SetValueString(self, String text)""" return _controls_.SpinCtrl_SetValueString(*args, **kwargs) def SetRange(*args, **kwargs): """SetRange(self, int minVal, int maxVal)""" return _controls_.SpinCtrl_SetRange(*args, **kwargs) def GetMin(*args, **kwargs): """GetMin(self) -> int""" return _controls_.SpinCtrl_GetMin(*args, **kwargs) def GetMax(*args, **kwargs): """GetMax(self) -> int""" return _controls_.SpinCtrl_GetMax(*args, **kwargs) def SetSelection(*args, **kwargs): """SetSelection(self, long from, long to)""" return _controls_.SpinCtrl_SetSelection(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.SpinCtrl_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) Max = property(GetMax,doc="See `GetMax`") Min = property(GetMin,doc="See `GetMin`") Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`") _controls_.SpinCtrl_swigregister(SpinCtrl) def PreSpinCtrl(*args, **kwargs): """PreSpinCtrl() -> SpinCtrl""" val = _controls_.new_PreSpinCtrl(*args, **kwargs) return val def SpinCtrl_GetClassDefaultAttributes(*args, **kwargs): """ SpinCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.SpinCtrl_GetClassDefaultAttributes(*args, **kwargs) class SpinEvent(_core.NotifyEvent): """Proxy of C++ SpinEvent class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self, EventType commandType=wxEVT_NULL, int winid=0) -> SpinEvent""" _controls_.SpinEvent_swiginit(self,_controls_.new_SpinEvent(*args, **kwargs)) def GetPosition(*args, **kwargs): """GetPosition(self) -> int""" return _controls_.SpinEvent_GetPosition(*args, **kwargs) def SetPosition(*args, **kwargs): """SetPosition(self, int pos)""" return _controls_.SpinEvent_SetPosition(*args, **kwargs) def GetValue(*args, **kwargs): """GetValue(self) -> int""" return _controls_.SpinEvent_GetValue(*args, **kwargs) def SetValue(*args, **kwargs): """SetValue(self, int value)""" return _controls_.SpinEvent_SetValue(*args, **kwargs) Position = property(GetPosition,SetPosition) Value = property(GetValue,SetValue) _controls_.SpinEvent_swigregister(SpinEvent) wxEVT_SPIN_UP = _controls_.wxEVT_SPIN_UP wxEVT_SPIN_DOWN = _controls_.wxEVT_SPIN_DOWN wxEVT_SPIN = _controls_.wxEVT_SPIN wxEVT_COMMAND_SPINCTRL_UPDATED = _controls_.wxEVT_COMMAND_SPINCTRL_UPDATED wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED = _controls_.wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED EVT_SPIN_UP = wx.PyEventBinder( wxEVT_SPIN_UP, 1) EVT_SPIN_DOWN = wx.PyEventBinder( wxEVT_SPIN_DOWN, 1) EVT_SPIN = wx.PyEventBinder( wxEVT_SPIN, 1) EVT_SPINCTRL = wx.PyEventBinder( wxEVT_COMMAND_SPINCTRL_UPDATED, 1) EVT_SPINCTRLDOUBLE = wx.PyEventBinder( wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, 1) class SpinCtrlDouble(_core.Control): """Proxy of C++ SpinCtrlDouble class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=ID_ANY, String value=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxSP_ARROW_KEYS|wxALIGN_RIGHT, double min=0, double max=100, double initial=0, double inc=1, String name="wxSpinCtrlDouble") -> SpinCtrlDouble """ _controls_.SpinCtrlDouble_swiginit(self,_controls_.new_SpinCtrlDouble(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=ID_ANY, String value=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=SP_ARROW_KEYS, double min=0, double max=100, double initial=0, double inc=1, String name="wxSpinCtrlDouble") -> bool """ return _controls_.SpinCtrlDouble_Create(*args, **kwargs) def GetValue(*args, **kwargs): """GetValue(self) -> double""" return _controls_.SpinCtrlDouble_GetValue(*args, **kwargs) def GetMin(*args, **kwargs): """GetMin(self) -> double""" return _controls_.SpinCtrlDouble_GetMin(*args, **kwargs) def GetMax(*args, **kwargs): """GetMax(self) -> double""" return _controls_.SpinCtrlDouble_GetMax(*args, **kwargs) def GetIncrement(*args, **kwargs): """GetIncrement(self) -> double""" return _controls_.SpinCtrlDouble_GetIncrement(*args, **kwargs) def GetDigits(*args, **kwargs): """GetDigits(self) -> unsigned int""" return _controls_.SpinCtrlDouble_GetDigits(*args, **kwargs) def SetValue(*args, **kwargs): """SetValue(self, double value)""" return _controls_.SpinCtrlDouble_SetValue(*args, **kwargs) def SetRange(*args, **kwargs): """SetRange(self, double minVal, double maxVal)""" return _controls_.SpinCtrlDouble_SetRange(*args, **kwargs) def SetMin(self, minVal): self.SetRange(minVal, self.GetMax()) def SetMax(self, maxVal): self.SetRange(self.GetMin(), maxVal) def SetIncrement(*args, **kwargs): """SetIncrement(self, double inc)""" return _controls_.SpinCtrlDouble_SetIncrement(*args, **kwargs) def SetDigits(*args, **kwargs): """SetDigits(self, unsigned int digits)""" return _controls_.SpinCtrlDouble_SetDigits(*args, **kwargs) Value = property(GetValue,SetValue) Min = property(GetMin,SetMin) Max = property(GetMax,SetMax) Increment = property(GetIncrement,SetIncrement) Digits = property(GetDigits,SetDigits) _controls_.SpinCtrlDouble_swigregister(SpinCtrlDouble) def PreSpinCtrlDouble(*args, **kwargs): """PreSpinCtrlDouble() -> SpinCtrlDouble""" val = _controls_.new_PreSpinCtrlDouble(*args, **kwargs) return val class SpinDoubleEvent(_core.NotifyEvent): """Proxy of C++ SpinDoubleEvent class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self, EventType commandType=wxEVT_NULL, int winid=0, double value=0) -> SpinDoubleEvent""" _controls_.SpinDoubleEvent_swiginit(self,_controls_.new_SpinDoubleEvent(*args, **kwargs)) def GetValue(*args, **kwargs): """GetValue(self) -> double""" return _controls_.SpinDoubleEvent_GetValue(*args, **kwargs) def SetValue(*args, **kwargs): """SetValue(self, double value)""" return _controls_.SpinDoubleEvent_SetValue(*args, **kwargs) Value = property(GetValue,SetValue) _controls_.SpinDoubleEvent_swigregister(SpinDoubleEvent) EVT_SPINCTRLDOUBLE = wx.PyEventBinder( wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, 1 ) #--------------------------------------------------------------------------- class RadioBox(_core.Control): """Proxy of C++ RadioBox class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray, int majorDimension=0, long style=RA_HORIZONTAL, Validator validator=DefaultValidator, String name=RadioBoxNameStr) -> RadioBox """ if kwargs.has_key('point'): kwargs['pos'] = kwargs['point'];del kwargs['point'] _controls_.RadioBox_swiginit(self,_controls_.new_RadioBox(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, wxArrayString choices=wxPyEmptyStringArray, int majorDimension=0, long style=RA_HORIZONTAL, Validator validator=DefaultValidator, String name=RadioBoxNameStr) -> bool """ return _controls_.RadioBox_Create(*args, **kwargs) def SetSelection(*args, **kwargs): """SetSelection(self, int n)""" return _controls_.RadioBox_SetSelection(*args, **kwargs) def GetSelection(*args, **kwargs): """GetSelection(self) -> int""" return _controls_.RadioBox_GetSelection(*args, **kwargs) def GetStringSelection(*args, **kwargs): """GetStringSelection(self) -> String""" return _controls_.RadioBox_GetStringSelection(*args, **kwargs) def SetStringSelection(*args, **kwargs): """SetStringSelection(self, String s) -> bool""" return _controls_.RadioBox_SetStringSelection(*args, **kwargs) def GetCount(*args, **kwargs): """GetCount(self) -> size_t""" return _controls_.RadioBox_GetCount(*args, **kwargs) def FindString(*args, **kwargs): """FindString(self, String s) -> int""" return _controls_.RadioBox_FindString(*args, **kwargs) def GetString(*args, **kwargs): """GetString(self, int n) -> String""" return _controls_.RadioBox_GetString(*args, **kwargs) def SetString(*args, **kwargs): """SetString(self, int n, String label)""" return _controls_.RadioBox_SetString(*args, **kwargs) GetItemLabel = GetString SetItemLabel = SetString def EnableItem(*args, **kwargs): """EnableItem(self, unsigned int n, bool enable=True)""" return _controls_.RadioBox_EnableItem(*args, **kwargs) def ShowItem(*args, **kwargs): """ShowItem(self, unsigned int n, bool show=True)""" return _controls_.RadioBox_ShowItem(*args, **kwargs) def IsItemEnabled(*args, **kwargs): """IsItemEnabled(self, unsigned int n) -> bool""" return _controls_.RadioBox_IsItemEnabled(*args, **kwargs) def IsItemShown(*args, **kwargs): """IsItemShown(self, unsigned int n) -> bool""" return _controls_.RadioBox_IsItemShown(*args, **kwargs) def GetColumnCount(*args, **kwargs): """GetColumnCount(self) -> unsigned int""" return _controls_.RadioBox_GetColumnCount(*args, **kwargs) def GetRowCount(*args, **kwargs): """GetRowCount(self) -> unsigned int""" return _controls_.RadioBox_GetRowCount(*args, **kwargs) def GetNextItem(*args, **kwargs): """GetNextItem(self, int item, int dir, long style) -> int""" return _controls_.RadioBox_GetNextItem(*args, **kwargs) def SetItemToolTip(*args, **kwargs): """SetItemToolTip(self, unsigned int item, String text)""" return _controls_.RadioBox_SetItemToolTip(*args, **kwargs) def GetItemToolTip(*args, **kwargs): """GetItemToolTip(self, unsigned int item) -> ToolTip""" return _controls_.RadioBox_GetItemToolTip(*args, **kwargs) def SetItemHelpText(*args, **kwargs): """SetItemHelpText(self, unsigned int n, String helpText)""" return _controls_.RadioBox_SetItemHelpText(*args, **kwargs) def GetItemHelpText(*args, **kwargs): """GetItemHelpText(self, unsigned int n) -> String""" return _controls_.RadioBox_GetItemHelpText(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.RadioBox_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) ColumnCount = property(GetColumnCount,doc="See `GetColumnCount`") Count = property(GetCount,doc="See `GetCount`") RowCount = property(GetRowCount,doc="See `GetRowCount`") Selection = property(GetSelection,SetSelection,doc="See `GetSelection` and `SetSelection`") StringSelection = property(GetStringSelection,SetStringSelection,doc="See `GetStringSelection` and `SetStringSelection`") _controls_.RadioBox_swigregister(RadioBox) RadioBoxNameStr = cvar.RadioBoxNameStr RadioButtonNameStr = cvar.RadioButtonNameStr def PreRadioBox(*args, **kwargs): """PreRadioBox() -> RadioBox""" val = _controls_.new_PreRadioBox(*args, **kwargs) return val def RadioBox_GetClassDefaultAttributes(*args, **kwargs): """ RadioBox_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.RadioBox_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- class RadioButton(_core.Control): """Proxy of C++ RadioButton class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=RadioButtonNameStr) -> RadioButton """ _controls_.RadioButton_swiginit(self,_controls_.new_RadioButton(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=RadioButtonNameStr) -> bool """ return _controls_.RadioButton_Create(*args, **kwargs) def GetValue(*args, **kwargs): """GetValue(self) -> bool""" return _controls_.RadioButton_GetValue(*args, **kwargs) def SetValue(*args, **kwargs): """SetValue(self, bool value)""" return _controls_.RadioButton_SetValue(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.RadioButton_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`") _controls_.RadioButton_swigregister(RadioButton) def PreRadioButton(*args, **kwargs): """PreRadioButton() -> RadioButton""" val = _controls_.new_PreRadioButton(*args, **kwargs) return val def RadioButton_GetClassDefaultAttributes(*args, **kwargs): """ RadioButton_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.RadioButton_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- SL_HORIZONTAL = _controls_.SL_HORIZONTAL SL_VERTICAL = _controls_.SL_VERTICAL SL_TICKS = _controls_.SL_TICKS SL_AUTOTICKS = _controls_.SL_AUTOTICKS SL_LEFT = _controls_.SL_LEFT SL_TOP = _controls_.SL_TOP SL_RIGHT = _controls_.SL_RIGHT SL_BOTTOM = _controls_.SL_BOTTOM SL_BOTH = _controls_.SL_BOTH SL_SELRANGE = _controls_.SL_SELRANGE SL_INVERSE = _controls_.SL_INVERSE SL_MIN_MAX_LABELS = _controls_.SL_MIN_MAX_LABELS SL_VALUE_LABEL = _controls_.SL_VALUE_LABEL SL_LABELS = _controls_.SL_LABELS class Slider(_core.Control): """Proxy of C++ Slider class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, int value=0, int minValue=0, int maxValue=100, Point pos=DefaultPosition, Size size=DefaultSize, long style=SL_HORIZONTAL, Validator validator=DefaultValidator, String name=SliderNameStr) -> Slider """ if kwargs.has_key('point'): kwargs['pos'] = kwargs['point'];del kwargs['point'] _controls_.Slider_swiginit(self,_controls_.new_Slider(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, int value=0, int minValue=0, int maxValue=100, Point pos=DefaultPosition, Size size=DefaultSize, long style=SL_HORIZONTAL, Validator validator=DefaultValidator, String name=SliderNameStr) -> bool """ return _controls_.Slider_Create(*args, **kwargs) def GetValue(*args, **kwargs): """GetValue(self) -> int""" return _controls_.Slider_GetValue(*args, **kwargs) def SetValue(*args, **kwargs): """SetValue(self, int value)""" return _controls_.Slider_SetValue(*args, **kwargs) def GetMin(*args, **kwargs): """GetMin(self) -> int""" return _controls_.Slider_GetMin(*args, **kwargs) def GetMax(*args, **kwargs): """GetMax(self) -> int""" return _controls_.Slider_GetMax(*args, **kwargs) def SetMin(*args, **kwargs): """SetMin(self, int minValue)""" return _controls_.Slider_SetMin(*args, **kwargs) def SetMax(*args, **kwargs): """SetMax(self, int maxValue)""" return _controls_.Slider_SetMax(*args, **kwargs) def SetRange(*args, **kwargs): """SetRange(self, int minValue, int maxValue)""" return _controls_.Slider_SetRange(*args, **kwargs) def GetRange(self): return self.GetMin(), self.GetMax() def SetLineSize(*args, **kwargs): """SetLineSize(self, int lineSize)""" return _controls_.Slider_SetLineSize(*args, **kwargs) def SetPageSize(*args, **kwargs): """SetPageSize(self, int pageSize)""" return _controls_.Slider_SetPageSize(*args, **kwargs) def GetLineSize(*args, **kwargs): """GetLineSize(self) -> int""" return _controls_.Slider_GetLineSize(*args, **kwargs) def GetPageSize(*args, **kwargs): """GetPageSize(self) -> int""" return _controls_.Slider_GetPageSize(*args, **kwargs) def SetThumbLength(*args, **kwargs): """SetThumbLength(self, int lenPixels)""" return _controls_.Slider_SetThumbLength(*args, **kwargs) def GetThumbLength(*args, **kwargs): """GetThumbLength(self) -> int""" return _controls_.Slider_GetThumbLength(*args, **kwargs) def SetTickFreq(*args, **kwargs): """SetTickFreq(self, int n, int pos=1)""" return _controls_.Slider_SetTickFreq(*args, **kwargs) def GetTickFreq(*args, **kwargs): """GetTickFreq(self) -> int""" return _controls_.Slider_GetTickFreq(*args, **kwargs) def ClearTicks(*args, **kwargs): """ClearTicks(self)""" return _controls_.Slider_ClearTicks(*args, **kwargs) def SetTick(*args, **kwargs): """SetTick(self, int tickPos)""" return _controls_.Slider_SetTick(*args, **kwargs) def ClearSel(*args, **kwargs): """ClearSel(self)""" return _controls_.Slider_ClearSel(*args, **kwargs) def GetSelEnd(*args, **kwargs): """GetSelEnd(self) -> int""" return _controls_.Slider_GetSelEnd(*args, **kwargs) def GetSelStart(*args, **kwargs): """GetSelStart(self) -> int""" return _controls_.Slider_GetSelStart(*args, **kwargs) def SetSelection(*args, **kwargs): """SetSelection(self, int min, int max)""" return _controls_.Slider_SetSelection(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.Slider_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) LineSize = property(GetLineSize,SetLineSize,doc="See `GetLineSize` and `SetLineSize`") Max = property(GetMax,SetMax,doc="See `GetMax` and `SetMax`") Min = property(GetMin,SetMin,doc="See `GetMin` and `SetMin`") PageSize = property(GetPageSize,SetPageSize,doc="See `GetPageSize` and `SetPageSize`") SelEnd = property(GetSelEnd,doc="See `GetSelEnd`") SelStart = property(GetSelStart,doc="See `GetSelStart`") ThumbLength = property(GetThumbLength,SetThumbLength,doc="See `GetThumbLength` and `SetThumbLength`") TickFreq = property(GetTickFreq,SetTickFreq,doc="See `GetTickFreq` and `SetTickFreq`") Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`") _controls_.Slider_swigregister(Slider) SliderNameStr = cvar.SliderNameStr def PreSlider(*args, **kwargs): """PreSlider() -> Slider""" val = _controls_.new_PreSlider(*args, **kwargs) return val def Slider_GetClassDefaultAttributes(*args, **kwargs): """ Slider_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.Slider_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- wxEVT_COMMAND_TOGGLEBUTTON_CLICKED = _controls_.wxEVT_COMMAND_TOGGLEBUTTON_CLICKED EVT_TOGGLEBUTTON = wx.PyEventBinder( wxEVT_COMMAND_TOGGLEBUTTON_CLICKED, 1) class ToggleButton(AnyButton): """Proxy of C++ ToggleButton class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=ToggleButtonNameStr) -> ToggleButton """ _controls_.ToggleButton_swiginit(self,_controls_.new_ToggleButton(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=ToggleButtonNameStr) -> bool """ return _controls_.ToggleButton_Create(*args, **kwargs) def SetValue(*args, **kwargs): """SetValue(self, bool value)""" return _controls_.ToggleButton_SetValue(*args, **kwargs) def GetValue(*args, **kwargs): """GetValue(self) -> bool""" return _controls_.ToggleButton_GetValue(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ToggleButton_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`") _controls_.ToggleButton_swigregister(ToggleButton) ToggleButtonNameStr = cvar.ToggleButtonNameStr def PreToggleButton(*args, **kwargs): """PreToggleButton() -> ToggleButton""" val = _controls_.new_PreToggleButton(*args, **kwargs) return val def ToggleButton_GetClassDefaultAttributes(*args, **kwargs): """ ToggleButton_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ToggleButton_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- NB_FIXEDWIDTH = _controls_.NB_FIXEDWIDTH NB_TOP = _controls_.NB_TOP NB_LEFT = _controls_.NB_LEFT NB_RIGHT = _controls_.NB_RIGHT NB_BOTTOM = _controls_.NB_BOTTOM NB_MULTILINE = _controls_.NB_MULTILINE NB_NOPAGETHEME = _controls_.NB_NOPAGETHEME NB_HITTEST_NOWHERE = _controls_.NB_HITTEST_NOWHERE NB_HITTEST_ONICON = _controls_.NB_HITTEST_ONICON NB_HITTEST_ONLABEL = _controls_.NB_HITTEST_ONLABEL NB_HITTEST_ONITEM = _controls_.NB_HITTEST_ONITEM NB_HITTEST_ONPAGE = _controls_.NB_HITTEST_ONPAGE class Notebook(_core.BookCtrlBase): """Proxy of C++ Notebook class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=NotebookNameStr) -> Notebook """ _controls_.Notebook_swiginit(self,_controls_.new_Notebook(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=NotebookNameStr) -> bool """ return _controls_.Notebook_Create(*args, **kwargs) def GetRowCount(*args, **kwargs): """GetRowCount(self) -> int""" return _controls_.Notebook_GetRowCount(*args, **kwargs) def SetPadding(*args, **kwargs): """SetPadding(self, Size padding)""" return _controls_.Notebook_SetPadding(*args, **kwargs) def SetTabSize(*args, **kwargs): """SetTabSize(self, Size sz)""" return _controls_.Notebook_SetTabSize(*args, **kwargs) def GetThemeBackgroundColour(*args, **kwargs): """GetThemeBackgroundColour(self) -> Colour""" return _controls_.Notebook_GetThemeBackgroundColour(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.Notebook_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) def SendPageChangingEvent(*args, **kwargs): """SendPageChangingEvent(self, int nPage) -> bool""" return _controls_.Notebook_SendPageChangingEvent(*args, **kwargs) def SendPageChangedEvent(*args, **kwargs): """SendPageChangedEvent(self, int nPageOld, int nPageNew=-1)""" return _controls_.Notebook_SendPageChangedEvent(*args, **kwargs) RowCount = property(GetRowCount,doc="See `GetRowCount`") ThemeBackgroundColour = property(GetThemeBackgroundColour,doc="See `GetThemeBackgroundColour`") _controls_.Notebook_swigregister(Notebook) NotebookNameStr = cvar.NotebookNameStr def PreNotebook(*args, **kwargs): """PreNotebook() -> Notebook""" val = _controls_.new_PreNotebook(*args, **kwargs) return val def Notebook_GetClassDefaultAttributes(*args, **kwargs): """ Notebook_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.Notebook_GetClassDefaultAttributes(*args, **kwargs) NotebookEvent = wx.BookCtrlEvent wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING # wxNotebook events EVT_NOTEBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED, 1 ) EVT_NOTEBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING, 1 ) #---------------------------------------------------------------------------- class NotebookPage(wx.Panel): """ There is an old (and apparently unsolvable) bug when placing a window with a nonstandard background colour in a wx.Notebook on wxGTK1, as the notbooks's background colour would always be used when the window is refreshed. The solution is to place a panel in the notbook and the coloured window on the panel, sized to cover the panel. This simple class does that for you, just put an instance of this in the notebook and make your regular window a child of this one and it will handle the resize for you. """ def __init__(self, parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.TAB_TRAVERSAL, name="panel"): wx.Panel.__init__(self, parent, id, pos, size, style, name) self.child = None self.Bind(wx.EVT_SIZE, self.OnSize) def OnSize(self, evt): if self.child is None: children = self.GetChildren() if len(children): self.child = children[0] if self.child: self.child.SetPosition((0,0)) self.child.SetSize(self.GetSize()) #--------------------------------------------------------------------------- LB_DEFAULT = _controls_.LB_DEFAULT LB_TOP = _controls_.LB_TOP LB_BOTTOM = _controls_.LB_BOTTOM LB_LEFT = _controls_.LB_LEFT LB_RIGHT = _controls_.LB_RIGHT LB_ALIGN_MASK = _controls_.LB_ALIGN_MASK class Listbook(_core.BookCtrlBase): """Proxy of C++ Listbook class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=EmptyString) -> Listbook """ _controls_.Listbook_swiginit(self,_controls_.new_Listbook(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=EmptyString) -> bool """ return _controls_.Listbook_Create(*args, **kwargs) def GetListView(*args, **kwargs): """GetListView(self) -> ListView""" return _controls_.Listbook_GetListView(*args, **kwargs) ListView = property(GetListView,doc="See `GetListView`") _controls_.Listbook_swigregister(Listbook) def PreListbook(*args, **kwargs): """PreListbook() -> Listbook""" val = _controls_.new_PreListbook(*args, **kwargs) return val ListbookEvent = wx.BookCtrlEvent wxEVT_COMMAND_LISTBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_LISTBOOK_PAGE_CHANGED wxEVT_COMMAND_LISTBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_LISTBOOK_PAGE_CHANGING EVT_LISTBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_LISTBOOK_PAGE_CHANGED, 1 ) EVT_LISTBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_LISTBOOK_PAGE_CHANGING, 1 ) CHB_DEFAULT = _controls_.CHB_DEFAULT CHB_TOP = _controls_.CHB_TOP CHB_BOTTOM = _controls_.CHB_BOTTOM CHB_LEFT = _controls_.CHB_LEFT CHB_RIGHT = _controls_.CHB_RIGHT CHB_ALIGN_MASK = _controls_.CHB_ALIGN_MASK class Choicebook(_core.BookCtrlBase): """Proxy of C++ Choicebook class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=EmptyString) -> Choicebook """ _controls_.Choicebook_swiginit(self,_controls_.new_Choicebook(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=EmptyString) -> bool """ return _controls_.Choicebook_Create(*args, **kwargs) def GetChoiceCtrl(*args, **kwargs): """GetChoiceCtrl(self) -> Choice""" return _controls_.Choicebook_GetChoiceCtrl(*args, **kwargs) ChoiceCtrl = property(GetChoiceCtrl,doc="See `GetChoiceCtrl`") _controls_.Choicebook_swigregister(Choicebook) def PreChoicebook(*args, **kwargs): """PreChoicebook() -> Choicebook""" val = _controls_.new_PreChoicebook(*args, **kwargs) return val ChoicebookEvent = wx.BookCtrlEvent wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING EVT_CHOICEBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGED, 1 ) EVT_CHOICEBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_CHOICEBOOK_PAGE_CHANGING, 1 ) #--------------------------------------------------------------------------- class Treebook(_core.BookCtrlBase): """Proxy of C++ Treebook class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, long style=BK_DEFAULT, String name=EmptyString) -> Treebook """ _controls_.Treebook_swiginit(self,_controls_.new_Treebook(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, long style=BK_DEFAULT, String name=EmptyString) -> bool """ return _controls_.Treebook_Create(*args, **kwargs) def InsertSubPage(*args, **kwargs): """ InsertSubPage(self, size_t pos, Window page, String text, bool select=False, int imageId=NOT_FOUND) -> bool """ return _controls_.Treebook_InsertSubPage(*args, **kwargs) def AddSubPage(*args, **kwargs): """AddSubPage(self, Window page, String text, bool select=False, int imageId=NOT_FOUND) -> bool""" return _controls_.Treebook_AddSubPage(*args, **kwargs) def IsNodeExpanded(*args, **kwargs): """IsNodeExpanded(self, size_t pos) -> bool""" return _controls_.Treebook_IsNodeExpanded(*args, **kwargs) def ExpandNode(*args, **kwargs): """ExpandNode(self, size_t pos, bool expand=True) -> bool""" return _controls_.Treebook_ExpandNode(*args, **kwargs) def CollapseNode(*args, **kwargs): """CollapseNode(self, size_t pos) -> bool""" return _controls_.Treebook_CollapseNode(*args, **kwargs) def GetPageParent(*args, **kwargs): """GetPageParent(self, size_t pos) -> int""" return _controls_.Treebook_GetPageParent(*args, **kwargs) def GetTreeCtrl(*args, **kwargs): """GetTreeCtrl(self) -> TreeCtrl""" return _controls_.Treebook_GetTreeCtrl(*args, **kwargs) TreeCtrl = property(GetTreeCtrl,doc="See `GetTreeCtrl`") _controls_.Treebook_swigregister(Treebook) def PreTreebook(*args, **kwargs): """PreTreebook() -> Treebook""" val = _controls_.new_PreTreebook(*args, **kwargs) return val TreebookEvent = wx.BookCtrlEvent wxEVT_COMMAND_TREEBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_TREEBOOK_PAGE_CHANGED wxEVT_COMMAND_TREEBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_TREEBOOK_PAGE_CHANGING wxEVT_COMMAND_TREEBOOK_NODE_COLLAPSED = _controls_.wxEVT_COMMAND_TREEBOOK_NODE_COLLAPSED wxEVT_COMMAND_TREEBOOK_NODE_EXPANDED = _controls_.wxEVT_COMMAND_TREEBOOK_NODE_EXPANDED EVT_TREEBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_TREEBOOK_PAGE_CHANGED, 1 ) EVT_TREEBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_TREEBOOK_PAGE_CHANGING, 1) EVT_TREEBOOK_NODE_COLLAPSED = wx.PyEventBinder( wxEVT_COMMAND_TREEBOOK_NODE_COLLAPSED, 1 ) EVT_TREEBOOK_NODE_EXPANDED = wx.PyEventBinder( wxEVT_COMMAND_TREEBOOK_NODE_EXPANDED, 1 ) #--------------------------------------------------------------------------- class Toolbook(_core.BookCtrlBase): """Proxy of C++ Toolbook class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, long style=BK_DEFAULT, String name=EmptyString) -> Toolbook """ _controls_.Toolbook_swiginit(self,_controls_.new_Toolbook(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, String name=wxEmptyString) -> bool """ return _controls_.Toolbook_Create(*args, **kwargs) def GetToolBar(*args, **kwargs): """GetToolBar(self) -> ToolBarBase""" return _controls_.Toolbook_GetToolBar(*args, **kwargs) def Realize(*args, **kwargs): """Realize(self)""" return _controls_.Toolbook_Realize(*args, **kwargs) ToolBar = property(GetToolBar,doc="See `GetToolBar`") _controls_.Toolbook_swigregister(Toolbook) def PreToolbook(*args, **kwargs): """PreToolbook() -> Toolbook""" val = _controls_.new_PreToolbook(*args, **kwargs) return val ToolbookEvent = wx.BookCtrlEvent wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGED = _controls_.wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGED wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGING = _controls_.wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGING EVT_TOOLBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGED, 1) EVT_TOOLBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_COMMAND_TOOLBOOK_PAGE_CHANGING, 1) #--------------------------------------------------------------------------- TOOL_STYLE_BUTTON = _controls_.TOOL_STYLE_BUTTON TOOL_STYLE_SEPARATOR = _controls_.TOOL_STYLE_SEPARATOR TOOL_STYLE_CONTROL = _controls_.TOOL_STYLE_CONTROL TB_HORIZONTAL = _controls_.TB_HORIZONTAL TB_VERTICAL = _controls_.TB_VERTICAL TB_TOP = _controls_.TB_TOP TB_LEFT = _controls_.TB_LEFT TB_BOTTOM = _controls_.TB_BOTTOM TB_RIGHT = _controls_.TB_RIGHT TB_3DBUTTONS = _controls_.TB_3DBUTTONS TB_FLAT = _controls_.TB_FLAT TB_DOCKABLE = _controls_.TB_DOCKABLE TB_NOICONS = _controls_.TB_NOICONS TB_TEXT = _controls_.TB_TEXT TB_NODIVIDER = _controls_.TB_NODIVIDER TB_NOALIGN = _controls_.TB_NOALIGN TB_HORZ_LAYOUT = _controls_.TB_HORZ_LAYOUT TB_HORZ_TEXT = _controls_.TB_HORZ_TEXT TB_NO_TOOLTIPS = _controls_.TB_NO_TOOLTIPS class ToolBarToolBase(_core.Object): """Proxy of C++ ToolBarToolBase class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self): raise AttributeError, "No constructor defined" __repr__ = _swig_repr def GetId(*args, **kwargs): """GetId(self) -> int""" return _controls_.ToolBarToolBase_GetId(*args, **kwargs) def GetControl(*args, **kwargs): """GetControl(self) -> Control""" return _controls_.ToolBarToolBase_GetControl(*args, **kwargs) def GetToolBar(*args, **kwargs): """GetToolBar(self) -> ToolBarBase""" return _controls_.ToolBarToolBase_GetToolBar(*args, **kwargs) def IsStretchable(*args, **kwargs): """IsStretchable(self) -> bool""" return _controls_.ToolBarToolBase_IsStretchable(*args, **kwargs) def IsButton(*args, **kwargs): """IsButton(self) -> int""" return _controls_.ToolBarToolBase_IsButton(*args, **kwargs) def IsControl(*args, **kwargs): """IsControl(self) -> int""" return _controls_.ToolBarToolBase_IsControl(*args, **kwargs) def IsSeparator(*args, **kwargs): """IsSeparator(self) -> int""" return _controls_.ToolBarToolBase_IsSeparator(*args, **kwargs) def IsStretchableSpace(*args, **kwargs): """IsStretchableSpace(self) -> bool""" return _controls_.ToolBarToolBase_IsStretchableSpace(*args, **kwargs) def GetStyle(*args, **kwargs): """GetStyle(self) -> int""" return _controls_.ToolBarToolBase_GetStyle(*args, **kwargs) def GetKind(*args, **kwargs): """GetKind(self) -> int""" return _controls_.ToolBarToolBase_GetKind(*args, **kwargs) def MakeStretchable(*args, **kwargs): """MakeStretchable(self)""" return _controls_.ToolBarToolBase_MakeStretchable(*args, **kwargs) def IsEnabled(*args, **kwargs): """IsEnabled(self) -> bool""" return _controls_.ToolBarToolBase_IsEnabled(*args, **kwargs) def IsToggled(*args, **kwargs): """IsToggled(self) -> bool""" return _controls_.ToolBarToolBase_IsToggled(*args, **kwargs) def CanBeToggled(*args, **kwargs): """CanBeToggled(self) -> bool""" return _controls_.ToolBarToolBase_CanBeToggled(*args, **kwargs) def GetNormalBitmap(*args, **kwargs): """GetNormalBitmap(self) -> Bitmap""" return _controls_.ToolBarToolBase_GetNormalBitmap(*args, **kwargs) def GetDisabledBitmap(*args, **kwargs): """GetDisabledBitmap(self) -> Bitmap""" return _controls_.ToolBarToolBase_GetDisabledBitmap(*args, **kwargs) def GetBitmap(*args, **kwargs): """GetBitmap(self) -> Bitmap""" return _controls_.ToolBarToolBase_GetBitmap(*args, **kwargs) def GetLabel(*args, **kwargs): """GetLabel(self) -> String""" return _controls_.ToolBarToolBase_GetLabel(*args, **kwargs) def GetShortHelp(*args, **kwargs): """GetShortHelp(self) -> String""" return _controls_.ToolBarToolBase_GetShortHelp(*args, **kwargs) def GetLongHelp(*args, **kwargs): """GetLongHelp(self) -> String""" return _controls_.ToolBarToolBase_GetLongHelp(*args, **kwargs) def Enable(*args, **kwargs): """Enable(self, bool enable) -> bool""" return _controls_.ToolBarToolBase_Enable(*args, **kwargs) def Toggle(*args, **kwargs): """Toggle(self)""" return _controls_.ToolBarToolBase_Toggle(*args, **kwargs) def SetToggle(*args, **kwargs): """SetToggle(self, bool toggle) -> bool""" return _controls_.ToolBarToolBase_SetToggle(*args, **kwargs) def SetShortHelp(*args, **kwargs): """SetShortHelp(self, String help) -> bool""" return _controls_.ToolBarToolBase_SetShortHelp(*args, **kwargs) def SetLongHelp(*args, **kwargs): """SetLongHelp(self, String help) -> bool""" return _controls_.ToolBarToolBase_SetLongHelp(*args, **kwargs) def SetNormalBitmap(*args, **kwargs): """SetNormalBitmap(self, Bitmap bmp)""" return _controls_.ToolBarToolBase_SetNormalBitmap(*args, **kwargs) def SetDisabledBitmap(*args, **kwargs): """SetDisabledBitmap(self, Bitmap bmp)""" return _controls_.ToolBarToolBase_SetDisabledBitmap(*args, **kwargs) def SetLabel(*args, **kwargs): """SetLabel(self, String label)""" return _controls_.ToolBarToolBase_SetLabel(*args, **kwargs) def Detach(*args, **kwargs): """Detach(self)""" return _controls_.ToolBarToolBase_Detach(*args, **kwargs) def Attach(*args, **kwargs): """Attach(self, ToolBarBase tbar)""" return _controls_.ToolBarToolBase_Attach(*args, **kwargs) def SetDropdownMenu(*args, **kwargs): """SetDropdownMenu(self, Menu menu)""" return _controls_.ToolBarToolBase_SetDropdownMenu(*args, **kwargs) def GetDropdownMenu(*args, **kwargs): """GetDropdownMenu(self) -> Menu""" return _controls_.ToolBarToolBase_GetDropdownMenu(*args, **kwargs) def GetClientData(*args, **kwargs): """GetClientData(self) -> PyObject""" return _controls_.ToolBarToolBase_GetClientData(*args, **kwargs) def SetClientData(*args, **kwargs): """SetClientData(self, PyObject clientData)""" return _controls_.ToolBarToolBase_SetClientData(*args, **kwargs) GetBitmap1 = GetNormalBitmap GetBitmap2 = GetDisabledBitmap SetBitmap1 = SetNormalBitmap SetBitmap2 = SetDisabledBitmap Bitmap = property(GetBitmap,doc="See `GetBitmap`") ClientData = property(GetClientData,SetClientData,doc="See `GetClientData` and `SetClientData`") Control = property(GetControl,doc="See `GetControl`") DisabledBitmap = property(GetDisabledBitmap,SetDisabledBitmap,doc="See `GetDisabledBitmap` and `SetDisabledBitmap`") Id = property(GetId,doc="See `GetId`") Kind = property(GetKind,doc="See `GetKind`") Label = property(GetLabel,SetLabel,doc="See `GetLabel` and `SetLabel`") LongHelp = property(GetLongHelp,SetLongHelp,doc="See `GetLongHelp` and `SetLongHelp`") NormalBitmap = property(GetNormalBitmap,SetNormalBitmap,doc="See `GetNormalBitmap` and `SetNormalBitmap`") ShortHelp = property(GetShortHelp,SetShortHelp,doc="See `GetShortHelp` and `SetShortHelp`") Style = property(GetStyle,doc="See `GetStyle`") ToolBar = property(GetToolBar,doc="See `GetToolBar`") _controls_.ToolBarToolBase_swigregister(ToolBarToolBase) class ToolBarBase(_core.Control): """Proxy of C++ ToolBarBase class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self): raise AttributeError, "No constructor defined" __repr__ = _swig_repr def DoAddTool(*args, **kwargs): """ DoAddTool(self, int id, String label, Bitmap bitmap, Bitmap bmpDisabled=wxNullBitmap, int kind=ITEM_NORMAL, String shortHelp=EmptyString, String longHelp=EmptyString, PyObject clientData=None) -> ToolBarToolBase """ return _controls_.ToolBarBase_DoAddTool(*args, **kwargs) def DoInsertTool(*args, **kwargs): """ DoInsertTool(self, size_t pos, int id, String label, Bitmap bitmap, Bitmap bmpDisabled=wxNullBitmap, int kind=ITEM_NORMAL, String shortHelp=EmptyString, String longHelp=EmptyString, PyObject clientData=None) -> ToolBarToolBase """ return _controls_.ToolBarBase_DoInsertTool(*args, **kwargs) # These match the original Add methods for this class, kept for # backwards compatibility with versions < 2.3.3. def AddTool(self, id, bitmap, pushedBitmap = wx.NullBitmap, isToggle = 0, clientData = None, shortHelpString = '', longHelpString = '') : '''Old style method to add a tool to the toolbar.''' kind = wx.ITEM_NORMAL if isToggle: kind = wx.ITEM_CHECK return self.DoAddTool(id, '', bitmap, pushedBitmap, kind, shortHelpString, longHelpString, clientData) def AddSimpleTool(self, id, bitmap, shortHelpString = '', longHelpString = '', isToggle = 0): '''Old style method to add a tool to the toolbar.''' kind = wx.ITEM_NORMAL if isToggle: kind = wx.ITEM_CHECK return self.DoAddTool(id, '', bitmap, wx.NullBitmap, kind, shortHelpString, longHelpString, None) def InsertTool(self, pos, id, bitmap, pushedBitmap = wx.NullBitmap, isToggle = 0, clientData = None, shortHelpString = '', longHelpString = ''): '''Old style method to insert a tool in the toolbar.''' kind = wx.ITEM_NORMAL if isToggle: kind = wx.ITEM_CHECK return self.DoInsertTool(pos, id, '', bitmap, pushedBitmap, kind, shortHelpString, longHelpString, clientData) def InsertSimpleTool(self, pos, id, bitmap, shortHelpString = '', longHelpString = '', isToggle = 0): '''Old style method to insert a tool in the toolbar.''' kind = wx.ITEM_NORMAL if isToggle: kind = wx.ITEM_CHECK return self.DoInsertTool(pos, id, '', bitmap, wx.NullBitmap, kind, shortHelpString, longHelpString, None) # The following are the new toolbar Add methods starting with # 2.3.3. They are renamed to have 'Label' in the name so as to be # able to keep backwards compatibility with using the above # methods. Eventually these should migrate to be the methods used # primarily and lose the 'Label' in the name... def AddLabelTool(self, id, label, bitmap, bmpDisabled = wx.NullBitmap, kind = wx.ITEM_NORMAL, shortHelp = '', longHelp = '', clientData = None): ''' The full AddTool() function. If bmpDisabled is wx.NullBitmap, a shadowed version of the normal bitmap is created and used as the disabled image. ''' return self.DoAddTool(id, label, bitmap, bmpDisabled, kind, shortHelp, longHelp, clientData) def InsertLabelTool(self, pos, id, label, bitmap, bmpDisabled = wx.NullBitmap, kind = wx.ITEM_NORMAL, shortHelp = '', longHelp = '', clientData = None): ''' Insert the new tool at the given position, if pos == GetToolsCount(), it is equivalent to AddTool() ''' return self.DoInsertTool(pos, id, label, bitmap, bmpDisabled, kind, shortHelp, longHelp, clientData) def AddCheckLabelTool(self, id, label, bitmap, bmpDisabled = wx.NullBitmap, shortHelp = '', longHelp = '', clientData = None): '''Add a check tool, i.e. a tool which can be toggled''' return self.DoAddTool(id, label, bitmap, bmpDisabled, wx.ITEM_CHECK, shortHelp, longHelp, clientData) def AddRadioLabelTool(self, id, label, bitmap, bmpDisabled = wx.NullBitmap, shortHelp = '', longHelp = '', clientData = None): ''' Add a radio tool, i.e. a tool which can be toggled and releases any other toggled radio tools in the same group when it happens ''' return self.DoAddTool(id, label, bitmap, bmpDisabled, wx.ITEM_RADIO, shortHelp, longHelp, clientData) # For consistency with the backwards compatible methods above, here are # some non-'Label' versions of the Check and Radio methods def AddCheckTool(self, id, bitmap, bmpDisabled = wx.NullBitmap, shortHelp = '', longHelp = '', clientData = None): '''Add a check tool, i.e. a tool which can be toggled''' return self.DoAddTool(id, '', bitmap, bmpDisabled, wx.ITEM_CHECK, shortHelp, longHelp, clientData) def AddRadioTool(self, id, bitmap, bmpDisabled = wx.NullBitmap, shortHelp = '', longHelp = '', clientData = None): ''' Add a radio tool, i.e. a tool which can be toggled and releases any other toggled radio tools in the same group when it happens ''' return self.DoAddTool(id, '', bitmap, bmpDisabled, wx.ITEM_RADIO, shortHelp, longHelp, clientData) def AddToolItem(*args, **kwargs): """AddToolItem(self, ToolBarToolBase tool) -> ToolBarToolBase""" return _controls_.ToolBarBase_AddToolItem(*args, **kwargs) def InsertToolItem(*args, **kwargs): """InsertToolItem(self, size_t pos, ToolBarToolBase tool) -> ToolBarToolBase""" return _controls_.ToolBarBase_InsertToolItem(*args, **kwargs) def AddControl(*args, **kwargs): """AddControl(self, Control control, String label=wxEmptyString) -> ToolBarToolBase""" return _controls_.ToolBarBase_AddControl(*args, **kwargs) def InsertControl(*args, **kwargs): """InsertControl(self, size_t pos, Control control, String label=wxEmptyString) -> ToolBarToolBase""" return _controls_.ToolBarBase_InsertControl(*args, **kwargs) def FindControl(*args, **kwargs): """FindControl(self, int id) -> Control""" return _controls_.ToolBarBase_FindControl(*args, **kwargs) def AddSeparator(*args, **kwargs): """AddSeparator(self) -> ToolBarToolBase""" return _controls_.ToolBarBase_AddSeparator(*args, **kwargs) def InsertSeparator(*args, **kwargs): """InsertSeparator(self, size_t pos) -> ToolBarToolBase""" return _controls_.ToolBarBase_InsertSeparator(*args, **kwargs) def AddStretchableSpace(*args, **kwargs): """AddStretchableSpace(self) -> ToolBarToolBase""" return _controls_.ToolBarBase_AddStretchableSpace(*args, **kwargs) def InsertStretchableSpace(*args, **kwargs): """InsertStretchableSpace(self, size_t pos) -> ToolBarToolBase""" return _controls_.ToolBarBase_InsertStretchableSpace(*args, **kwargs) def RemoveTool(*args, **kwargs): """RemoveTool(self, int id) -> ToolBarToolBase""" return _controls_.ToolBarBase_RemoveTool(*args, **kwargs) def DeleteToolByPos(*args, **kwargs): """DeleteToolByPos(self, size_t pos) -> bool""" return _controls_.ToolBarBase_DeleteToolByPos(*args, **kwargs) def DeleteTool(*args, **kwargs): """DeleteTool(self, int id) -> bool""" return _controls_.ToolBarBase_DeleteTool(*args, **kwargs) def ClearTools(*args, **kwargs): """ClearTools(self)""" return _controls_.ToolBarBase_ClearTools(*args, **kwargs) def Realize(*args, **kwargs): """Realize(self) -> bool""" return _controls_.ToolBarBase_Realize(*args, **kwargs) def EnableTool(*args, **kwargs): """EnableTool(self, int id, bool enable)""" return _controls_.ToolBarBase_EnableTool(*args, **kwargs) def ToggleTool(*args, **kwargs): """ToggleTool(self, int id, bool toggle)""" return _controls_.ToolBarBase_ToggleTool(*args, **kwargs) def SetToggle(*args, **kwargs): """SetToggle(self, int id, bool toggle)""" return _controls_.ToolBarBase_SetToggle(*args, **kwargs) def GetToolClientData(*args, **kwargs): """GetToolClientData(self, int id) -> PyObject""" return _controls_.ToolBarBase_GetToolClientData(*args, **kwargs) def SetToolClientData(*args, **kwargs): """SetToolClientData(self, int id, PyObject clientData)""" return _controls_.ToolBarBase_SetToolClientData(*args, **kwargs) def GetToolPos(*args, **kwargs): """GetToolPos(self, int id) -> int""" return _controls_.ToolBarBase_GetToolPos(*args, **kwargs) def GetToolState(*args, **kwargs): """GetToolState(self, int id) -> bool""" return _controls_.ToolBarBase_GetToolState(*args, **kwargs) def GetToolEnabled(*args, **kwargs): """GetToolEnabled(self, int id) -> bool""" return _controls_.ToolBarBase_GetToolEnabled(*args, **kwargs) def SetToolShortHelp(*args, **kwargs): """SetToolShortHelp(self, int id, String helpString)""" return _controls_.ToolBarBase_SetToolShortHelp(*args, **kwargs) def GetToolShortHelp(*args, **kwargs): """GetToolShortHelp(self, int id) -> String""" return _controls_.ToolBarBase_GetToolShortHelp(*args, **kwargs) def SetToolLongHelp(*args, **kwargs): """SetToolLongHelp(self, int id, String helpString)""" return _controls_.ToolBarBase_SetToolLongHelp(*args, **kwargs) def GetToolLongHelp(*args, **kwargs): """GetToolLongHelp(self, int id) -> String""" return _controls_.ToolBarBase_GetToolLongHelp(*args, **kwargs) def SetMarginsXY(*args, **kwargs): """SetMarginsXY(self, int x, int y)""" return _controls_.ToolBarBase_SetMarginsXY(*args, **kwargs) def SetMargins(*args, **kwargs): """SetMargins(self, Size size)""" return _controls_.ToolBarBase_SetMargins(*args, **kwargs) def SetToolPacking(*args, **kwargs): """SetToolPacking(self, int packing)""" return _controls_.ToolBarBase_SetToolPacking(*args, **kwargs) def SetToolSeparation(*args, **kwargs): """SetToolSeparation(self, int separation)""" return _controls_.ToolBarBase_SetToolSeparation(*args, **kwargs) def GetToolMargins(*args, **kwargs): """GetToolMargins(self) -> Size""" return _controls_.ToolBarBase_GetToolMargins(*args, **kwargs) def GetMargins(*args, **kwargs): """GetMargins(self) -> Size""" return _controls_.ToolBarBase_GetMargins(*args, **kwargs) def GetToolPacking(*args, **kwargs): """GetToolPacking(self) -> int""" return _controls_.ToolBarBase_GetToolPacking(*args, **kwargs) def GetToolSeparation(*args, **kwargs): """GetToolSeparation(self) -> int""" return _controls_.ToolBarBase_GetToolSeparation(*args, **kwargs) def SetRows(*args, **kwargs): """SetRows(self, int nRows)""" return _controls_.ToolBarBase_SetRows(*args, **kwargs) def SetMaxRowsCols(*args, **kwargs): """SetMaxRowsCols(self, int rows, int cols)""" return _controls_.ToolBarBase_SetMaxRowsCols(*args, **kwargs) def GetMaxRows(*args, **kwargs): """GetMaxRows(self) -> int""" return _controls_.ToolBarBase_GetMaxRows(*args, **kwargs) def GetMaxCols(*args, **kwargs): """GetMaxCols(self) -> int""" return _controls_.ToolBarBase_GetMaxCols(*args, **kwargs) def SetToolBitmapSize(*args, **kwargs): """SetToolBitmapSize(self, Size size)""" return _controls_.ToolBarBase_SetToolBitmapSize(*args, **kwargs) def GetToolBitmapSize(*args, **kwargs): """GetToolBitmapSize(self) -> Size""" return _controls_.ToolBarBase_GetToolBitmapSize(*args, **kwargs) def GetToolSize(*args, **kwargs): """GetToolSize(self) -> Size""" return _controls_.ToolBarBase_GetToolSize(*args, **kwargs) def FindToolForPosition(*args, **kwargs): """FindToolForPosition(self, int x, int y) -> ToolBarToolBase""" return _controls_.ToolBarBase_FindToolForPosition(*args, **kwargs) def FindById(*args, **kwargs): """FindById(self, int toolid) -> ToolBarToolBase""" return _controls_.ToolBarBase_FindById(*args, **kwargs) def IsVertical(*args, **kwargs): """IsVertical(self) -> bool""" return _controls_.ToolBarBase_IsVertical(*args, **kwargs) def GetToolsCount(*args, **kwargs): """GetToolsCount(self) -> size_t""" return _controls_.ToolBarBase_GetToolsCount(*args, **kwargs) def GetToolByPos(*args, **kwargs): """GetToolByPos(self, int pos) -> ToolBarToolBase""" return _controls_.ToolBarBase_GetToolByPos(*args, **kwargs) def SetDropdownMenu(*args, **kwargs): """SetDropdownMenu(self, int toolid, Menu menu) -> bool""" return _controls_.ToolBarBase_SetDropdownMenu(*args, **kwargs) Margins = property(GetMargins,SetMargins,doc="See `GetMargins` and `SetMargins`") MaxCols = property(GetMaxCols,doc="See `GetMaxCols`") MaxRows = property(GetMaxRows,doc="See `GetMaxRows`") ToolBitmapSize = property(GetToolBitmapSize,SetToolBitmapSize,doc="See `GetToolBitmapSize` and `SetToolBitmapSize`") ToolMargins = property(GetToolMargins,doc="See `GetToolMargins`") ToolPacking = property(GetToolPacking,SetToolPacking,doc="See `GetToolPacking` and `SetToolPacking`") ToolSeparation = property(GetToolSeparation,SetToolSeparation,doc="See `GetToolSeparation` and `SetToolSeparation`") ToolSize = property(GetToolSize,doc="See `GetToolSize`") ToolsCount = property(GetToolsCount,doc="See `GetToolsCount`") _controls_.ToolBarBase_swigregister(ToolBarBase) class ToolBar(ToolBarBase): """Proxy of C++ ToolBar class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxNO_BORDER|wxTB_HORIZONTAL, String name=wxPyToolBarNameStr) -> ToolBar """ _controls_.ToolBar_swiginit(self,_controls_.new_ToolBar(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxNO_BORDER|wxTB_HORIZONTAL, String name=wxPyToolBarNameStr) -> bool """ return _controls_.ToolBar_Create(*args, **kwargs) def SetToolNormalBitmap(*args, **kwargs): """SetToolNormalBitmap(self, int id, Bitmap bitmap)""" return _controls_.ToolBar_SetToolNormalBitmap(*args, **kwargs) def SetToolDisabledBitmap(*args, **kwargs): """SetToolDisabledBitmap(self, int id, Bitmap bitmap)""" return _controls_.ToolBar_SetToolDisabledBitmap(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ToolBar_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) _controls_.ToolBar_swigregister(ToolBar) def PreToolBar(*args, **kwargs): """PreToolBar() -> ToolBar""" val = _controls_.new_PreToolBar(*args, **kwargs) return val def ToolBar_GetClassDefaultAttributes(*args, **kwargs): """ ToolBar_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ToolBar_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- LC_VRULES = _controls_.LC_VRULES LC_HRULES = _controls_.LC_HRULES LC_ICON = _controls_.LC_ICON LC_SMALL_ICON = _controls_.LC_SMALL_ICON LC_LIST = _controls_.LC_LIST LC_REPORT = _controls_.LC_REPORT LC_ALIGN_TOP = _controls_.LC_ALIGN_TOP LC_ALIGN_LEFT = _controls_.LC_ALIGN_LEFT LC_AUTOARRANGE = _controls_.LC_AUTOARRANGE LC_VIRTUAL = _controls_.LC_VIRTUAL LC_EDIT_LABELS = _controls_.LC_EDIT_LABELS LC_NO_HEADER = _controls_.LC_NO_HEADER LC_NO_SORT_HEADER = _controls_.LC_NO_SORT_HEADER LC_SINGLE_SEL = _controls_.LC_SINGLE_SEL LC_SORT_ASCENDING = _controls_.LC_SORT_ASCENDING LC_SORT_DESCENDING = _controls_.LC_SORT_DESCENDING LC_MASK_TYPE = _controls_.LC_MASK_TYPE LC_MASK_ALIGN = _controls_.LC_MASK_ALIGN LC_MASK_SORT = _controls_.LC_MASK_SORT LIST_MASK_STATE = _controls_.LIST_MASK_STATE LIST_MASK_TEXT = _controls_.LIST_MASK_TEXT LIST_MASK_IMAGE = _controls_.LIST_MASK_IMAGE LIST_MASK_DATA = _controls_.LIST_MASK_DATA LIST_SET_ITEM = _controls_.LIST_SET_ITEM LIST_MASK_WIDTH = _controls_.LIST_MASK_WIDTH LIST_MASK_FORMAT = _controls_.LIST_MASK_FORMAT LIST_STATE_DONTCARE = _controls_.LIST_STATE_DONTCARE LIST_STATE_DROPHILITED = _controls_.LIST_STATE_DROPHILITED LIST_STATE_FOCUSED = _controls_.LIST_STATE_FOCUSED LIST_STATE_SELECTED = _controls_.LIST_STATE_SELECTED LIST_STATE_CUT = _controls_.LIST_STATE_CUT LIST_STATE_DISABLED = _controls_.LIST_STATE_DISABLED LIST_STATE_FILTERED = _controls_.LIST_STATE_FILTERED LIST_STATE_INUSE = _controls_.LIST_STATE_INUSE LIST_STATE_PICKED = _controls_.LIST_STATE_PICKED LIST_STATE_SOURCE = _controls_.LIST_STATE_SOURCE LIST_HITTEST_ABOVE = _controls_.LIST_HITTEST_ABOVE LIST_HITTEST_BELOW = _controls_.LIST_HITTEST_BELOW LIST_HITTEST_NOWHERE = _controls_.LIST_HITTEST_NOWHERE LIST_HITTEST_ONITEMICON = _controls_.LIST_HITTEST_ONITEMICON LIST_HITTEST_ONITEMLABEL = _controls_.LIST_HITTEST_ONITEMLABEL LIST_HITTEST_ONITEMRIGHT = _controls_.LIST_HITTEST_ONITEMRIGHT LIST_HITTEST_ONITEMSTATEICON = _controls_.LIST_HITTEST_ONITEMSTATEICON LIST_HITTEST_TOLEFT = _controls_.LIST_HITTEST_TOLEFT LIST_HITTEST_TORIGHT = _controls_.LIST_HITTEST_TORIGHT LIST_HITTEST_ONITEM = _controls_.LIST_HITTEST_ONITEM LIST_GETSUBITEMRECT_WHOLEITEM = _controls_.LIST_GETSUBITEMRECT_WHOLEITEM LIST_NEXT_ABOVE = _controls_.LIST_NEXT_ABOVE LIST_NEXT_ALL = _controls_.LIST_NEXT_ALL LIST_NEXT_BELOW = _controls_.LIST_NEXT_BELOW LIST_NEXT_LEFT = _controls_.LIST_NEXT_LEFT LIST_NEXT_RIGHT = _controls_.LIST_NEXT_RIGHT LIST_ALIGN_DEFAULT = _controls_.LIST_ALIGN_DEFAULT LIST_ALIGN_LEFT = _controls_.LIST_ALIGN_LEFT LIST_ALIGN_TOP = _controls_.LIST_ALIGN_TOP LIST_ALIGN_SNAP_TO_GRID = _controls_.LIST_ALIGN_SNAP_TO_GRID LIST_FORMAT_LEFT = _controls_.LIST_FORMAT_LEFT LIST_FORMAT_RIGHT = _controls_.LIST_FORMAT_RIGHT LIST_FORMAT_CENTRE = _controls_.LIST_FORMAT_CENTRE LIST_FORMAT_CENTER = _controls_.LIST_FORMAT_CENTER LIST_AUTOSIZE = _controls_.LIST_AUTOSIZE LIST_AUTOSIZE_USEHEADER = _controls_.LIST_AUTOSIZE_USEHEADER LIST_RECT_BOUNDS = _controls_.LIST_RECT_BOUNDS LIST_RECT_ICON = _controls_.LIST_RECT_ICON LIST_RECT_LABEL = _controls_.LIST_RECT_LABEL LIST_FIND_UP = _controls_.LIST_FIND_UP LIST_FIND_DOWN = _controls_.LIST_FIND_DOWN LIST_FIND_LEFT = _controls_.LIST_FIND_LEFT LIST_FIND_RIGHT = _controls_.LIST_FIND_RIGHT #--------------------------------------------------------------------------- class ListItemAttr(object): """Proxy of C++ ListItemAttr class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Colour colText=wxNullColour, Colour colBack=wxNullColour, Font font=wxNullFont) -> ListItemAttr """ _controls_.ListItemAttr_swiginit(self,_controls_.new_ListItemAttr(*args, **kwargs)) __swig_destroy__ = _controls_.delete_ListItemAttr __del__ = lambda self : None; def SetTextColour(*args, **kwargs): """SetTextColour(self, Colour colText)""" return _controls_.ListItemAttr_SetTextColour(*args, **kwargs) def SetBackgroundColour(*args, **kwargs): """SetBackgroundColour(self, Colour colBack)""" return _controls_.ListItemAttr_SetBackgroundColour(*args, **kwargs) def SetFont(*args, **kwargs): """SetFont(self, Font font)""" return _controls_.ListItemAttr_SetFont(*args, **kwargs) def HasTextColour(*args, **kwargs): """HasTextColour(self) -> bool""" return _controls_.ListItemAttr_HasTextColour(*args, **kwargs) def HasBackgroundColour(*args, **kwargs): """HasBackgroundColour(self) -> bool""" return _controls_.ListItemAttr_HasBackgroundColour(*args, **kwargs) def HasFont(*args, **kwargs): """HasFont(self) -> bool""" return _controls_.ListItemAttr_HasFont(*args, **kwargs) def GetTextColour(*args, **kwargs): """GetTextColour(self) -> Colour""" return _controls_.ListItemAttr_GetTextColour(*args, **kwargs) def GetBackgroundColour(*args, **kwargs): """GetBackgroundColour(self) -> Colour""" return _controls_.ListItemAttr_GetBackgroundColour(*args, **kwargs) def GetFont(*args, **kwargs): """GetFont(self) -> Font""" return _controls_.ListItemAttr_GetFont(*args, **kwargs) def AssignFrom(*args, **kwargs): """AssignFrom(self, ListItemAttr source)""" return _controls_.ListItemAttr_AssignFrom(*args, **kwargs) def Destroy(*args, **kwargs): """Destroy(self)""" args[0].this.own(False) return _controls_.ListItemAttr_Destroy(*args, **kwargs) BackgroundColour = property(GetBackgroundColour,SetBackgroundColour,doc="See `GetBackgroundColour` and `SetBackgroundColour`") Font = property(GetFont,SetFont,doc="See `GetFont` and `SetFont`") TextColour = property(GetTextColour,SetTextColour,doc="See `GetTextColour` and `SetTextColour`") _controls_.ListItemAttr_swigregister(ListItemAttr) ListCtrlNameStr = cvar.ListCtrlNameStr #--------------------------------------------------------------------------- class ListItem(_core.Object): """Proxy of C++ ListItem class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self) -> ListItem""" _controls_.ListItem_swiginit(self,_controls_.new_ListItem(*args, **kwargs)) __swig_destroy__ = _controls_.delete_ListItem __del__ = lambda self : None; def Clear(*args, **kwargs): """Clear(self)""" return _controls_.ListItem_Clear(*args, **kwargs) def ClearAttributes(*args, **kwargs): """ClearAttributes(self)""" return _controls_.ListItem_ClearAttributes(*args, **kwargs) def SetMask(*args, **kwargs): """SetMask(self, long mask)""" return _controls_.ListItem_SetMask(*args, **kwargs) def SetId(*args, **kwargs): """SetId(self, long id)""" return _controls_.ListItem_SetId(*args, **kwargs) def SetColumn(*args, **kwargs): """SetColumn(self, int col)""" return _controls_.ListItem_SetColumn(*args, **kwargs) def SetState(*args, **kwargs): """SetState(self, long state)""" return _controls_.ListItem_SetState(*args, **kwargs) def SetStateMask(*args, **kwargs): """SetStateMask(self, long stateMask)""" return _controls_.ListItem_SetStateMask(*args, **kwargs) def SetText(*args, **kwargs): """SetText(self, String text)""" return _controls_.ListItem_SetText(*args, **kwargs) def SetImage(*args, **kwargs): """SetImage(self, int image)""" return _controls_.ListItem_SetImage(*args, **kwargs) def SetData(*args, **kwargs): """SetData(self, long data)""" return _controls_.ListItem_SetData(*args, **kwargs) def SetWidth(*args, **kwargs): """SetWidth(self, int width)""" return _controls_.ListItem_SetWidth(*args, **kwargs) def SetAlign(*args, **kwargs): """SetAlign(self, int align)""" return _controls_.ListItem_SetAlign(*args, **kwargs) def SetTextColour(*args, **kwargs): """SetTextColour(self, Colour colText)""" return _controls_.ListItem_SetTextColour(*args, **kwargs) def SetBackgroundColour(*args, **kwargs): """SetBackgroundColour(self, Colour colBack)""" return _controls_.ListItem_SetBackgroundColour(*args, **kwargs) def SetFont(*args, **kwargs): """SetFont(self, Font font)""" return _controls_.ListItem_SetFont(*args, **kwargs) def GetMask(*args, **kwargs): """GetMask(self) -> long""" return _controls_.ListItem_GetMask(*args, **kwargs) def GetId(*args, **kwargs): """GetId(self) -> long""" return _controls_.ListItem_GetId(*args, **kwargs) def GetColumn(*args, **kwargs): """GetColumn(self) -> int""" return _controls_.ListItem_GetColumn(*args, **kwargs) def GetState(*args, **kwargs): """GetState(self) -> long""" return _controls_.ListItem_GetState(*args, **kwargs) def GetText(*args, **kwargs): """GetText(self) -> String""" return _controls_.ListItem_GetText(*args, **kwargs) def GetImage(*args, **kwargs): """GetImage(self) -> int""" return _controls_.ListItem_GetImage(*args, **kwargs) def GetData(*args, **kwargs): """GetData(self) -> long""" return _controls_.ListItem_GetData(*args, **kwargs) def GetWidth(*args, **kwargs): """GetWidth(self) -> int""" return _controls_.ListItem_GetWidth(*args, **kwargs) def GetAlign(*args, **kwargs): """GetAlign(self) -> int""" return _controls_.ListItem_GetAlign(*args, **kwargs) def GetAttributes(*args, **kwargs): """GetAttributes(self) -> ListItemAttr""" return _controls_.ListItem_GetAttributes(*args, **kwargs) def HasAttributes(*args, **kwargs): """HasAttributes(self) -> bool""" return _controls_.ListItem_HasAttributes(*args, **kwargs) def GetTextColour(*args, **kwargs): """GetTextColour(self) -> Colour""" return _controls_.ListItem_GetTextColour(*args, **kwargs) def GetBackgroundColour(*args, **kwargs): """GetBackgroundColour(self) -> Colour""" return _controls_.ListItem_GetBackgroundColour(*args, **kwargs) def GetFont(*args, **kwargs): """GetFont(self) -> Font""" return _controls_.ListItem_GetFont(*args, **kwargs) m_mask = property(_controls_.ListItem_m_mask_get, _controls_.ListItem_m_mask_set) m_itemId = property(_controls_.ListItem_m_itemId_get, _controls_.ListItem_m_itemId_set) m_col = property(_controls_.ListItem_m_col_get, _controls_.ListItem_m_col_set) m_state = property(_controls_.ListItem_m_state_get, _controls_.ListItem_m_state_set) m_stateMask = property(_controls_.ListItem_m_stateMask_get, _controls_.ListItem_m_stateMask_set) m_text = property(_controls_.ListItem_m_text_get, _controls_.ListItem_m_text_set) m_image = property(_controls_.ListItem_m_image_get, _controls_.ListItem_m_image_set) m_data = property(_controls_.ListItem_m_data_get, _controls_.ListItem_m_data_set) m_format = property(_controls_.ListItem_m_format_get, _controls_.ListItem_m_format_set) m_width = property(_controls_.ListItem_m_width_get, _controls_.ListItem_m_width_set) Align = property(GetAlign,SetAlign,doc="See `GetAlign` and `SetAlign`") Attributes = property(GetAttributes,doc="See `GetAttributes`") BackgroundColour = property(GetBackgroundColour,SetBackgroundColour,doc="See `GetBackgroundColour` and `SetBackgroundColour`") Column = property(GetColumn,SetColumn,doc="See `GetColumn` and `SetColumn`") Data = property(GetData,SetData,doc="See `GetData` and `SetData`") Font = property(GetFont,SetFont,doc="See `GetFont` and `SetFont`") Id = property(GetId,SetId,doc="See `GetId` and `SetId`") Image = property(GetImage,SetImage,doc="See `GetImage` and `SetImage`") Mask = property(GetMask,SetMask,doc="See `GetMask` and `SetMask`") State = property(GetState,SetState,doc="See `GetState` and `SetState`") Text = property(GetText,SetText,doc="See `GetText` and `SetText`") TextColour = property(GetTextColour,SetTextColour,doc="See `GetTextColour` and `SetTextColour`") Width = property(GetWidth,SetWidth,doc="See `GetWidth` and `SetWidth`") _controls_.ListItem_swigregister(ListItem) #--------------------------------------------------------------------------- class ListEvent(_core.NotifyEvent): """Proxy of C++ ListEvent class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self, EventType commandType=wxEVT_NULL, int id=0) -> ListEvent""" _controls_.ListEvent_swiginit(self,_controls_.new_ListEvent(*args, **kwargs)) m_code = property(_controls_.ListEvent_m_code_get, _controls_.ListEvent_m_code_set) m_oldItemIndex = property(_controls_.ListEvent_m_oldItemIndex_get, _controls_.ListEvent_m_oldItemIndex_set) m_itemIndex = property(_controls_.ListEvent_m_itemIndex_get, _controls_.ListEvent_m_itemIndex_set) m_col = property(_controls_.ListEvent_m_col_get, _controls_.ListEvent_m_col_set) m_pointDrag = property(_controls_.ListEvent_m_pointDrag_get, _controls_.ListEvent_m_pointDrag_set) m_item = property(_controls_.ListEvent_m_item_get) def GetKeyCode(*args, **kwargs): """GetKeyCode(self) -> int""" return _controls_.ListEvent_GetKeyCode(*args, **kwargs) GetCode = GetKeyCode def GetIndex(*args, **kwargs): """GetIndex(self) -> long""" return _controls_.ListEvent_GetIndex(*args, **kwargs) def GetColumn(*args, **kwargs): """GetColumn(self) -> int""" return _controls_.ListEvent_GetColumn(*args, **kwargs) def GetPoint(*args, **kwargs): """GetPoint(self) -> Point""" return _controls_.ListEvent_GetPoint(*args, **kwargs) GetPosition = GetPoint def GetLabel(*args, **kwargs): """GetLabel(self) -> String""" return _controls_.ListEvent_GetLabel(*args, **kwargs) def GetText(*args, **kwargs): """GetText(self) -> String""" return _controls_.ListEvent_GetText(*args, **kwargs) def GetImage(*args, **kwargs): """GetImage(self) -> int""" return _controls_.ListEvent_GetImage(*args, **kwargs) def GetData(*args, **kwargs): """GetData(self) -> long""" return _controls_.ListEvent_GetData(*args, **kwargs) def GetMask(*args, **kwargs): """GetMask(self) -> long""" return _controls_.ListEvent_GetMask(*args, **kwargs) def GetItem(*args, **kwargs): """GetItem(self) -> ListItem""" return _controls_.ListEvent_GetItem(*args, **kwargs) def GetCacheFrom(*args, **kwargs): """GetCacheFrom(self) -> long""" return _controls_.ListEvent_GetCacheFrom(*args, **kwargs) def GetCacheTo(*args, **kwargs): """GetCacheTo(self) -> long""" return _controls_.ListEvent_GetCacheTo(*args, **kwargs) def IsEditCancelled(*args, **kwargs): """IsEditCancelled(self) -> bool""" return _controls_.ListEvent_IsEditCancelled(*args, **kwargs) def SetEditCanceled(*args, **kwargs): """SetEditCanceled(self, bool editCancelled)""" return _controls_.ListEvent_SetEditCanceled(*args, **kwargs) CacheFrom = property(GetCacheFrom,doc="See `GetCacheFrom`") CacheTo = property(GetCacheTo,doc="See `GetCacheTo`") Column = property(GetColumn,doc="See `GetColumn`") Data = property(GetData,doc="See `GetData`") Image = property(GetImage,doc="See `GetImage`") Index = property(GetIndex,doc="See `GetIndex`") Item = property(GetItem,doc="See `GetItem`") KeyCode = property(GetKeyCode,doc="See `GetKeyCode`") Label = property(GetLabel,doc="See `GetLabel`") Mask = property(GetMask,doc="See `GetMask`") Point = property(GetPoint,doc="See `GetPoint`") Text = property(GetText,doc="See `GetText`") _controls_.ListEvent_swigregister(ListEvent) wxEVT_COMMAND_LIST_BEGIN_DRAG = _controls_.wxEVT_COMMAND_LIST_BEGIN_DRAG wxEVT_COMMAND_LIST_BEGIN_RDRAG = _controls_.wxEVT_COMMAND_LIST_BEGIN_RDRAG wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT = _controls_.wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT wxEVT_COMMAND_LIST_END_LABEL_EDIT = _controls_.wxEVT_COMMAND_LIST_END_LABEL_EDIT wxEVT_COMMAND_LIST_DELETE_ITEM = _controls_.wxEVT_COMMAND_LIST_DELETE_ITEM wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS = _controls_.wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS wxEVT_COMMAND_LIST_ITEM_SELECTED = _controls_.wxEVT_COMMAND_LIST_ITEM_SELECTED wxEVT_COMMAND_LIST_ITEM_DESELECTED = _controls_.wxEVT_COMMAND_LIST_ITEM_DESELECTED wxEVT_COMMAND_LIST_KEY_DOWN = _controls_.wxEVT_COMMAND_LIST_KEY_DOWN wxEVT_COMMAND_LIST_INSERT_ITEM = _controls_.wxEVT_COMMAND_LIST_INSERT_ITEM wxEVT_COMMAND_LIST_COL_CLICK = _controls_.wxEVT_COMMAND_LIST_COL_CLICK wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK = _controls_.wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK = _controls_.wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK wxEVT_COMMAND_LIST_ITEM_ACTIVATED = _controls_.wxEVT_COMMAND_LIST_ITEM_ACTIVATED wxEVT_COMMAND_LIST_CACHE_HINT = _controls_.wxEVT_COMMAND_LIST_CACHE_HINT wxEVT_COMMAND_LIST_COL_RIGHT_CLICK = _controls_.wxEVT_COMMAND_LIST_COL_RIGHT_CLICK wxEVT_COMMAND_LIST_COL_BEGIN_DRAG = _controls_.wxEVT_COMMAND_LIST_COL_BEGIN_DRAG wxEVT_COMMAND_LIST_COL_DRAGGING = _controls_.wxEVT_COMMAND_LIST_COL_DRAGGING wxEVT_COMMAND_LIST_COL_END_DRAG = _controls_.wxEVT_COMMAND_LIST_COL_END_DRAG wxEVT_COMMAND_LIST_ITEM_FOCUSED = _controls_.wxEVT_COMMAND_LIST_ITEM_FOCUSED EVT_LIST_BEGIN_DRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_BEGIN_DRAG , 1) EVT_LIST_BEGIN_RDRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_BEGIN_RDRAG , 1) EVT_LIST_BEGIN_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT , 1) EVT_LIST_END_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_LIST_END_LABEL_EDIT , 1) EVT_LIST_DELETE_ITEM = wx.PyEventBinder(wxEVT_COMMAND_LIST_DELETE_ITEM , 1) EVT_LIST_DELETE_ALL_ITEMS = wx.PyEventBinder(wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS , 1) EVT_LIST_ITEM_SELECTED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_SELECTED , 1) EVT_LIST_ITEM_DESELECTED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_DESELECTED , 1) EVT_LIST_KEY_DOWN = wx.PyEventBinder(wxEVT_COMMAND_LIST_KEY_DOWN , 1) EVT_LIST_INSERT_ITEM = wx.PyEventBinder(wxEVT_COMMAND_LIST_INSERT_ITEM , 1) EVT_LIST_COL_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_CLICK , 1) EVT_LIST_ITEM_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK , 1) EVT_LIST_ITEM_MIDDLE_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK, 1) EVT_LIST_ITEM_ACTIVATED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_ACTIVATED , 1) EVT_LIST_CACHE_HINT = wx.PyEventBinder(wxEVT_COMMAND_LIST_CACHE_HINT , 1) EVT_LIST_COL_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_RIGHT_CLICK , 1) EVT_LIST_COL_BEGIN_DRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_BEGIN_DRAG , 1) EVT_LIST_COL_DRAGGING = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_DRAGGING , 1) EVT_LIST_COL_END_DRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_END_DRAG , 1) EVT_LIST_ITEM_FOCUSED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_FOCUSED , 1) #--------------------------------------------------------------------------- class ListCtrl(_core.Control): """Proxy of C++ ListCtrl class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=LC_ICON, Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> ListCtrl """ _controls_.ListCtrl_swiginit(self,_controls_.new_ListCtrl(*args, **kwargs)) self._setOORInfo(self);ListCtrl._setCallbackInfo(self, self, ListCtrl) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=LC_ICON, Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> bool Do the 2nd phase and create the GUI control. """ return _controls_.ListCtrl_Create(*args, **kwargs) def _setCallbackInfo(*args, **kwargs): """_setCallbackInfo(self, PyObject self, PyObject _class)""" return _controls_.ListCtrl__setCallbackInfo(*args, **kwargs) def GetColumn(*args, **kwargs): """GetColumn(self, int col) -> ListItem""" val = _controls_.ListCtrl_GetColumn(*args, **kwargs) if val is not None: val.thisown = 1 return val def SetColumn(*args, **kwargs): """SetColumn(self, int col, ListItem item) -> bool""" return _controls_.ListCtrl_SetColumn(*args, **kwargs) def GetColumnWidth(*args, **kwargs): """GetColumnWidth(self, int col) -> int""" return _controls_.ListCtrl_GetColumnWidth(*args, **kwargs) def SetColumnWidth(*args, **kwargs): """SetColumnWidth(self, int col, int width) -> bool""" return _controls_.ListCtrl_SetColumnWidth(*args, **kwargs) def HasColumnOrderSupport(*args, **kwargs): """HasColumnOrderSupport() -> bool""" return _controls_.ListCtrl_HasColumnOrderSupport(*args, **kwargs) HasColumnOrderSupport = staticmethod(HasColumnOrderSupport) def GetColumnOrder(*args, **kwargs): """GetColumnOrder(self, int col) -> int""" return _controls_.ListCtrl_GetColumnOrder(*args, **kwargs) def GetColumnIndexFromOrder(*args, **kwargs): """GetColumnIndexFromOrder(self, int order) -> int""" return _controls_.ListCtrl_GetColumnIndexFromOrder(*args, **kwargs) def GetColumnsOrder(*args, **kwargs): """GetColumnsOrder(self) -> wxArrayInt""" return _controls_.ListCtrl_GetColumnsOrder(*args, **kwargs) def SetColumnsOrder(*args, **kwargs): """SetColumnsOrder(self, wxArrayInt orders) -> bool""" return _controls_.ListCtrl_SetColumnsOrder(*args, **kwargs) def GetCountPerPage(*args, **kwargs): """GetCountPerPage(self) -> int""" return _controls_.ListCtrl_GetCountPerPage(*args, **kwargs) def GetViewRect(*args, **kwargs): """GetViewRect(self) -> Rect""" return _controls_.ListCtrl_GetViewRect(*args, **kwargs) def GetEditControl(*args, **kwargs): """GetEditControl(self) -> TextCtrl""" return _controls_.ListCtrl_GetEditControl(*args, **kwargs) def GetItem(*args, **kwargs): """GetItem(self, long itemId, int col=0) -> ListItem""" val = _controls_.ListCtrl_GetItem(*args, **kwargs) if val is not None: val.thisown = 1 return val def SetItem(*args, **kwargs): """SetItem(self, ListItem info) -> bool""" return _controls_.ListCtrl_SetItem(*args, **kwargs) def SetStringItem(*args, **kwargs): """SetStringItem(self, long index, int col, String label, int imageId=-1) -> long""" return _controls_.ListCtrl_SetStringItem(*args, **kwargs) def GetItemState(*args, **kwargs): """GetItemState(self, long item, long stateMask) -> int""" return _controls_.ListCtrl_GetItemState(*args, **kwargs) def SetItemState(*args, **kwargs): """SetItemState(self, long item, long state, long stateMask) -> bool""" return _controls_.ListCtrl_SetItemState(*args, **kwargs) def SetItemImage(*args, **kwargs): """SetItemImage(self, long item, int image, int selImage=-1) -> bool""" return _controls_.ListCtrl_SetItemImage(*args, **kwargs) def SetItemColumnImage(*args, **kwargs): """SetItemColumnImage(self, long item, long column, int image) -> bool""" return _controls_.ListCtrl_SetItemColumnImage(*args, **kwargs) def GetItemText(*args, **kwargs): """GetItemText(self, long item, int col=0) -> String""" return _controls_.ListCtrl_GetItemText(*args, **kwargs) def SetItemText(*args, **kwargs): """SetItemText(self, long item, String str)""" return _controls_.ListCtrl_SetItemText(*args, **kwargs) def GetItemData(*args, **kwargs): """GetItemData(self, long item) -> long""" return _controls_.ListCtrl_GetItemData(*args, **kwargs) def SetItemData(*args, **kwargs): """SetItemData(self, long item, long data) -> bool""" return _controls_.ListCtrl_SetItemData(*args, **kwargs) def GetItemPosition(*args, **kwargs): """GetItemPosition(self, long item) -> Point""" return _controls_.ListCtrl_GetItemPosition(*args, **kwargs) def GetItemRect(*args, **kwargs): """GetItemRect(self, long item, int code=LIST_RECT_BOUNDS) -> Rect""" return _controls_.ListCtrl_GetItemRect(*args, **kwargs) def SetItemPosition(*args, **kwargs): """SetItemPosition(self, long item, Point pos) -> bool""" return _controls_.ListCtrl_SetItemPosition(*args, **kwargs) def GetItemCount(*args, **kwargs): """GetItemCount(self) -> int""" return _controls_.ListCtrl_GetItemCount(*args, **kwargs) def GetColumnCount(*args, **kwargs): """GetColumnCount(self) -> int""" return _controls_.ListCtrl_GetColumnCount(*args, **kwargs) def GetItemSpacing(*args, **kwargs): """GetItemSpacing(self) -> Size""" return _controls_.ListCtrl_GetItemSpacing(*args, **kwargs) GetItemSpacing = wx.deprecated(GetItemSpacing) def SetItemSpacing(*args, **kwargs): """SetItemSpacing(self, int spacing, bool isSmall=False)""" return _controls_.ListCtrl_SetItemSpacing(*args, **kwargs) SetItemSpacing = wx.deprecated(SetItemSpacing) def GetSelectedItemCount(*args, **kwargs): """GetSelectedItemCount(self) -> int""" return _controls_.ListCtrl_GetSelectedItemCount(*args, **kwargs) def GetTextColour(*args, **kwargs): """GetTextColour(self) -> Colour""" return _controls_.ListCtrl_GetTextColour(*args, **kwargs) def SetTextColour(*args, **kwargs): """SetTextColour(self, Colour col)""" return _controls_.ListCtrl_SetTextColour(*args, **kwargs) def GetTopItem(*args, **kwargs): """GetTopItem(self) -> long""" return _controls_.ListCtrl_GetTopItem(*args, **kwargs) def SetSingleStyle(*args, **kwargs): """SetSingleStyle(self, long style, bool add=True)""" return _controls_.ListCtrl_SetSingleStyle(*args, **kwargs) def GetNextItem(*args, **kwargs): """GetNextItem(self, long item, int geometry=LIST_NEXT_ALL, int state=LIST_STATE_DONTCARE) -> long""" return _controls_.ListCtrl_GetNextItem(*args, **kwargs) def GetImageList(*args, **kwargs): """GetImageList(self, int which) -> ImageList""" return _controls_.ListCtrl_GetImageList(*args, **kwargs) def SetImageList(*args, **kwargs): """SetImageList(self, ImageList imageList, int which)""" return _controls_.ListCtrl_SetImageList(*args, **kwargs) def AssignImageList(*args, **kwargs): """AssignImageList(self, ImageList imageList, int which)""" return _controls_.ListCtrl_AssignImageList(*args, **kwargs) def InReportView(*args, **kwargs): """InReportView(self) -> bool""" return _controls_.ListCtrl_InReportView(*args, **kwargs) def IsVirtual(*args, **kwargs): """IsVirtual(self) -> bool""" return _controls_.ListCtrl_IsVirtual(*args, **kwargs) def RefreshItem(*args, **kwargs): """RefreshItem(self, long item)""" return _controls_.ListCtrl_RefreshItem(*args, **kwargs) def RefreshItems(*args, **kwargs): """RefreshItems(self, long itemFrom, long itemTo)""" return _controls_.ListCtrl_RefreshItems(*args, **kwargs) def Arrange(*args, **kwargs): """Arrange(self, int flag=LIST_ALIGN_DEFAULT) -> bool""" return _controls_.ListCtrl_Arrange(*args, **kwargs) def DeleteItem(*args, **kwargs): """DeleteItem(self, long item) -> bool""" return _controls_.ListCtrl_DeleteItem(*args, **kwargs) def DeleteAllItems(*args, **kwargs): """DeleteAllItems(self) -> bool""" return _controls_.ListCtrl_DeleteAllItems(*args, **kwargs) def DeleteColumn(*args, **kwargs): """DeleteColumn(self, int col) -> bool""" return _controls_.ListCtrl_DeleteColumn(*args, **kwargs) def DeleteAllColumns(*args, **kwargs): """DeleteAllColumns(self) -> bool""" return _controls_.ListCtrl_DeleteAllColumns(*args, **kwargs) def ClearAll(*args, **kwargs): """ClearAll(self)""" return _controls_.ListCtrl_ClearAll(*args, **kwargs) def EditLabel(*args, **kwargs): """EditLabel(self, long item)""" return _controls_.ListCtrl_EditLabel(*args, **kwargs) def EnsureVisible(*args, **kwargs): """EnsureVisible(self, long item) -> bool""" return _controls_.ListCtrl_EnsureVisible(*args, **kwargs) def FindItem(*args, **kwargs): """FindItem(self, long start, String str, bool partial=False) -> long""" return _controls_.ListCtrl_FindItem(*args, **kwargs) def FindItemData(*args, **kwargs): """FindItemData(self, long start, long data) -> long""" return _controls_.ListCtrl_FindItemData(*args, **kwargs) def FindItemAtPos(*args, **kwargs): """FindItemAtPos(self, long start, Point pt, int direction) -> long""" return _controls_.ListCtrl_FindItemAtPos(*args, **kwargs) def HitTest(*args, **kwargs): """ HitTest(Point point) -> (item, where) Determines which item (if any) is at the specified point, giving in the second return value (see wx.LIST_HITTEST flags.) """ return _controls_.ListCtrl_HitTest(*args, **kwargs) def HitTestSubItem(*args, **kwargs): """ HitTestSubItem(Point point) -> (item, where, subItem) Determines which item (if any) is at the specified point, giving in the second return value (see wx.LIST_HITTEST flags) and also the subItem, if any. """ return _controls_.ListCtrl_HitTestSubItem(*args, **kwargs) def InsertItem(*args, **kwargs): """InsertItem(self, ListItem info) -> long""" return _controls_.ListCtrl_InsertItem(*args, **kwargs) def InsertStringItem(*args, **kwargs): """InsertStringItem(self, long index, String label, int imageIndex=-1) -> long""" return _controls_.ListCtrl_InsertStringItem(*args, **kwargs) def InsertImageItem(*args, **kwargs): """InsertImageItem(self, long index, int imageIndex) -> long""" return _controls_.ListCtrl_InsertImageItem(*args, **kwargs) def InsertImageStringItem(*args, **kwargs): """InsertImageStringItem(self, long index, String label, int imageIndex) -> long""" return _controls_.ListCtrl_InsertImageStringItem(*args, **kwargs) def InsertColumnItem(*args, **kwargs): """InsertColumnItem(self, long col, ListItem info) -> long""" return _controls_.ListCtrl_InsertColumnItem(*args, **kwargs) InsertColumnInfo = InsertColumnItem def InsertColumn(*args, **kwargs): """ InsertColumn(self, long col, String heading, int format=LIST_FORMAT_LEFT, int width=-1) -> long """ return _controls_.ListCtrl_InsertColumn(*args, **kwargs) def SetItemCount(*args, **kwargs): """SetItemCount(self, long count)""" return _controls_.ListCtrl_SetItemCount(*args, **kwargs) def ScrollList(*args, **kwargs): """ScrollList(self, int dx, int dy) -> bool""" return _controls_.ListCtrl_ScrollList(*args, **kwargs) def SetItemTextColour(*args, **kwargs): """SetItemTextColour(self, long item, Colour col)""" return _controls_.ListCtrl_SetItemTextColour(*args, **kwargs) def GetItemTextColour(*args, **kwargs): """GetItemTextColour(self, long item) -> Colour""" return _controls_.ListCtrl_GetItemTextColour(*args, **kwargs) def SetItemBackgroundColour(*args, **kwargs): """SetItemBackgroundColour(self, long item, Colour col)""" return _controls_.ListCtrl_SetItemBackgroundColour(*args, **kwargs) def GetItemBackgroundColour(*args, **kwargs): """GetItemBackgroundColour(self, long item) -> Colour""" return _controls_.ListCtrl_GetItemBackgroundColour(*args, **kwargs) def SetItemFont(*args, **kwargs): """SetItemFont(self, long item, Font f)""" return _controls_.ListCtrl_SetItemFont(*args, **kwargs) def GetItemFont(*args, **kwargs): """GetItemFont(self, long item) -> Font""" return _controls_.ListCtrl_GetItemFont(*args, **kwargs) # # Some helpers... def Select(self, idx, on=1): '''[de]select an item''' if on: state = wx.LIST_STATE_SELECTED else: state = 0 self.SetItemState(idx, state, wx.LIST_STATE_SELECTED) def Focus(self, idx): '''Focus and show the given item''' self.SetItemState(idx, wx.LIST_STATE_FOCUSED, wx.LIST_STATE_FOCUSED) self.EnsureVisible(idx) def GetFocusedItem(self): '''get the currently focused item or -1 if none''' return self.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_FOCUSED) def GetFirstSelected(self, *args): '''return first selected item, or -1 when none''' return self.GetNextSelected(-1) def GetNextSelected(self, item): '''return subsequent selected items, or -1 when no more''' return self.GetNextItem(item, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED) def IsSelected(self, idx): '''return True if the item is selected''' return (self.GetItemState(idx, wx.LIST_STATE_SELECTED) & wx.LIST_STATE_SELECTED) != 0 def SetColumnImage(self, col, image): item = self.GetColumn(col) # preserve all other attributes too item.SetMask( wx.LIST_MASK_STATE | wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_DATA | wx.LIST_SET_ITEM | wx.LIST_MASK_WIDTH | wx.LIST_MASK_FORMAT ) item.SetImage(image) self.SetColumn(col, item) def ClearColumnImage(self, col): self.SetColumnImage(col, -1) def Append(self, entry): '''Append an item to the list control. The entry parameter should be a sequence with an item for each column''' if len(entry): if wx.USE_UNICODE: cvtfunc = unicode else: cvtfunc = str pos = self.GetItemCount() self.InsertStringItem(pos, cvtfunc(entry[0])) for i in range(1, len(entry)): self.SetStringItem(pos, i, cvtfunc(entry[i])) return pos def SortItems(*args, **kwargs): """SortItems(self, PyObject func) -> bool""" return _controls_.ListCtrl_SortItems(*args, **kwargs) def GetMainWindow(*args, **kwargs): """GetMainWindow(self) -> Window""" return _controls_.ListCtrl_GetMainWindow(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ListCtrl_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) ColumnCount = property(GetColumnCount,doc="See `GetColumnCount`") CountPerPage = property(GetCountPerPage,doc="See `GetCountPerPage`") EditControl = property(GetEditControl,doc="See `GetEditControl`") FocusedItem = property(GetFocusedItem,doc="See `GetFocusedItem`") ItemCount = property(GetItemCount,SetItemCount,doc="See `GetItemCount` and `SetItemCount`") MainWindow = property(GetMainWindow,doc="See `GetMainWindow`") SelectedItemCount = property(GetSelectedItemCount,doc="See `GetSelectedItemCount`") TextColour = property(GetTextColour,SetTextColour,doc="See `GetTextColour` and `SetTextColour`") TopItem = property(GetTopItem,doc="See `GetTopItem`") ViewRect = property(GetViewRect,doc="See `GetViewRect`") _controls_.ListCtrl_swigregister(ListCtrl) def PreListCtrl(*args, **kwargs): """PreListCtrl() -> ListCtrl""" val = _controls_.new_PreListCtrl(*args, **kwargs) return val def ListCtrl_HasColumnOrderSupport(*args): """ListCtrl_HasColumnOrderSupport() -> bool""" return _controls_.ListCtrl_HasColumnOrderSupport(*args) def ListCtrl_GetClassDefaultAttributes(*args, **kwargs): """ ListCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ListCtrl_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- class ListView(ListCtrl): """Proxy of C++ ListView class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=LC_REPORT, Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> ListView """ _controls_.ListView_swiginit(self,_controls_.new_ListView(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=LC_REPORT, Validator validator=DefaultValidator, String name=ListCtrlNameStr) -> bool Do the 2nd phase and create the GUI control. """ return _controls_.ListView_Create(*args, **kwargs) def Select(*args, **kwargs): """Select(self, long n, bool on=True)""" return _controls_.ListView_Select(*args, **kwargs) def Focus(*args, **kwargs): """Focus(self, long index)""" return _controls_.ListView_Focus(*args, **kwargs) def GetFocusedItem(*args, **kwargs): """GetFocusedItem(self) -> long""" return _controls_.ListView_GetFocusedItem(*args, **kwargs) def GetNextSelected(*args, **kwargs): """GetNextSelected(self, long item) -> long""" return _controls_.ListView_GetNextSelected(*args, **kwargs) def GetFirstSelected(*args, **kwargs): """GetFirstSelected(self) -> long""" return _controls_.ListView_GetFirstSelected(*args, **kwargs) def IsSelected(*args, **kwargs): """IsSelected(self, long index) -> bool""" return _controls_.ListView_IsSelected(*args, **kwargs) def SetColumnImage(*args, **kwargs): """SetColumnImage(self, int col, int image)""" return _controls_.ListView_SetColumnImage(*args, **kwargs) def ClearColumnImage(*args, **kwargs): """ClearColumnImage(self, int col)""" return _controls_.ListView_ClearColumnImage(*args, **kwargs) FocusedItem = property(GetFocusedItem,doc="See `GetFocusedItem`") _controls_.ListView_swigregister(ListView) def PreListView(*args, **kwargs): """PreListView() -> ListView""" val = _controls_.new_PreListView(*args, **kwargs) return val #--------------------------------------------------------------------------- TR_NO_BUTTONS = _controls_.TR_NO_BUTTONS TR_HAS_BUTTONS = _controls_.TR_HAS_BUTTONS TR_NO_LINES = _controls_.TR_NO_LINES TR_LINES_AT_ROOT = _controls_.TR_LINES_AT_ROOT TR_SINGLE = _controls_.TR_SINGLE TR_MULTIPLE = _controls_.TR_MULTIPLE TR_EXTENDED = _controls_.TR_EXTENDED TR_HAS_VARIABLE_ROW_HEIGHT = _controls_.TR_HAS_VARIABLE_ROW_HEIGHT TR_EDIT_LABELS = _controls_.TR_EDIT_LABELS TR_HIDE_ROOT = _controls_.TR_HIDE_ROOT TR_ROW_LINES = _controls_.TR_ROW_LINES TR_FULL_ROW_HIGHLIGHT = _controls_.TR_FULL_ROW_HIGHLIGHT TR_DEFAULT_STYLE = _controls_.TR_DEFAULT_STYLE TR_TWIST_BUTTONS = _controls_.TR_TWIST_BUTTONS # obsolete TR_MAC_BUTTONS = 0 wxTR_AQUA_BUTTONS = 0 TreeItemIcon_Normal = _controls_.TreeItemIcon_Normal TreeItemIcon_Selected = _controls_.TreeItemIcon_Selected TreeItemIcon_Expanded = _controls_.TreeItemIcon_Expanded TreeItemIcon_SelectedExpanded = _controls_.TreeItemIcon_SelectedExpanded TreeItemIcon_Max = _controls_.TreeItemIcon_Max TREE_ITEMSTATE_NONE = _controls_.TREE_ITEMSTATE_NONE TREE_ITEMSTATE_NEXT = _controls_.TREE_ITEMSTATE_NEXT TREE_ITEMSTATE_PREV = _controls_.TREE_ITEMSTATE_PREV TREE_HITTEST_ABOVE = _controls_.TREE_HITTEST_ABOVE TREE_HITTEST_BELOW = _controls_.TREE_HITTEST_BELOW TREE_HITTEST_NOWHERE = _controls_.TREE_HITTEST_NOWHERE TREE_HITTEST_ONITEMBUTTON = _controls_.TREE_HITTEST_ONITEMBUTTON TREE_HITTEST_ONITEMICON = _controls_.TREE_HITTEST_ONITEMICON TREE_HITTEST_ONITEMINDENT = _controls_.TREE_HITTEST_ONITEMINDENT TREE_HITTEST_ONITEMLABEL = _controls_.TREE_HITTEST_ONITEMLABEL TREE_HITTEST_ONITEMRIGHT = _controls_.TREE_HITTEST_ONITEMRIGHT TREE_HITTEST_ONITEMSTATEICON = _controls_.TREE_HITTEST_ONITEMSTATEICON TREE_HITTEST_TOLEFT = _controls_.TREE_HITTEST_TOLEFT TREE_HITTEST_TORIGHT = _controls_.TREE_HITTEST_TORIGHT TREE_HITTEST_ONITEMUPPERPART = _controls_.TREE_HITTEST_ONITEMUPPERPART TREE_HITTEST_ONITEMLOWERPART = _controls_.TREE_HITTEST_ONITEMLOWERPART TREE_HITTEST_ONITEM = _controls_.TREE_HITTEST_ONITEM #--------------------------------------------------------------------------- class TreeItemId(object): """Proxy of C++ TreeItemId class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self) -> TreeItemId""" _controls_.TreeItemId_swiginit(self,_controls_.new_TreeItemId(*args, **kwargs)) __swig_destroy__ = _controls_.delete_TreeItemId __del__ = lambda self : None; def IsOk(*args, **kwargs): """IsOk(self) -> bool""" return _controls_.TreeItemId_IsOk(*args, **kwargs) def __eq__(*args, **kwargs): """__eq__(self, TreeItemId other) -> bool""" return _controls_.TreeItemId___eq__(*args, **kwargs) def __ne__(*args, **kwargs): """__ne__(self, TreeItemId other) -> bool""" return _controls_.TreeItemId___ne__(*args, **kwargs) m_pItem = property(_controls_.TreeItemId_m_pItem_get, _controls_.TreeItemId_m_pItem_set) Ok = IsOk def __nonzero__(self): return self.IsOk() _controls_.TreeItemId_swigregister(TreeItemId) TreeCtrlNameStr = cvar.TreeCtrlNameStr class TreeItemData(object): """Proxy of C++ TreeItemData class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self, PyObject obj=None) -> TreeItemData""" _controls_.TreeItemData_swiginit(self,_controls_.new_TreeItemData(*args, **kwargs)) __swig_destroy__ = _controls_.delete_TreeItemData __del__ = lambda self : None; def GetData(*args, **kwargs): """GetData(self) -> PyObject""" return _controls_.TreeItemData_GetData(*args, **kwargs) def SetData(*args, **kwargs): """SetData(self, PyObject obj)""" return _controls_.TreeItemData_SetData(*args, **kwargs) def GetId(*args, **kwargs): """GetId(self) -> TreeItemId""" return _controls_.TreeItemData_GetId(*args, **kwargs) def SetId(*args, **kwargs): """SetId(self, TreeItemId id)""" return _controls_.TreeItemData_SetId(*args, **kwargs) def Destroy(*args, **kwargs): """Destroy(self)""" args[0].this.own(False) return _controls_.TreeItemData_Destroy(*args, **kwargs) Data = property(GetData,SetData,doc="See `GetData` and `SetData`") Id = property(GetId,SetId,doc="See `GetId` and `SetId`") _controls_.TreeItemData_swigregister(TreeItemData) #--------------------------------------------------------------------------- wxEVT_COMMAND_TREE_BEGIN_DRAG = _controls_.wxEVT_COMMAND_TREE_BEGIN_DRAG wxEVT_COMMAND_TREE_BEGIN_RDRAG = _controls_.wxEVT_COMMAND_TREE_BEGIN_RDRAG wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT = _controls_.wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT wxEVT_COMMAND_TREE_END_LABEL_EDIT = _controls_.wxEVT_COMMAND_TREE_END_LABEL_EDIT wxEVT_COMMAND_TREE_DELETE_ITEM = _controls_.wxEVT_COMMAND_TREE_DELETE_ITEM wxEVT_COMMAND_TREE_GET_INFO = _controls_.wxEVT_COMMAND_TREE_GET_INFO wxEVT_COMMAND_TREE_SET_INFO = _controls_.wxEVT_COMMAND_TREE_SET_INFO wxEVT_COMMAND_TREE_ITEM_EXPANDED = _controls_.wxEVT_COMMAND_TREE_ITEM_EXPANDED wxEVT_COMMAND_TREE_ITEM_EXPANDING = _controls_.wxEVT_COMMAND_TREE_ITEM_EXPANDING wxEVT_COMMAND_TREE_ITEM_COLLAPSED = _controls_.wxEVT_COMMAND_TREE_ITEM_COLLAPSED wxEVT_COMMAND_TREE_ITEM_COLLAPSING = _controls_.wxEVT_COMMAND_TREE_ITEM_COLLAPSING wxEVT_COMMAND_TREE_SEL_CHANGED = _controls_.wxEVT_COMMAND_TREE_SEL_CHANGED wxEVT_COMMAND_TREE_SEL_CHANGING = _controls_.wxEVT_COMMAND_TREE_SEL_CHANGING wxEVT_COMMAND_TREE_KEY_DOWN = _controls_.wxEVT_COMMAND_TREE_KEY_DOWN wxEVT_COMMAND_TREE_ITEM_ACTIVATED = _controls_.wxEVT_COMMAND_TREE_ITEM_ACTIVATED wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK = _controls_.wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK = _controls_.wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK wxEVT_COMMAND_TREE_END_DRAG = _controls_.wxEVT_COMMAND_TREE_END_DRAG wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK = _controls_.wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP = _controls_.wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP wxEVT_COMMAND_TREE_ITEM_MENU = _controls_.wxEVT_COMMAND_TREE_ITEM_MENU EVT_TREE_BEGIN_DRAG = wx.PyEventBinder(wxEVT_COMMAND_TREE_BEGIN_DRAG , 1) EVT_TREE_BEGIN_RDRAG = wx.PyEventBinder(wxEVT_COMMAND_TREE_BEGIN_RDRAG , 1) EVT_TREE_BEGIN_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT , 1) EVT_TREE_END_LABEL_EDIT = wx.PyEventBinder(wxEVT_COMMAND_TREE_END_LABEL_EDIT , 1) EVT_TREE_DELETE_ITEM = wx.PyEventBinder(wxEVT_COMMAND_TREE_DELETE_ITEM , 1) EVT_TREE_GET_INFO = wx.PyEventBinder(wxEVT_COMMAND_TREE_GET_INFO , 1) EVT_TREE_SET_INFO = wx.PyEventBinder(wxEVT_COMMAND_TREE_SET_INFO , 1) EVT_TREE_ITEM_EXPANDED = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_EXPANDED , 1) EVT_TREE_ITEM_EXPANDING = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_EXPANDING , 1) EVT_TREE_ITEM_COLLAPSED = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_COLLAPSED , 1) EVT_TREE_ITEM_COLLAPSING = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_COLLAPSING , 1) EVT_TREE_SEL_CHANGED = wx.PyEventBinder(wxEVT_COMMAND_TREE_SEL_CHANGED , 1) EVT_TREE_SEL_CHANGING = wx.PyEventBinder(wxEVT_COMMAND_TREE_SEL_CHANGING , 1) EVT_TREE_KEY_DOWN = wx.PyEventBinder(wxEVT_COMMAND_TREE_KEY_DOWN , 1) EVT_TREE_ITEM_ACTIVATED = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_ACTIVATED , 1) EVT_TREE_ITEM_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK , 1) EVT_TREE_ITEM_MIDDLE_CLICK = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK, 1) EVT_TREE_END_DRAG = wx.PyEventBinder(wxEVT_COMMAND_TREE_END_DRAG , 1) EVT_TREE_STATE_IMAGE_CLICK = wx.PyEventBinder(wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK, 1) EVT_TREE_ITEM_GETTOOLTIP = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP, 1) EVT_TREE_ITEM_MENU = wx.PyEventBinder(wxEVT_COMMAND_TREE_ITEM_MENU, 1) class TreeEvent(_core.NotifyEvent): """Proxy of C++ TreeEvent class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): """ __init__(self, EventType commandType=wxEVT_NULL, int id=0) -> TreeEvent __init__(self, EventType commandType, TreeCtrl tree, TreeItemId item=NullTreeItemId) -> TreeEvent """ _controls_.TreeEvent_swiginit(self,_controls_.new_TreeEvent(*args)) def GetItem(*args, **kwargs): """GetItem(self) -> TreeItemId""" return _controls_.TreeEvent_GetItem(*args, **kwargs) def SetItem(*args, **kwargs): """SetItem(self, TreeItemId item)""" return _controls_.TreeEvent_SetItem(*args, **kwargs) def GetOldItem(*args, **kwargs): """GetOldItem(self) -> TreeItemId""" return _controls_.TreeEvent_GetOldItem(*args, **kwargs) def SetOldItem(*args, **kwargs): """SetOldItem(self, TreeItemId item)""" return _controls_.TreeEvent_SetOldItem(*args, **kwargs) def GetPoint(*args, **kwargs): """GetPoint(self) -> Point""" return _controls_.TreeEvent_GetPoint(*args, **kwargs) def SetPoint(*args, **kwargs): """SetPoint(self, Point pt)""" return _controls_.TreeEvent_SetPoint(*args, **kwargs) def GetKeyEvent(*args, **kwargs): """GetKeyEvent(self) -> KeyEvent""" return _controls_.TreeEvent_GetKeyEvent(*args, **kwargs) def GetKeyCode(*args, **kwargs): """GetKeyCode(self) -> int""" return _controls_.TreeEvent_GetKeyCode(*args, **kwargs) def SetKeyEvent(*args, **kwargs): """SetKeyEvent(self, KeyEvent evt)""" return _controls_.TreeEvent_SetKeyEvent(*args, **kwargs) def GetLabel(*args, **kwargs): """GetLabel(self) -> String""" return _controls_.TreeEvent_GetLabel(*args, **kwargs) def SetLabel(*args, **kwargs): """SetLabel(self, String label)""" return _controls_.TreeEvent_SetLabel(*args, **kwargs) def IsEditCancelled(*args, **kwargs): """IsEditCancelled(self) -> bool""" return _controls_.TreeEvent_IsEditCancelled(*args, **kwargs) def SetEditCanceled(*args, **kwargs): """SetEditCanceled(self, bool editCancelled)""" return _controls_.TreeEvent_SetEditCanceled(*args, **kwargs) def SetToolTip(*args, **kwargs): """SetToolTip(self, String toolTip)""" return _controls_.TreeEvent_SetToolTip(*args, **kwargs) def GetToolTip(*args, **kwargs): """GetToolTip(self) -> String""" return _controls_.TreeEvent_GetToolTip(*args, **kwargs) Item = property(GetItem,SetItem,doc="See `GetItem` and `SetItem`") KeyCode = property(GetKeyCode,doc="See `GetKeyCode`") KeyEvent = property(GetKeyEvent,SetKeyEvent,doc="See `GetKeyEvent` and `SetKeyEvent`") Label = property(GetLabel,SetLabel,doc="See `GetLabel` and `SetLabel`") OldItem = property(GetOldItem,SetOldItem,doc="See `GetOldItem` and `SetOldItem`") Point = property(GetPoint,SetPoint,doc="See `GetPoint` and `SetPoint`") ToolTip = property(GetToolTip,SetToolTip,doc="See `GetToolTip` and `SetToolTip`") EditCancelled = property(IsEditCancelled,SetEditCanceled,doc="See `IsEditCancelled` and `SetEditCanceled`") _controls_.TreeEvent_swigregister(TreeEvent) #--------------------------------------------------------------------------- class TreeCtrl(_core.Control): """Proxy of C++ TreeCtrl class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=TR_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=TreeCtrlNameStr) -> TreeCtrl """ _controls_.TreeCtrl_swiginit(self,_controls_.new_TreeCtrl(*args, **kwargs)) self._setOORInfo(self);TreeCtrl._setCallbackInfo(self, self, TreeCtrl) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=TR_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=TreeCtrlNameStr) -> bool Do the 2nd phase and create the GUI control. """ return _controls_.TreeCtrl_Create(*args, **kwargs) def _setCallbackInfo(*args, **kwargs): """_setCallbackInfo(self, PyObject self, PyObject _class)""" return _controls_.TreeCtrl__setCallbackInfo(*args, **kwargs) def GetCount(*args, **kwargs): """GetCount(self) -> unsigned int""" return _controls_.TreeCtrl_GetCount(*args, **kwargs) def GetIndent(*args, **kwargs): """GetIndent(self) -> unsigned int""" return _controls_.TreeCtrl_GetIndent(*args, **kwargs) def SetIndent(*args, **kwargs): """SetIndent(self, unsigned int indent)""" return _controls_.TreeCtrl_SetIndent(*args, **kwargs) def GetSpacing(*args, **kwargs): """GetSpacing(self) -> unsigned int""" return _controls_.TreeCtrl_GetSpacing(*args, **kwargs) def SetSpacing(*args, **kwargs): """SetSpacing(self, unsigned int spacing)""" return _controls_.TreeCtrl_SetSpacing(*args, **kwargs) def GetImageList(*args, **kwargs): """GetImageList(self) -> ImageList""" return _controls_.TreeCtrl_GetImageList(*args, **kwargs) def GetStateImageList(*args, **kwargs): """GetStateImageList(self) -> ImageList""" return _controls_.TreeCtrl_GetStateImageList(*args, **kwargs) def SetImageList(*args, **kwargs): """SetImageList(self, ImageList imageList)""" return _controls_.TreeCtrl_SetImageList(*args, **kwargs) def SetStateImageList(*args, **kwargs): """SetStateImageList(self, ImageList imageList)""" return _controls_.TreeCtrl_SetStateImageList(*args, **kwargs) def AssignImageList(*args, **kwargs): """AssignImageList(self, ImageList imageList)""" return _controls_.TreeCtrl_AssignImageList(*args, **kwargs) def AssignStateImageList(*args, **kwargs): """AssignStateImageList(self, ImageList imageList)""" return _controls_.TreeCtrl_AssignStateImageList(*args, **kwargs) def GetItemText(*args, **kwargs): """GetItemText(self, TreeItemId item) -> String""" return _controls_.TreeCtrl_GetItemText(*args, **kwargs) def GetItemImage(*args, **kwargs): """GetItemImage(self, TreeItemId item, int which=TreeItemIcon_Normal) -> int""" return _controls_.TreeCtrl_GetItemImage(*args, **kwargs) def GetItemData(*args, **kwargs): """GetItemData(self, TreeItemId item) -> TreeItemData""" return _controls_.TreeCtrl_GetItemData(*args, **kwargs) def GetItemPyData(*args, **kwargs): """GetItemPyData(self, TreeItemId item) -> PyObject""" return _controls_.TreeCtrl_GetItemPyData(*args, **kwargs) GetPyData = GetItemPyData def GetItemTextColour(*args, **kwargs): """GetItemTextColour(self, TreeItemId item) -> Colour""" return _controls_.TreeCtrl_GetItemTextColour(*args, **kwargs) def GetItemBackgroundColour(*args, **kwargs): """GetItemBackgroundColour(self, TreeItemId item) -> Colour""" return _controls_.TreeCtrl_GetItemBackgroundColour(*args, **kwargs) def GetItemFont(*args, **kwargs): """GetItemFont(self, TreeItemId item) -> Font""" return _controls_.TreeCtrl_GetItemFont(*args, **kwargs) def GetItemState(*args, **kwargs): """GetItemState(self, TreeItemId item) -> int""" return _controls_.TreeCtrl_GetItemState(*args, **kwargs) def SetItemText(*args, **kwargs): """SetItemText(self, TreeItemId item, String text)""" return _controls_.TreeCtrl_SetItemText(*args, **kwargs) def SetItemImage(*args, **kwargs): """SetItemImage(self, TreeItemId item, int image, int which=TreeItemIcon_Normal)""" return _controls_.TreeCtrl_SetItemImage(*args, **kwargs) def SetItemData(*args, **kwargs): """SetItemData(self, TreeItemId item, TreeItemData data)""" return _controls_.TreeCtrl_SetItemData(*args, **kwargs) def SetItemPyData(*args, **kwargs): """SetItemPyData(self, TreeItemId item, PyObject obj)""" return _controls_.TreeCtrl_SetItemPyData(*args, **kwargs) SetPyData = SetItemPyData def SetItemHasChildren(*args, **kwargs): """SetItemHasChildren(self, TreeItemId item, bool has=True)""" return _controls_.TreeCtrl_SetItemHasChildren(*args, **kwargs) def SetItemBold(*args, **kwargs): """SetItemBold(self, TreeItemId item, bool bold=True)""" return _controls_.TreeCtrl_SetItemBold(*args, **kwargs) def SetItemDropHighlight(*args, **kwargs): """SetItemDropHighlight(self, TreeItemId item, bool highlight=True)""" return _controls_.TreeCtrl_SetItemDropHighlight(*args, **kwargs) def SetItemTextColour(*args, **kwargs): """SetItemTextColour(self, TreeItemId item, Colour col)""" return _controls_.TreeCtrl_SetItemTextColour(*args, **kwargs) def SetItemBackgroundColour(*args, **kwargs): """SetItemBackgroundColour(self, TreeItemId item, Colour col)""" return _controls_.TreeCtrl_SetItemBackgroundColour(*args, **kwargs) def SetItemFont(*args, **kwargs): """SetItemFont(self, TreeItemId item, Font font)""" return _controls_.TreeCtrl_SetItemFont(*args, **kwargs) def SetItemState(*args, **kwargs): """SetItemState(self, TreeItemId item, int state)""" return _controls_.TreeCtrl_SetItemState(*args, **kwargs) def IsVisible(*args, **kwargs): """IsVisible(self, TreeItemId item) -> bool""" return _controls_.TreeCtrl_IsVisible(*args, **kwargs) def ItemHasChildren(*args, **kwargs): """ItemHasChildren(self, TreeItemId item) -> bool""" return _controls_.TreeCtrl_ItemHasChildren(*args, **kwargs) def IsExpanded(*args, **kwargs): """IsExpanded(self, TreeItemId item) -> bool""" return _controls_.TreeCtrl_IsExpanded(*args, **kwargs) def IsSelected(*args, **kwargs): """IsSelected(self, TreeItemId item) -> bool""" return _controls_.TreeCtrl_IsSelected(*args, **kwargs) def IsBold(*args, **kwargs): """IsBold(self, TreeItemId item) -> bool""" return _controls_.TreeCtrl_IsBold(*args, **kwargs) def IsEmpty(*args, **kwargs): """IsEmpty(self) -> bool""" return _controls_.TreeCtrl_IsEmpty(*args, **kwargs) def GetChildrenCount(*args, **kwargs): """GetChildrenCount(self, TreeItemId item, bool recursively=True) -> size_t""" return _controls_.TreeCtrl_GetChildrenCount(*args, **kwargs) def GetRootItem(*args, **kwargs): """GetRootItem(self) -> TreeItemId""" return _controls_.TreeCtrl_GetRootItem(*args, **kwargs) def GetSelection(*args, **kwargs): """GetSelection(self) -> TreeItemId""" return _controls_.TreeCtrl_GetSelection(*args, **kwargs) def GetSelections(*args, **kwargs): """GetSelections(self) -> PyObject""" return _controls_.TreeCtrl_GetSelections(*args, **kwargs) def GetFocusedItem(*args, **kwargs): """GetFocusedItem(self) -> TreeItemId""" return _controls_.TreeCtrl_GetFocusedItem(*args, **kwargs) def ClearFocusedItem(*args, **kwargs): """ClearFocusedItem(self)""" return _controls_.TreeCtrl_ClearFocusedItem(*args, **kwargs) def SetFocusedItem(*args, **kwargs): """SetFocusedItem(self, TreeItemId item)""" return _controls_.TreeCtrl_SetFocusedItem(*args, **kwargs) def GetItemParent(*args, **kwargs): """GetItemParent(self, TreeItemId item) -> TreeItemId""" return _controls_.TreeCtrl_GetItemParent(*args, **kwargs) def GetFirstChild(*args, **kwargs): """GetFirstChild(self, TreeItemId item) -> PyObject""" return _controls_.TreeCtrl_GetFirstChild(*args, **kwargs) def GetNextChild(*args, **kwargs): """GetNextChild(self, TreeItemId item, void cookie) -> PyObject""" return _controls_.TreeCtrl_GetNextChild(*args, **kwargs) def GetLastChild(*args, **kwargs): """GetLastChild(self, TreeItemId item) -> TreeItemId""" return _controls_.TreeCtrl_GetLastChild(*args, **kwargs) def GetNextSibling(*args, **kwargs): """GetNextSibling(self, TreeItemId item) -> TreeItemId""" return _controls_.TreeCtrl_GetNextSibling(*args, **kwargs) def GetPrevSibling(*args, **kwargs): """GetPrevSibling(self, TreeItemId item) -> TreeItemId""" return _controls_.TreeCtrl_GetPrevSibling(*args, **kwargs) def GetFirstVisibleItem(*args, **kwargs): """GetFirstVisibleItem(self) -> TreeItemId""" return _controls_.TreeCtrl_GetFirstVisibleItem(*args, **kwargs) def GetNextVisible(*args, **kwargs): """GetNextVisible(self, TreeItemId item) -> TreeItemId""" return _controls_.TreeCtrl_GetNextVisible(*args, **kwargs) def GetPrevVisible(*args, **kwargs): """GetPrevVisible(self, TreeItemId item) -> TreeItemId""" return _controls_.TreeCtrl_GetPrevVisible(*args, **kwargs) def AddRoot(*args, **kwargs): """AddRoot(self, String text, int image=-1, int selectedImage=-1, TreeItemData data=None) -> TreeItemId""" return _controls_.TreeCtrl_AddRoot(*args, **kwargs) def PrependItem(*args, **kwargs): """ PrependItem(self, TreeItemId parent, String text, int image=-1, int selectedImage=-1, TreeItemData data=None) -> TreeItemId """ return _controls_.TreeCtrl_PrependItem(*args, **kwargs) def InsertItem(*args, **kwargs): """ InsertItem(self, TreeItemId parent, TreeItemId idPrevious, String text, int image=-1, int selectedImage=-1, TreeItemData data=None) -> TreeItemId """ return _controls_.TreeCtrl_InsertItem(*args, **kwargs) def InsertItemBefore(*args, **kwargs): """ InsertItemBefore(self, TreeItemId parent, size_t index, String text, int image=-1, int selectedImage=-1, TreeItemData data=None) -> TreeItemId """ return _controls_.TreeCtrl_InsertItemBefore(*args, **kwargs) def AppendItem(*args, **kwargs): """ AppendItem(self, TreeItemId parent, String text, int image=-1, int selectedImage=-1, TreeItemData data=None) -> TreeItemId """ return _controls_.TreeCtrl_AppendItem(*args, **kwargs) def Delete(*args, **kwargs): """Delete(self, TreeItemId item)""" return _controls_.TreeCtrl_Delete(*args, **kwargs) def DeleteChildren(*args, **kwargs): """DeleteChildren(self, TreeItemId item)""" return _controls_.TreeCtrl_DeleteChildren(*args, **kwargs) def DeleteAllItems(*args, **kwargs): """DeleteAllItems(self)""" return _controls_.TreeCtrl_DeleteAllItems(*args, **kwargs) def Expand(*args, **kwargs): """Expand(self, TreeItemId item)""" return _controls_.TreeCtrl_Expand(*args, **kwargs) def ExpandAllChildren(*args, **kwargs): """ExpandAllChildren(self, TreeItemId item)""" return _controls_.TreeCtrl_ExpandAllChildren(*args, **kwargs) def ExpandAll(*args, **kwargs): """ExpandAll(self)""" return _controls_.TreeCtrl_ExpandAll(*args, **kwargs) def Collapse(*args, **kwargs): """Collapse(self, TreeItemId item)""" return _controls_.TreeCtrl_Collapse(*args, **kwargs) def CollapseAllChildren(*args, **kwargs): """CollapseAllChildren(self, TreeItemId item)""" return _controls_.TreeCtrl_CollapseAllChildren(*args, **kwargs) def CollapseAll(*args, **kwargs): """CollapseAll(self)""" return _controls_.TreeCtrl_CollapseAll(*args, **kwargs) def CollapseAndReset(*args, **kwargs): """CollapseAndReset(self, TreeItemId item)""" return _controls_.TreeCtrl_CollapseAndReset(*args, **kwargs) def Toggle(*args, **kwargs): """Toggle(self, TreeItemId item)""" return _controls_.TreeCtrl_Toggle(*args, **kwargs) def Unselect(*args, **kwargs): """Unselect(self)""" return _controls_.TreeCtrl_Unselect(*args, **kwargs) def UnselectItem(*args, **kwargs): """UnselectItem(self, TreeItemId item)""" return _controls_.TreeCtrl_UnselectItem(*args, **kwargs) def UnselectAll(*args, **kwargs): """UnselectAll(self)""" return _controls_.TreeCtrl_UnselectAll(*args, **kwargs) def SelectItem(*args, **kwargs): """SelectItem(self, TreeItemId item, bool select=True)""" return _controls_.TreeCtrl_SelectItem(*args, **kwargs) def SelectChildren(*args, **kwargs): """SelectChildren(self, TreeItemId parent)""" return _controls_.TreeCtrl_SelectChildren(*args, **kwargs) def ToggleItemSelection(*args, **kwargs): """ToggleItemSelection(self, TreeItemId item)""" return _controls_.TreeCtrl_ToggleItemSelection(*args, **kwargs) def EnsureVisible(*args, **kwargs): """EnsureVisible(self, TreeItemId item)""" return _controls_.TreeCtrl_EnsureVisible(*args, **kwargs) def ScrollTo(*args, **kwargs): """ScrollTo(self, TreeItemId item)""" return _controls_.TreeCtrl_ScrollTo(*args, **kwargs) def EditLabel(*args, **kwargs): """EditLabel(self, TreeItemId item)""" return _controls_.TreeCtrl_EditLabel(*args, **kwargs) def GetEditControl(*args, **kwargs): """GetEditControl(self) -> TextCtrl""" return _controls_.TreeCtrl_GetEditControl(*args, **kwargs) def SortChildren(*args, **kwargs): """SortChildren(self, TreeItemId item)""" return _controls_.TreeCtrl_SortChildren(*args, **kwargs) def HitTest(*args, **kwargs): """ HitTest(Point point) -> (item, where) Determine which item (if any) belongs the given point. The coordinates specified are relative to the client area of tree ctrl and the where return value is set to a bitmask of wxTREE_HITTEST_xxx constants. """ return _controls_.TreeCtrl_HitTest(*args, **kwargs) def GetBoundingRect(*args, **kwargs): """GetBoundingRect(self, TreeItemId item, bool textOnly=False) -> PyObject""" return _controls_.TreeCtrl_GetBoundingRect(*args, **kwargs) def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.TreeCtrl_GetClassDefaultAttributes(*args, **kwargs) GetClassDefaultAttributes = staticmethod(GetClassDefaultAttributes) def SetQuickBestSize(*args, **kwargs): """SetQuickBestSize(self, bool q)""" return _controls_.TreeCtrl_SetQuickBestSize(*args, **kwargs) def GetQuickBestSize(*args, **kwargs): """GetQuickBestSize(self) -> bool""" return _controls_.TreeCtrl_GetQuickBestSize(*args, **kwargs) Count = property(GetCount,doc="See `GetCount`") EditControl = property(GetEditControl,doc="See `GetEditControl`") FirstVisibleItem = property(GetFirstVisibleItem,doc="See `GetFirstVisibleItem`") ImageList = property(GetImageList,SetImageList,doc="See `GetImageList` and `SetImageList`") Indent = property(GetIndent,SetIndent,doc="See `GetIndent` and `SetIndent`") QuickBestSize = property(GetQuickBestSize,SetQuickBestSize,doc="See `GetQuickBestSize` and `SetQuickBestSize`") RootItem = property(GetRootItem,doc="See `GetRootItem`") Selection = property(GetSelection,doc="See `GetSelection`") Selections = property(GetSelections,doc="See `GetSelections`") Spacing = property(GetSpacing,SetSpacing,doc="See `GetSpacing` and `SetSpacing`") StateImageList = property(GetStateImageList,SetStateImageList,doc="See `GetStateImageList` and `SetStateImageList`") _controls_.TreeCtrl_swigregister(TreeCtrl) def PreTreeCtrl(*args, **kwargs): """PreTreeCtrl() -> TreeCtrl""" val = _controls_.new_PreTreeCtrl(*args, **kwargs) return val def TreeCtrl_GetClassDefaultAttributes(*args, **kwargs): """ TreeCtrl_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.TreeCtrl_GetClassDefaultAttributes(*args, **kwargs) #--------------------------------------------------------------------------- DIRCTRL_DIR_ONLY = _controls_.DIRCTRL_DIR_ONLY DIRCTRL_SELECT_FIRST = _controls_.DIRCTRL_SELECT_FIRST DIRCTRL_SHOW_FILTERS = _controls_.DIRCTRL_SHOW_FILTERS DIRCTRL_3D_INTERNAL = _controls_.DIRCTRL_3D_INTERNAL DIRCTRL_EDIT_LABELS = _controls_.DIRCTRL_EDIT_LABELS DIRCTRL_MULTIPLE = _controls_.DIRCTRL_MULTIPLE class DirItemData(_core.Object): """Proxy of C++ DirItemData class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self): raise AttributeError, "No constructor defined" __repr__ = _swig_repr def SetNewDirName(*args, **kwargs): """SetNewDirName(self, String path)""" return _controls_.DirItemData_SetNewDirName(*args, **kwargs) m_path = property(_controls_.DirItemData_m_path_get, _controls_.DirItemData_m_path_set) m_name = property(_controls_.DirItemData_m_name_get, _controls_.DirItemData_m_name_set) m_isHidden = property(_controls_.DirItemData_m_isHidden_get, _controls_.DirItemData_m_isHidden_set) m_isExpanded = property(_controls_.DirItemData_m_isExpanded_get, _controls_.DirItemData_m_isExpanded_set) m_isDir = property(_controls_.DirItemData_m_isDir_get, _controls_.DirItemData_m_isDir_set) _controls_.DirItemData_swigregister(DirItemData) DirDialogDefaultFolderStr = cvar.DirDialogDefaultFolderStr class GenericDirCtrl(_core.Control): """Proxy of C++ GenericDirCtrl class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String dir=DirDialogDefaultFolderStr, Point pos=DefaultPosition, Size size=DefaultSize, long style=DIRCTRL_3D_INTERNAL, String filter=EmptyString, int defaultFilter=0, String name=TreeCtrlNameStr) -> GenericDirCtrl """ _controls_.GenericDirCtrl_swiginit(self,_controls_.new_GenericDirCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String dir=DirDialogDefaultFolderStr, Point pos=DefaultPosition, Size size=DefaultSize, long style=DIRCTRL_3D_INTERNAL, String filter=EmptyString, int defaultFilter=0, String name=TreeCtrlNameStr) -> bool """ return _controls_.GenericDirCtrl_Create(*args, **kwargs) def ExpandPath(*args, **kwargs): """ExpandPath(self, String path) -> bool""" return _controls_.GenericDirCtrl_ExpandPath(*args, **kwargs) def CollapsePath(*args, **kwargs): """CollapsePath(self, String path) -> bool""" return _controls_.GenericDirCtrl_CollapsePath(*args, **kwargs) def GetDefaultPath(*args, **kwargs): """GetDefaultPath(self) -> String""" return _controls_.GenericDirCtrl_GetDefaultPath(*args, **kwargs) def SetDefaultPath(*args, **kwargs): """SetDefaultPath(self, String path)""" return _controls_.GenericDirCtrl_SetDefaultPath(*args, **kwargs) def GetPath(*args, **kwargs): """GetPath(self) -> String""" return _controls_.GenericDirCtrl_GetPath(*args, **kwargs) def GetPaths(*args, **kwargs): """GetPaths(self) -> wxArrayString""" return _controls_.GenericDirCtrl_GetPaths(*args, **kwargs) def GetFilePath(*args, **kwargs): """GetFilePath(self) -> String""" return _controls_.GenericDirCtrl_GetFilePath(*args, **kwargs) def SetPath(*args, **kwargs): """SetPath(self, String path)""" return _controls_.GenericDirCtrl_SetPath(*args, **kwargs) def GetFilePaths(*args, **kwargs): """GetFilePaths(self) -> wxArrayString""" return _controls_.GenericDirCtrl_GetFilePaths(*args, **kwargs) def SelectPath(*args, **kwargs): """SelectPath(self, String path, bool select=True)""" return _controls_.GenericDirCtrl_SelectPath(*args, **kwargs) def SelectPaths(*args, **kwargs): """SelectPaths(self, wxArrayString paths)""" return _controls_.GenericDirCtrl_SelectPaths(*args, **kwargs) def ShowHidden(*args, **kwargs): """ShowHidden(self, bool show)""" return _controls_.GenericDirCtrl_ShowHidden(*args, **kwargs) def GetShowHidden(*args, **kwargs): """GetShowHidden(self) -> bool""" return _controls_.GenericDirCtrl_GetShowHidden(*args, **kwargs) def GetFilter(*args, **kwargs): """GetFilter(self) -> String""" return _controls_.GenericDirCtrl_GetFilter(*args, **kwargs) def SetFilter(*args, **kwargs): """SetFilter(self, String filter)""" return _controls_.GenericDirCtrl_SetFilter(*args, **kwargs) def GetFilterIndex(*args, **kwargs): """GetFilterIndex(self) -> int""" return _controls_.GenericDirCtrl_GetFilterIndex(*args, **kwargs) def SetFilterIndex(*args, **kwargs): """SetFilterIndex(self, int n)""" return _controls_.GenericDirCtrl_SetFilterIndex(*args, **kwargs) def GetRootId(*args, **kwargs): """GetRootId(self) -> TreeItemId""" return _controls_.GenericDirCtrl_GetRootId(*args, **kwargs) def GetTreeCtrl(*args, **kwargs): """GetTreeCtrl(self) -> TreeCtrl""" return _controls_.GenericDirCtrl_GetTreeCtrl(*args, **kwargs) def GetFilterListCtrl(*args, **kwargs): """GetFilterListCtrl(self) -> DirFilterListCtrl""" return _controls_.GenericDirCtrl_GetFilterListCtrl(*args, **kwargs) def UnselectAll(*args, **kwargs): """UnselectAll(self)""" return _controls_.GenericDirCtrl_UnselectAll(*args, **kwargs) def GetDirItemData(*args, **kwargs): """GetDirItemData(self, TreeItemId id) -> DirItemData""" return _controls_.GenericDirCtrl_GetDirItemData(*args, **kwargs) def FindChild(*args, **kwargs): """ FindChild(wxTreeItemId parentId, wxString path) -> (item, done) Find the child that matches the first part of 'path'. E.g. if a child path is "/usr" and 'path' is "/usr/include" then the child for /usr is returned. If the path string has been used (we're at the leaf), done is set to True. """ return _controls_.GenericDirCtrl_FindChild(*args, **kwargs) def DoResize(*args, **kwargs): """DoResize(self)""" return _controls_.GenericDirCtrl_DoResize(*args, **kwargs) def ReCreateTree(*args, **kwargs): """ReCreateTree(self)""" return _controls_.GenericDirCtrl_ReCreateTree(*args, **kwargs) DefaultPath = property(GetDefaultPath,SetDefaultPath,doc="See `GetDefaultPath` and `SetDefaultPath`") FilePath = property(GetFilePath,doc="See `GetFilePath`") Filter = property(GetFilter,SetFilter,doc="See `GetFilter` and `SetFilter`") FilterIndex = property(GetFilterIndex,SetFilterIndex,doc="See `GetFilterIndex` and `SetFilterIndex`") FilterListCtrl = property(GetFilterListCtrl,doc="See `GetFilterListCtrl`") Path = property(GetPath,SetPath,doc="See `GetPath` and `SetPath`") RootId = property(GetRootId,doc="See `GetRootId`") TreeCtrl = property(GetTreeCtrl,doc="See `GetTreeCtrl`") _controls_.GenericDirCtrl_swigregister(GenericDirCtrl) def PreGenericDirCtrl(*args, **kwargs): """PreGenericDirCtrl() -> GenericDirCtrl""" val = _controls_.new_PreGenericDirCtrl(*args, **kwargs) return val class DirFilterListCtrl(Choice): """Proxy of C++ DirFilterListCtrl class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, GenericDirCtrl parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=0) -> DirFilterListCtrl """ _controls_.DirFilterListCtrl_swiginit(self,_controls_.new_DirFilterListCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, GenericDirCtrl parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=0) -> bool """ return _controls_.DirFilterListCtrl_Create(*args, **kwargs) def FillFilterList(*args, **kwargs): """FillFilterList(self, String filter, int defaultFilter)""" return _controls_.DirFilterListCtrl_FillFilterList(*args, **kwargs) _controls_.DirFilterListCtrl_swigregister(DirFilterListCtrl) def PreDirFilterListCtrl(*args, **kwargs): """PreDirFilterListCtrl() -> DirFilterListCtrl""" val = _controls_.new_PreDirFilterListCtrl(*args, **kwargs) return val #--------------------------------------------------------------------------- class PyControl(_core.Control): """Proxy of C++ PyControl class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=ControlNameStr) -> PyControl """ _controls_.PyControl_swiginit(self,_controls_.new_PyControl(*args, **kwargs)) self._setOORInfo(self);PyControl._setCallbackInfo(self, self, PyControl) def _setCallbackInfo(*args, **kwargs): """_setCallbackInfo(self, PyObject self, PyObject _class)""" return _controls_.PyControl__setCallbackInfo(*args, **kwargs) SetBestSize = wx.Window.SetInitialSize def DoEraseBackground(*args, **kwargs): """DoEraseBackground(self, DC dc) -> bool""" return _controls_.PyControl_DoEraseBackground(*args, **kwargs) def DoMoveWindow(*args, **kwargs): """DoMoveWindow(self, int x, int y, int width, int height)""" return _controls_.PyControl_DoMoveWindow(*args, **kwargs) def DoSetSize(*args, **kwargs): """DoSetSize(self, int x, int y, int width, int height, int sizeFlags=SIZE_AUTO)""" return _controls_.PyControl_DoSetSize(*args, **kwargs) def DoSetClientSize(*args, **kwargs): """DoSetClientSize(self, int width, int height)""" return _controls_.PyControl_DoSetClientSize(*args, **kwargs) def DoSetVirtualSize(*args, **kwargs): """DoSetVirtualSize(self, int x, int y)""" return _controls_.PyControl_DoSetVirtualSize(*args, **kwargs) def DoGetSize(*args, **kwargs): """DoGetSize() -> (width, height)""" return _controls_.PyControl_DoGetSize(*args, **kwargs) def DoGetClientSize(*args, **kwargs): """DoGetClientSize() -> (width, height)""" return _controls_.PyControl_DoGetClientSize(*args, **kwargs) def DoGetPosition(*args, **kwargs): """DoGetPosition() -> (x,y)""" return _controls_.PyControl_DoGetPosition(*args, **kwargs) def DoGetVirtualSize(*args, **kwargs): """DoGetVirtualSize(self) -> Size""" return _controls_.PyControl_DoGetVirtualSize(*args, **kwargs) def DoGetBestSize(*args, **kwargs): """DoGetBestSize(self) -> Size""" return _controls_.PyControl_DoGetBestSize(*args, **kwargs) def GetDefaultAttributes(*args, **kwargs): """GetDefaultAttributes(self) -> VisualAttributes""" return _controls_.PyControl_GetDefaultAttributes(*args, **kwargs) def OnInternalIdle(*args, **kwargs): """OnInternalIdle(self)""" return _controls_.PyControl_OnInternalIdle(*args, **kwargs) def base_DoMoveWindow(*args, **kw): return PyControl.DoMoveWindow(*args, **kw) base_DoMoveWindow = wx.deprecated(base_DoMoveWindow, "Please use PyControl.DoMoveWindow instead.") def base_DoSetSize(*args, **kw): return PyControl.DoSetSize(*args, **kw) base_DoSetSize = wx.deprecated(base_DoSetSize, "Please use PyControl.DoSetSize instead.") def base_DoSetClientSize(*args, **kw): return PyControl.DoSetClientSize(*args, **kw) base_DoSetClientSize = wx.deprecated(base_DoSetClientSize, "Please use PyControl.DoSetClientSize instead.") def base_DoSetVirtualSize(*args, **kw): return PyControl.DoSetVirtualSize(*args, **kw) base_DoSetVirtualSize = wx.deprecated(base_DoSetVirtualSize, "Please use PyControl.DoSetVirtualSize instead.") def base_DoGetSize(*args, **kw): return PyControl.DoGetSize(*args, **kw) base_DoGetSize = wx.deprecated(base_DoGetSize, "Please use PyControl.DoGetSize instead.") def base_DoGetClientSize(*args, **kw): return PyControl.DoGetClientSize(*args, **kw) base_DoGetClientSize = wx.deprecated(base_DoGetClientSize, "Please use PyControl.DoGetClientSize instead.") def base_DoGetPosition(*args, **kw): return PyControl.DoGetPosition(*args, **kw) base_DoGetPosition = wx.deprecated(base_DoGetPosition, "Please use PyControl.DoGetPosition instead.") def base_DoGetVirtualSize(*args, **kw): return PyControl.DoGetVirtualSize(*args, **kw) base_DoGetVirtualSize = wx.deprecated(base_DoGetVirtualSize, "Please use PyControl.DoGetVirtualSize instead.") def base_DoGetBestSize(*args, **kw): return PyControl.DoGetBestSize(*args, **kw) base_DoGetBestSize = wx.deprecated(base_DoGetBestSize, "Please use PyControl.DoGetBestSize instead.") def base_InitDialog(*args, **kw): return PyControl.InitDialog(*args, **kw) base_InitDialog = wx.deprecated(base_InitDialog, "Please use PyControl.InitDialog instead.") def base_TransferDataToWindow(*args, **kw): return PyControl.TransferDataToWindow(*args, **kw) base_TransferDataToWindow = wx.deprecated(base_TransferDataToWindow, "Please use PyControl.TransferDataToWindow instead.") def base_TransferDataFromWindow(*args, **kw): return PyControl.TransferDataFromWindow(*args, **kw) base_TransferDataFromWindow = wx.deprecated(base_TransferDataFromWindow, "Please use PyControl.TransferDataFromWindow instead.") def base_Validate(*args, **kw): return PyControl.Validate(*args, **kw) base_Validate = wx.deprecated(base_Validate, "Please use PyControl.Validate instead.") def base_AcceptsFocus(*args, **kw): return PyControl.AcceptsFocus(*args, **kw) base_AcceptsFocus = wx.deprecated(base_AcceptsFocus, "Please use PyControl.AcceptsFocus instead.") def base_AcceptsFocusFromKeyboard(*args, **kw): return PyControl.AcceptsFocusFromKeyboard(*args, **kw) base_AcceptsFocusFromKeyboard = wx.deprecated(base_AcceptsFocusFromKeyboard, "Please use PyControl.AcceptsFocusFromKeyboard instead.") def base_GetMaxSize(*args, **kw): return PyControl.GetMaxSize(*args, **kw) base_GetMaxSize = wx.deprecated(base_GetMaxSize, "Please use PyControl.GetMaxSize instead.") def base_Enable(*args, **kw): return PyControl.Enable(*args, **kw) base_Enable = wx.deprecated(base_Enable, "Please use PyControl.Enable instead.") def base_AddChild(*args, **kw): return PyControl.AddChild(*args, **kw) base_AddChild = wx.deprecated(base_AddChild, "Please use PyControl.AddChild instead.") def base_RemoveChild(*args, **kw): return PyControl.RemoveChild(*args, **kw) base_RemoveChild = wx.deprecated(base_RemoveChild, "Please use PyControl.RemoveChild instead.") def base_ShouldInheritColours(*args, **kw): return PyControl.ShouldInheritColours(*args, **kw) base_ShouldInheritColours = wx.deprecated(base_ShouldInheritColours, "Please use PyControl.ShouldInheritColours instead.") def base_GetDefaultAttributes(*args, **kw): return PyControl.GetDefaultAttributes(*args, **kw) base_GetDefaultAttributes = wx.deprecated(base_GetDefaultAttributes, "Please use PyControl.GetDefaultAttributes instead.") def base_OnInternalIdle(*args, **kw): return PyControl.OnInternalIdle(*args, **kw) base_OnInternalIdle = wx.deprecated(base_OnInternalIdle, "Please use PyControl.OnInternalIdle instead.") _controls_.PyControl_swigregister(PyControl) def PrePyControl(*args, **kwargs): """PrePyControl() -> PyControl""" val = _controls_.new_PrePyControl(*args, **kwargs) return val #--------------------------------------------------------------------------- wxEVT_HELP = _controls_.wxEVT_HELP wxEVT_DETAILED_HELP = _controls_.wxEVT_DETAILED_HELP EVT_HELP = wx.PyEventBinder( wxEVT_HELP, 1) EVT_HELP_RANGE = wx.PyEventBinder( wxEVT_HELP, 2) EVT_DETAILED_HELP = wx.PyEventBinder( wxEVT_DETAILED_HELP, 1) EVT_DETAILED_HELP_RANGE = wx.PyEventBinder( wxEVT_DETAILED_HELP, 2) class HelpEvent(_core.CommandEvent): """ A help event is sent when the user has requested context-sensitive help. This can either be caused by the application requesting context-sensitive help mode via wx.ContextHelp, or (on MS Windows) by the system generating a WM_HELP message when the user pressed F1 or clicked on the query button in a dialog caption. A help event is sent to the window that the user clicked on, and is propagated up the window hierarchy until the event is processed or there are no more event handlers. The application should call event.GetId to check the identity of the clicked-on window, and then either show some suitable help or call event.Skip if the identifier is unrecognised. Calling Skip is important because it allows wxWindows to generate further events for ancestors of the clicked-on window. Otherwise it would be impossible to show help for container windows, since processing would stop after the first window found. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr Origin_Unknown = _controls_.HelpEvent_Origin_Unknown Origin_Keyboard = _controls_.HelpEvent_Origin_Keyboard Origin_HelpButton = _controls_.HelpEvent_Origin_HelpButton def __init__(self, *args, **kwargs): """ __init__(self, EventType type=wxEVT_NULL, int winid=0, Point pt=DefaultPosition, int origin=Origin_Unknown) -> HelpEvent """ _controls_.HelpEvent_swiginit(self,_controls_.new_HelpEvent(*args, **kwargs)) def GetPosition(*args, **kwargs): """ GetPosition(self) -> Point Returns the left-click position of the mouse, in screen coordinates. This allows the application to position the help appropriately. """ return _controls_.HelpEvent_GetPosition(*args, **kwargs) def SetPosition(*args, **kwargs): """ SetPosition(self, Point pos) Sets the left-click position of the mouse, in screen coordinates. """ return _controls_.HelpEvent_SetPosition(*args, **kwargs) def GetLink(*args, **kwargs): """ GetLink(self) -> String Get an optional link to further help """ return _controls_.HelpEvent_GetLink(*args, **kwargs) def SetLink(*args, **kwargs): """ SetLink(self, String link) Set an optional link to further help """ return _controls_.HelpEvent_SetLink(*args, **kwargs) def GetTarget(*args, **kwargs): """ GetTarget(self) -> String Get an optional target to display help in. E.g. a window specification """ return _controls_.HelpEvent_GetTarget(*args, **kwargs) def SetTarget(*args, **kwargs): """ SetTarget(self, String target) Set an optional target to display help in. E.g. a window specification """ return _controls_.HelpEvent_SetTarget(*args, **kwargs) def GetOrigin(*args, **kwargs): """ GetOrigin(self) -> int Optiononal indication of the source of the event. """ return _controls_.HelpEvent_GetOrigin(*args, **kwargs) def SetOrigin(*args, **kwargs): """SetOrigin(self, int origin)""" return _controls_.HelpEvent_SetOrigin(*args, **kwargs) Link = property(GetLink,SetLink,doc="See `GetLink` and `SetLink`") Origin = property(GetOrigin,SetOrigin,doc="See `GetOrigin` and `SetOrigin`") Position = property(GetPosition,SetPosition,doc="See `GetPosition` and `SetPosition`") Target = property(GetTarget,SetTarget,doc="See `GetTarget` and `SetTarget`") _controls_.HelpEvent_swigregister(HelpEvent) class ContextHelp(_core.Object): """ This class changes the cursor to a query and puts the application into a 'context-sensitive help mode'. When the user left-clicks on a window within the specified window, a ``EVT_HELP`` event is sent to that control, and the application may respond to it by popping up some help. There are a couple of ways to invoke this behaviour implicitly: * Use the wx.WS_EX_CONTEXTHELP extended style for a dialog or frame (Windows only). This will put a question mark in the titlebar, and Windows will put the application into context-sensitive help mode automatically, with further programming. * Create a `wx.ContextHelpButton`, whose predefined behaviour is to create a context help object. Normally you will write your application so that this button is only added to a dialog for non-Windows platforms (use ``wx.WS_EX_CONTEXTHELP`` on Windows). :see: `wx.ContextHelpButton` """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window window=None, bool doNow=True) -> ContextHelp Constructs a context help object, calling BeginContextHelp if doNow is true (the default). If window is None, the top window is used. """ _controls_.ContextHelp_swiginit(self,_controls_.new_ContextHelp(*args, **kwargs)) __swig_destroy__ = _controls_.delete_ContextHelp __del__ = lambda self : None; def BeginContextHelp(*args, **kwargs): """ BeginContextHelp(self, Window window=None) -> bool Puts the application into context-sensitive help mode. window is the window which will be used to catch events; if NULL, the top window will be used. Returns true if the application was successfully put into context-sensitive help mode. This function only returns when the event loop has finished. """ return _controls_.ContextHelp_BeginContextHelp(*args, **kwargs) def EndContextHelp(*args, **kwargs): """ EndContextHelp(self) -> bool Ends context-sensitive help mode. Not normally called by the application. """ return _controls_.ContextHelp_EndContextHelp(*args, **kwargs) _controls_.ContextHelp_swigregister(ContextHelp) class ContextHelpButton(BitmapButton): """ Instances of this class may be used to add a question mark button that when pressed, puts the application into context-help mode. It does this by creating a wx.ContextHelp object which itself generates a ``EVT_HELP`` event when the user clicks on a window. On Windows, you may add a question-mark icon to a dialog by use of the ``wx.DIALOG_EX_CONTEXTHELP`` extra style, but on other platforms you will have to add a button explicitly, usually next to OK, Cancel or similar buttons. :see: `wx.ContextHelp`, `wx.ContextHelpButton` """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=ID_CONTEXT_HELP, Point pos=DefaultPosition, Size size=DefaultSize, long style=BU_AUTODRAW) -> ContextHelpButton Constructor, creating and showing a context help button. """ _controls_.ContextHelpButton_swiginit(self,_controls_.new_ContextHelpButton(*args, **kwargs)) self._setOORInfo(self) _controls_.ContextHelpButton_swigregister(ContextHelpButton) class HelpProvider(object): """ wx.HelpProvider is an abstract class used by a program implementing context-sensitive help to show the help text for the given window. The current help provider must be explicitly set by the application using wx.HelpProvider.Set(). """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self): raise AttributeError, "No constructor defined" __repr__ = _swig_repr __swig_destroy__ = _controls_.delete_HelpProvider __del__ = lambda self : None; def Set(*args, **kwargs): """ Set(HelpProvider helpProvider) -> HelpProvider Sset the current, application-wide help provider. Returns the previous one. Unlike some other classes, the help provider is not created on demand. This must be explicitly done by the application. """ return _controls_.HelpProvider_Set(*args, **kwargs) Set = staticmethod(Set) def Get(*args, **kwargs): """ Get() -> HelpProvider Return the current application-wide help provider. """ return _controls_.HelpProvider_Get(*args, **kwargs) Get = staticmethod(Get) def GetHelp(*args, **kwargs): """ GetHelp(self, Window window) -> String Gets the help string for this window. Its interpretation is dependent on the help provider except that empty string always means that no help is associated with the window. """ return _controls_.HelpProvider_GetHelp(*args, **kwargs) def ShowHelp(*args, **kwargs): """ ShowHelp(self, Window window) -> bool Shows help for the given window. Uses GetHelp internally if applicable. Returns True if it was done, or False if no help was available for this window. """ return _controls_.HelpProvider_ShowHelp(*args, **kwargs) def ShowHelpAtPoint(*args, **kwargs): """ ShowHelpAtPoint(self, wxWindowBase window, Point pt, int origin) -> bool Show help for the given window (uses window.GetHelpAtPoint() internally if applicable), return true if it was done or false if no help available for this window. """ return _controls_.HelpProvider_ShowHelpAtPoint(*args, **kwargs) def AddHelp(*args, **kwargs): """ AddHelp(self, Window window, String text) Associates the text with the given window. """ return _controls_.HelpProvider_AddHelp(*args, **kwargs) def AddHelpById(*args, **kwargs): """ AddHelpById(self, int id, String text) This version associates the given text with all windows with this id. May be used to set the same help string for all Cancel buttons in the application, for example. """ return _controls_.HelpProvider_AddHelpById(*args, **kwargs) def RemoveHelp(*args, **kwargs): """ RemoveHelp(self, Window window) Removes the association between the window pointer and the help text. This is called by the wx.Window destructor. Without this, the table of help strings will fill up and when window pointers are reused, the wrong help string will be found. """ return _controls_.HelpProvider_RemoveHelp(*args, **kwargs) def Destroy(*args, **kwargs): """Destroy(self)""" args[0].this.own(False) return _controls_.HelpProvider_Destroy(*args, **kwargs) _controls_.HelpProvider_swigregister(HelpProvider) def HelpProvider_Set(*args, **kwargs): """ HelpProvider_Set(HelpProvider helpProvider) -> HelpProvider Sset the current, application-wide help provider. Returns the previous one. Unlike some other classes, the help provider is not created on demand. This must be explicitly done by the application. """ return _controls_.HelpProvider_Set(*args, **kwargs) def HelpProvider_Get(*args): """ HelpProvider_Get() -> HelpProvider Return the current application-wide help provider. """ return _controls_.HelpProvider_Get(*args) class SimpleHelpProvider(HelpProvider): """ wx.SimpleHelpProvider is an implementation of `wx.HelpProvider` which supports only plain text help strings, and shows the string associated with the control (if any) in a tooltip. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self) -> SimpleHelpProvider wx.SimpleHelpProvider is an implementation of `wx.HelpProvider` which supports only plain text help strings, and shows the string associated with the control (if any) in a tooltip. """ _controls_.SimpleHelpProvider_swiginit(self,_controls_.new_SimpleHelpProvider(*args, **kwargs)) _controls_.SimpleHelpProvider_swigregister(SimpleHelpProvider) #--------------------------------------------------------------------------- class DragImage(_core.Object): """Proxy of C++ DragImage class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self, Bitmap image, Cursor cursor=wxNullCursor) -> DragImage""" _controls_.DragImage_swiginit(self,_controls_.new_DragImage(*args, **kwargs)) __swig_destroy__ = _controls_.delete_DragImage __del__ = lambda self : None; def SetBackingBitmap(*args, **kwargs): """SetBackingBitmap(self, Bitmap bitmap)""" return _controls_.DragImage_SetBackingBitmap(*args, **kwargs) def BeginDrag(*args, **kwargs): """ BeginDrag(self, Point hotspot, Window window, bool fullScreen=False, Rect rect=None) -> bool """ return _controls_.DragImage_BeginDrag(*args, **kwargs) def BeginDragBounded(*args, **kwargs): """BeginDragBounded(self, Point hotspot, Window window, Window boundingWindow) -> bool""" return _controls_.DragImage_BeginDragBounded(*args, **kwargs) def EndDrag(*args, **kwargs): """EndDrag(self) -> bool""" return _controls_.DragImage_EndDrag(*args, **kwargs) def Move(*args, **kwargs): """Move(self, Point pt) -> bool""" return _controls_.DragImage_Move(*args, **kwargs) def Show(*args, **kwargs): """Show(self) -> bool""" return _controls_.DragImage_Show(*args, **kwargs) def Hide(*args, **kwargs): """Hide(self) -> bool""" return _controls_.DragImage_Hide(*args, **kwargs) def GetImageRect(*args, **kwargs): """GetImageRect(self, Point pos) -> Rect""" return _controls_.DragImage_GetImageRect(*args, **kwargs) def DoDrawImage(*args, **kwargs): """DoDrawImage(self, DC dc, Point pos) -> bool""" return _controls_.DragImage_DoDrawImage(*args, **kwargs) def UpdateBackingFromWindow(*args, **kwargs): """UpdateBackingFromWindow(self, DC windowDC, MemoryDC destDC, Rect sourceRect, Rect destRect) -> bool""" return _controls_.DragImage_UpdateBackingFromWindow(*args, **kwargs) def RedrawImage(*args, **kwargs): """RedrawImage(self, Point oldPos, Point newPos, bool eraseOld, bool drawNew) -> bool""" return _controls_.DragImage_RedrawImage(*args, **kwargs) ImageRect = property(GetImageRect,doc="See `GetImageRect`") _controls_.DragImage_swigregister(DragImage) def DragIcon(*args, **kwargs): """DragIcon(Icon image, Cursor cursor=wxNullCursor) -> DragImage""" val = _controls_.new_DragIcon(*args, **kwargs) return val def DragString(*args, **kwargs): """DragString(String str, Cursor cursor=wxNullCursor) -> DragImage""" val = _controls_.new_DragString(*args, **kwargs) return val def DragTreeItem(*args, **kwargs): """DragTreeItem(TreeCtrl treeCtrl, TreeItemId id) -> DragImage""" val = _controls_.new_DragTreeItem(*args, **kwargs) return val def DragListItem(*args, **kwargs): """DragListItem(ListCtrl listCtrl, long id) -> DragImage""" val = _controls_.new_DragListItem(*args, **kwargs) return val #--------------------------------------------------------------------------- DP_DEFAULT = _controls_.DP_DEFAULT DP_SPIN = _controls_.DP_SPIN DP_DROPDOWN = _controls_.DP_DROPDOWN DP_SHOWCENTURY = _controls_.DP_SHOWCENTURY DP_ALLOWNONE = _controls_.DP_ALLOWNONE class DatePickerCtrlBase(_core.Control): """Proxy of C++ DatePickerCtrlBase class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self): raise AttributeError, "No constructor defined" __repr__ = _swig_repr def SetValue(*args, **kwargs): """ SetValue(self, DateTime dt) Changes the current value of the control. The date should be valid and included in the currently selected range, if any. Calling this method does not result in a date change event. """ return _controls_.DatePickerCtrlBase_SetValue(*args, **kwargs) def GetValue(*args, **kwargs): """ GetValue(self) -> DateTime Returns the currently selected date. If there is no selection or the selection is outside of the current range, an invalid `wx.DateTime` object is returned. """ return _controls_.DatePickerCtrlBase_GetValue(*args, **kwargs) def SetRange(*args, **kwargs): """ SetRange(self, DateTime dt1, DateTime dt2) Sets the valid range for the date selection. If dt1 is valid, it becomes the earliest date (inclusive) accepted by the control. If dt2 is valid, it becomes the latest possible date. If the current value of the control is outside of the newly set range bounds, the behaviour is undefined. """ return _controls_.DatePickerCtrlBase_SetRange(*args, **kwargs) def GetLowerLimit(*args, **kwargs): """ GetLowerLimit(self) -> DateTime Get the lower limit of the valid range for the date selection, if any. If there is no range or there is no lower limit, then the `wx.DateTime` value returned will be invalid. """ return _controls_.DatePickerCtrlBase_GetLowerLimit(*args, **kwargs) def GetUpperLimit(*args, **kwargs): """ GetUpperLimit(self) -> DateTime Get the upper limit of the valid range for the date selection, if any. If there is no range or there is no upper limit, then the `wx.DateTime` value returned will be invalid. """ return _controls_.DatePickerCtrlBase_GetUpperLimit(*args, **kwargs) LowerLimit = property(GetLowerLimit,doc="See `GetLowerLimit`") UpperLimit = property(GetUpperLimit,doc="See `GetUpperLimit`") Value = property(GetValue,SetValue,doc="See `GetValue` and `SetValue`") _controls_.DatePickerCtrlBase_swigregister(DatePickerCtrlBase) DatePickerCtrlNameStr = cvar.DatePickerCtrlNameStr class DatePickerCtrl(DatePickerCtrlBase): """ This control allows the user to select a date. Unlike `wx.calendar.CalendarCtrl`, which is a relatively big control, `wx.DatePickerCtrl` is implemented as a small window showing the currently selected date. The control can be edited using the keyboard, and can also display a popup window for more user-friendly date selection, depending on the styles used and the platform. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxDP_DEFAULT|wxDP_SHOWCENTURY, Validator validator=DefaultValidator, String name=DatePickerCtrlNameStr) -> DatePickerCtrl Create a new DatePickerCtrl. """ _controls_.DatePickerCtrl_swiginit(self,_controls_.new_DatePickerCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxDP_DEFAULT|wxDP_SHOWCENTURY, Validator validator=DefaultValidator, String name=DatePickerCtrlNameStr) -> bool Create the GUI parts of the DatePickerCtrl, for use in 2-phase creation. """ return _controls_.DatePickerCtrl_Create(*args, **kwargs) _controls_.DatePickerCtrl_swigregister(DatePickerCtrl) def PreDatePickerCtrl(*args, **kwargs): """ PreDatePickerCtrl() -> DatePickerCtrl Precreate a DatePickerCtrl for use in 2-phase creation. """ val = _controls_.new_PreDatePickerCtrl(*args, **kwargs) return val class GenericDatePickerCtrl(DatePickerCtrlBase): """Proxy of C++ GenericDatePickerCtrl class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxDP_DEFAULT|wxDP_SHOWCENTURY, Validator validator=DefaultValidator, String name=DatePickerCtrlNameStr) -> GenericDatePickerCtrl Create a new GenericDatePickerCtrl. """ _controls_.GenericDatePickerCtrl_swiginit(self,_controls_.new_GenericDatePickerCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, DateTime dt=wxDefaultDateTime, Point pos=DefaultPosition, Size size=DefaultSize, long style=wxDP_DEFAULT|wxDP_SHOWCENTURY, Validator validator=DefaultValidator, String name=DatePickerCtrlNameStr) -> bool Create the GUI parts of the GenericDatePickerCtrl, for use in 2-phase creation. """ return _controls_.GenericDatePickerCtrl_Create(*args, **kwargs) _controls_.GenericDatePickerCtrl_swigregister(GenericDatePickerCtrl) def PreGenericDatePickerCtrl(*args, **kwargs): """ PreGenericDatePickerCtrl() -> GenericDatePickerCtrl Precreate a GenericDatePickerCtrl for use in 2-phase creation. """ val = _controls_.new_PreGenericDatePickerCtrl(*args, **kwargs) return val HL_CONTEXTMENU = _controls_.HL_CONTEXTMENU HL_ALIGN_LEFT = _controls_.HL_ALIGN_LEFT HL_ALIGN_RIGHT = _controls_.HL_ALIGN_RIGHT HL_ALIGN_CENTRE = _controls_.HL_ALIGN_CENTRE HL_DEFAULT_STYLE = _controls_.HL_DEFAULT_STYLE #--------------------------------------------------------------------------- class HyperlinkCtrl(_core.Control): """ A static text control that emulates a hyperlink. The link is displayed in an appropriate text style, derived from the control's normal font. When the mouse rolls over the link, the cursor changes to a hand and the link's color changes to the active color. Clicking on the link does not launch a web browser; instead, a wx.HyperlinkEvent is fired. Use the wx.EVT_HYPERLINK to catch link events. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String label=wxEmptyString, String url=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=HL_DEFAULT_STYLE, String name=HyperlinkCtrlNameStr) -> HyperlinkCtrl A static text control that emulates a hyperlink. The link is displayed in an appropriate text style, derived from the control's normal font. When the mouse rolls over the link, the cursor changes to a hand and the link's color changes to the active color. Clicking on the link does not launch a web browser; instead, a wx.HyperlinkEvent is fired. Use the wx.EVT_HYPERLINK to catch link events. """ _controls_.HyperlinkCtrl_swiginit(self,_controls_.new_HyperlinkCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String label=wxEmptyString, String url=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=HL_DEFAULT_STYLE, String name=HyperlinkCtrlNameStr) -> bool """ return _controls_.HyperlinkCtrl_Create(*args, **kwargs) def GetHoverColour(*args, **kwargs): """GetHoverColour(self) -> Colour""" return _controls_.HyperlinkCtrl_GetHoverColour(*args, **kwargs) def SetHoverColour(*args, **kwargs): """SetHoverColour(self, Colour colour)""" return _controls_.HyperlinkCtrl_SetHoverColour(*args, **kwargs) def GetNormalColour(*args, **kwargs): """GetNormalColour(self) -> Colour""" return _controls_.HyperlinkCtrl_GetNormalColour(*args, **kwargs) def SetNormalColour(*args, **kwargs): """SetNormalColour(self, Colour colour)""" return _controls_.HyperlinkCtrl_SetNormalColour(*args, **kwargs) def GetVisitedColour(*args, **kwargs): """GetVisitedColour(self) -> Colour""" return _controls_.HyperlinkCtrl_GetVisitedColour(*args, **kwargs) def SetVisitedColour(*args, **kwargs): """SetVisitedColour(self, Colour colour)""" return _controls_.HyperlinkCtrl_SetVisitedColour(*args, **kwargs) def GetURL(*args, **kwargs): """GetURL(self) -> String""" return _controls_.HyperlinkCtrl_GetURL(*args, **kwargs) def SetURL(*args, **kwargs): """SetURL(self, String url)""" return _controls_.HyperlinkCtrl_SetURL(*args, **kwargs) def SetVisited(*args, **kwargs): """SetVisited(self, bool visited=True)""" return _controls_.HyperlinkCtrl_SetVisited(*args, **kwargs) def GetVisited(*args, **kwargs): """GetVisited(self) -> bool""" return _controls_.HyperlinkCtrl_GetVisited(*args, **kwargs) HoverColour = property(GetHoverColour,SetHoverColour,doc="See `GetHoverColour` and `SetHoverColour`") NormalColour = property(GetNormalColour,SetNormalColour,doc="See `GetNormalColour` and `SetNormalColour`") URL = property(GetURL,SetURL,doc="See `GetURL` and `SetURL`") Visited = property(GetVisited,SetVisited,doc="See `GetVisited` and `SetVisited`") VisitedColour = property(GetVisitedColour,SetVisitedColour,doc="See `GetVisitedColour` and `SetVisitedColour`") _controls_.HyperlinkCtrl_swigregister(HyperlinkCtrl) HyperlinkCtrlNameStr = cvar.HyperlinkCtrlNameStr def PreHyperlinkCtrl(*args, **kwargs): """ PreHyperlinkCtrl() -> HyperlinkCtrl A static text control that emulates a hyperlink. The link is displayed in an appropriate text style, derived from the control's normal font. When the mouse rolls over the link, the cursor changes to a hand and the link's color changes to the active color. Clicking on the link does not launch a web browser; instead, a wx.HyperlinkEvent is fired. Use the wx.EVT_HYPERLINK to catch link events. """ val = _controls_.new_PreHyperlinkCtrl(*args, **kwargs) return val wxEVT_COMMAND_HYPERLINK = _controls_.wxEVT_COMMAND_HYPERLINK class HyperlinkEvent(_core.CommandEvent): """Proxy of C++ HyperlinkEvent class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self, Object generator, int id, String url) -> HyperlinkEvent""" _controls_.HyperlinkEvent_swiginit(self,_controls_.new_HyperlinkEvent(*args, **kwargs)) def GetURL(*args, **kwargs): """GetURL(self) -> String""" return _controls_.HyperlinkEvent_GetURL(*args, **kwargs) def SetURL(*args, **kwargs): """SetURL(self, String url)""" return _controls_.HyperlinkEvent_SetURL(*args, **kwargs) URL = property(GetURL,SetURL,doc="See `GetURL` and `SetURL`") _controls_.HyperlinkEvent_swigregister(HyperlinkEvent) EVT_HYPERLINK = wx.PyEventBinder( wxEVT_COMMAND_HYPERLINK, 1 ) #--------------------------------------------------------------------------- PB_USE_TEXTCTRL = _controls_.PB_USE_TEXTCTRL class PickerBase(_core.Control): """ Base abstract class for all pickers which support an auxiliary text control. This class handles all positioning and sizing of the text control like a horizontal `wx.BoxSizer` would do, with the text control on the left of the picker button and the proportion of the picker fixed to value 1. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self): raise AttributeError, "No constructor defined" __repr__ = _swig_repr def CreateBase(*args, **kwargs): """ CreateBase(self, Window parent, int id, String text=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=wxButtonNameStr) -> bool """ return _controls_.PickerBase_CreateBase(*args, **kwargs) def SetInternalMargin(*args, **kwargs): """ SetInternalMargin(self, int newmargin) Sets the margin (in pixels) between the picker and the text control. """ return _controls_.PickerBase_SetInternalMargin(*args, **kwargs) def GetInternalMargin(*args, **kwargs): """ GetInternalMargin(self) -> int Returns the margin (in pixels) between the picker and the text control. """ return _controls_.PickerBase_GetInternalMargin(*args, **kwargs) def SetTextCtrlProportion(*args, **kwargs): """ SetTextCtrlProportion(self, int prop) Sets the proportion between the text control and the picker button. This is used to set relative sizes of the text contorl and the picker. The value passed to this function must be >= 1. """ return _controls_.PickerBase_SetTextCtrlProportion(*args, **kwargs) def GetTextCtrlProportion(*args, **kwargs): """ GetTextCtrlProportion(self) -> int Returns the proportion between the text control and the picker. """ return _controls_.PickerBase_GetTextCtrlProportion(*args, **kwargs) def SetPickerCtrlProportion(*args, **kwargs): """ SetPickerCtrlProportion(self, int prop) Sets the proportion value of the picker. """ return _controls_.PickerBase_SetPickerCtrlProportion(*args, **kwargs) def GetPickerCtrlProportion(*args, **kwargs): """ GetPickerCtrlProportion(self) -> int Gets the proportion value of the picker. """ return _controls_.PickerBase_GetPickerCtrlProportion(*args, **kwargs) def IsTextCtrlGrowable(*args, **kwargs): """IsTextCtrlGrowable(self) -> bool""" return _controls_.PickerBase_IsTextCtrlGrowable(*args, **kwargs) def SetTextCtrlGrowable(*args, **kwargs): """SetTextCtrlGrowable(self, bool grow=True)""" return _controls_.PickerBase_SetTextCtrlGrowable(*args, **kwargs) def IsPickerCtrlGrowable(*args, **kwargs): """IsPickerCtrlGrowable(self) -> bool""" return _controls_.PickerBase_IsPickerCtrlGrowable(*args, **kwargs) def SetPickerCtrlGrowable(*args, **kwargs): """SetPickerCtrlGrowable(self, bool grow=True)""" return _controls_.PickerBase_SetPickerCtrlGrowable(*args, **kwargs) def HasTextCtrl(*args, **kwargs): """ HasTextCtrl(self) -> bool Returns true if this class has a valid text control (i.e. if the wx.PB_USE_TEXTCTRL style was given when creating this control). """ return _controls_.PickerBase_HasTextCtrl(*args, **kwargs) def GetTextCtrl(*args, **kwargs): """ GetTextCtrl(self) -> TextCtrl Returns a pointer to the text control handled by this class or None if the wx.PB_USE_TEXTCTRL style was not specified when this control was created. Very important: the contents of the text control could be containing an invalid representation of the entity which can be chosen through the picker (e.g. the user entered an invalid colour syntax because of a typo). Thus you should never parse the content of the textctrl to get the user's input; rather use the derived-class getter (e.g. `wx.ColourPickerCtrl.GetColour`, `wx.FilePickerCtrl.GetPath`, etc). """ return _controls_.PickerBase_GetTextCtrl(*args, **kwargs) def GetPickerCtrl(*args, **kwargs): """GetPickerCtrl(self) -> Control""" return _controls_.PickerBase_GetPickerCtrl(*args, **kwargs) InternalMargin = property(GetInternalMargin,SetInternalMargin,doc="See `GetInternalMargin` and `SetInternalMargin`") PickerCtrl = property(GetPickerCtrl,doc="See `GetPickerCtrl`") PickerCtrlProportion = property(GetPickerCtrlProportion,SetPickerCtrlProportion,doc="See `GetPickerCtrlProportion` and `SetPickerCtrlProportion`") TextCtrl = property(GetTextCtrl,doc="See `GetTextCtrl`") TextCtrlProportion = property(GetTextCtrlProportion,SetTextCtrlProportion,doc="See `GetTextCtrlProportion` and `SetTextCtrlProportion`") TextCtrlGrowable = property(IsTextCtrlGrowable,SetTextCtrlGrowable,doc="See `IsTextCtrlGrowable` and `SetTextCtrlGrowable`") PickerCtrlGrowable = property(IsPickerCtrlGrowable,SetPickerCtrlGrowable,doc="See `IsPickerCtrlGrowable` and `SetPickerCtrlGrowable`") _controls_.PickerBase_swigregister(PickerBase) class PyPickerBase(PickerBase): """Proxy of C++ PyPickerBase class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String text=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=wxButtonNameStr) -> PyPickerBase """ _controls_.PyPickerBase_swiginit(self,_controls_.new_PyPickerBase(*args, **kwargs)) self._setOORInfo(self);PyPickerBase._setCallbackInfo(self, self, PyPickerBase) def _setCallbackInfo(*args, **kwargs): """_setCallbackInfo(self, PyObject self, PyObject _class)""" return _controls_.PyPickerBase__setCallbackInfo(*args, **kwargs) def UpdatePickerFromTextCtrl(*args, **kwargs): """UpdatePickerFromTextCtrl(self)""" return _controls_.PyPickerBase_UpdatePickerFromTextCtrl(*args, **kwargs) def UpdateTextCtrlFromPicker(*args, **kwargs): """UpdateTextCtrlFromPicker(self)""" return _controls_.PyPickerBase_UpdateTextCtrlFromPicker(*args, **kwargs) def GetTextCtrlStyle(*args, **kwargs): """GetTextCtrlStyle(self, long style) -> long""" return _controls_.PyPickerBase_GetTextCtrlStyle(*args, **kwargs) def GetPickerStyle(*args, **kwargs): """GetPickerStyle(self, long style) -> long""" return _controls_.PyPickerBase_GetPickerStyle(*args, **kwargs) def SetTextCtrl(*args, **kwargs): """SetTextCtrl(self, TextCtrl text)""" return _controls_.PyPickerBase_SetTextCtrl(*args, **kwargs) def SetPickerCtrl(*args, **kwargs): """SetPickerCtrl(self, Control picker)""" return _controls_.PyPickerBase_SetPickerCtrl(*args, **kwargs) def PostCreation(*args, **kwargs): """PostCreation(self)""" return _controls_.PyPickerBase_PostCreation(*args, **kwargs) _controls_.PyPickerBase_swigregister(PyPickerBase) def PrePyPickerBase(*args, **kwargs): """PrePyPickerBase() -> PyPickerBase""" val = _controls_.new_PrePyPickerBase(*args, **kwargs) return val #--------------------------------------------------------------------------- CLRP_SHOW_LABEL = _controls_.CLRP_SHOW_LABEL CLRP_USE_TEXTCTRL = _controls_.CLRP_USE_TEXTCTRL CLRP_DEFAULT_STYLE = _controls_.CLRP_DEFAULT_STYLE class ColourPickerCtrl(PickerBase): """ This control allows the user to select a colour. The implementation varies by platform but is usually a button which brings up a `wx.ColourDialog` when clicked. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Colour col=*wxBLACK, Point pos=DefaultPosition, Size size=DefaultSize, long style=CLRP_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=ColourPickerCtrlNameStr) -> ColourPickerCtrl This control allows the user to select a colour. The implementation varies by platform but is usually a button which brings up a `wx.ColourDialog` when clicked. """ _controls_.ColourPickerCtrl_swiginit(self,_controls_.new_ColourPickerCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id, Colour col=*wxBLACK, Point pos=DefaultPosition, Size size=DefaultSize, long style=CLRP_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=ColourPickerCtrlNameStr) -> bool """ return _controls_.ColourPickerCtrl_Create(*args, **kwargs) def GetColour(*args, **kwargs): """ GetColour(self) -> Colour Returns the currently selected colour. """ return _controls_.ColourPickerCtrl_GetColour(*args, **kwargs) def SetColour(*args, **kwargs): """ SetColour(self, Colour col) Set the displayed colour. """ return _controls_.ColourPickerCtrl_SetColour(*args, **kwargs) Colour = property(GetColour,SetColour,doc="See `GetColour` and `SetColour`") _controls_.ColourPickerCtrl_swigregister(ColourPickerCtrl) ColourPickerCtrlNameStr = cvar.ColourPickerCtrlNameStr def PreColourPickerCtrl(*args, **kwargs): """ PreColourPickerCtrl() -> ColourPickerCtrl This control allows the user to select a colour. The implementation varies by platform but is usually a button which brings up a `wx.ColourDialog` when clicked. """ val = _controls_.new_PreColourPickerCtrl(*args, **kwargs) return val wxEVT_COMMAND_COLOURPICKER_CHANGED = _controls_.wxEVT_COMMAND_COLOURPICKER_CHANGED EVT_COLOURPICKER_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_COLOURPICKER_CHANGED, 1 ) class ColourPickerEvent(_core.CommandEvent): """Proxy of C++ ColourPickerEvent class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self, Object generator, int id, Colour col) -> ColourPickerEvent""" _controls_.ColourPickerEvent_swiginit(self,_controls_.new_ColourPickerEvent(*args, **kwargs)) def GetColour(*args, **kwargs): """GetColour(self) -> Colour""" return _controls_.ColourPickerEvent_GetColour(*args, **kwargs) def SetColour(*args, **kwargs): """SetColour(self, Colour c)""" return _controls_.ColourPickerEvent_SetColour(*args, **kwargs) Colour = property(GetColour,SetColour,doc="See `GetColour` and `SetColour`") _controls_.ColourPickerEvent_swigregister(ColourPickerEvent) #--------------------------------------------------------------------------- FLP_OPEN = _controls_.FLP_OPEN FLP_SAVE = _controls_.FLP_SAVE FLP_OVERWRITE_PROMPT = _controls_.FLP_OVERWRITE_PROMPT FLP_FILE_MUST_EXIST = _controls_.FLP_FILE_MUST_EXIST FLP_CHANGE_DIR = _controls_.FLP_CHANGE_DIR FLP_SMALL = _controls_.FLP_SMALL DIRP_DIR_MUST_EXIST = _controls_.DIRP_DIR_MUST_EXIST DIRP_CHANGE_DIR = _controls_.DIRP_CHANGE_DIR DIRP_SMALL = _controls_.DIRP_SMALL FLP_USE_TEXTCTRL = _controls_.FLP_USE_TEXTCTRL FLP_DEFAULT_STYLE = _controls_.FLP_DEFAULT_STYLE DIRP_USE_TEXTCTRL = _controls_.DIRP_USE_TEXTCTRL DIRP_DEFAULT_STYLE = _controls_.DIRP_DEFAULT_STYLE class FilePickerCtrl(PickerBase): """Proxy of C++ FilePickerCtrl class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String path=EmptyString, String message=FileSelectorPromptStr, String wildcard=FileSelectorDefaultWildcardStr, Point pos=DefaultPosition, Size size=DefaultSize, long style=FLP_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=FilePickerCtrlNameStr) -> FilePickerCtrl """ _controls_.FilePickerCtrl_swiginit(self,_controls_.new_FilePickerCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String path=EmptyString, String message=FileSelectorPromptStr, String wildcard=FileSelectorDefaultWildcardStr, Point pos=DefaultPosition, Size size=DefaultSize, long style=FLP_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=FilePickerCtrlNameStr) -> bool """ return _controls_.FilePickerCtrl_Create(*args, **kwargs) def GetPath(*args, **kwargs): """GetPath(self) -> String""" return _controls_.FilePickerCtrl_GetPath(*args, **kwargs) def SetPath(*args, **kwargs): """SetPath(self, String str)""" return _controls_.FilePickerCtrl_SetPath(*args, **kwargs) def GetTextCtrlValue(*args, **kwargs): """GetTextCtrlValue(self) -> String""" return _controls_.FilePickerCtrl_GetTextCtrlValue(*args, **kwargs) def SetInitialDirectory(*args, **kwargs): """SetInitialDirectory(self, String dir)""" return _controls_.FilePickerCtrl_SetInitialDirectory(*args, **kwargs) Path = property(GetPath,SetPath,doc="See `GetPath` and `SetPath`") TextCtrlValue = property(GetTextCtrlValue,doc="See `GetTextCtrlValue`") _controls_.FilePickerCtrl_swigregister(FilePickerCtrl) FilePickerCtrlNameStr = cvar.FilePickerCtrlNameStr FileSelectorPromptStr = cvar.FileSelectorPromptStr DirPickerCtrlNameStr = cvar.DirPickerCtrlNameStr DirSelectorPromptStr = cvar.DirSelectorPromptStr FileSelectorDefaultWildcardStr = cvar.FileSelectorDefaultWildcardStr def PreFilePickerCtrl(*args, **kwargs): """PreFilePickerCtrl() -> FilePickerCtrl""" val = _controls_.new_PreFilePickerCtrl(*args, **kwargs) return val class DirPickerCtrl(PickerBase): """Proxy of C++ DirPickerCtrl class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String path=EmptyString, String message=DirSelectorPromptStr, Point pos=DefaultPosition, Size size=DefaultSize, long style=DIRP_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=DirPickerCtrlNameStr) -> DirPickerCtrl """ _controls_.DirPickerCtrl_swiginit(self,_controls_.new_DirPickerCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String path=EmptyString, String message=DirSelectorPromptStr, Point pos=DefaultPosition, Size size=DefaultSize, long style=DIRP_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=DirPickerCtrlNameStr) -> bool """ return _controls_.DirPickerCtrl_Create(*args, **kwargs) def GetPath(*args, **kwargs): """GetPath(self) -> String""" return _controls_.DirPickerCtrl_GetPath(*args, **kwargs) def SetPath(*args, **kwargs): """SetPath(self, String str)""" return _controls_.DirPickerCtrl_SetPath(*args, **kwargs) def GetTextCtrlValue(*args, **kwargs): """GetTextCtrlValue(self) -> String""" return _controls_.DirPickerCtrl_GetTextCtrlValue(*args, **kwargs) Path = property(GetPath,SetPath,doc="See `GetPath` and `SetPath`") TextCtrlValue = property(GetTextCtrlValue,doc="See `GetTextCtrlValue`") _controls_.DirPickerCtrl_swigregister(DirPickerCtrl) def PreDirPickerCtrl(*args, **kwargs): """PreDirPickerCtrl() -> DirPickerCtrl""" val = _controls_.new_PreDirPickerCtrl(*args, **kwargs) return val wxEVT_COMMAND_FILEPICKER_CHANGED = _controls_.wxEVT_COMMAND_FILEPICKER_CHANGED wxEVT_COMMAND_DIRPICKER_CHANGED = _controls_.wxEVT_COMMAND_DIRPICKER_CHANGED EVT_FILEPICKER_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_FILEPICKER_CHANGED, 1 ) EVT_DIRPICKER_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_DIRPICKER_CHANGED, 1 ) class FileDirPickerEvent(_core.CommandEvent): """Proxy of C++ FileDirPickerEvent class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self, EventType type, Object generator, int id, String path) -> FileDirPickerEvent""" _controls_.FileDirPickerEvent_swiginit(self,_controls_.new_FileDirPickerEvent(*args, **kwargs)) def GetPath(*args, **kwargs): """GetPath(self) -> String""" return _controls_.FileDirPickerEvent_GetPath(*args, **kwargs) def SetPath(*args, **kwargs): """SetPath(self, String p)""" return _controls_.FileDirPickerEvent_SetPath(*args, **kwargs) Path = property(GetPath,SetPath,doc="See `GetPath` and `SetPath`") _controls_.FileDirPickerEvent_swigregister(FileDirPickerEvent) #--------------------------------------------------------------------------- FNTP_FONTDESC_AS_LABEL = _controls_.FNTP_FONTDESC_AS_LABEL FNTP_USEFONT_FOR_LABEL = _controls_.FNTP_USEFONT_FOR_LABEL FNTP_USE_TEXTCTRL = _controls_.FNTP_USE_TEXTCTRL FNTP_DEFAULT_STYLE = _controls_.FNTP_DEFAULT_STYLE class FontPickerCtrl(PickerBase): """Proxy of C++ FontPickerCtrl class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Font initial=wxNullFont, Point pos=DefaultPosition, Size size=DefaultSize, long style=FNTP_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=FontPickerCtrlNameStr) -> FontPickerCtrl """ _controls_.FontPickerCtrl_swiginit(self,_controls_.new_FontPickerCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, Font initial=wxNullFont, Point pos=DefaultPosition, Size size=DefaultSize, long style=FNTP_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=FontPickerCtrlNameStr) -> bool """ return _controls_.FontPickerCtrl_Create(*args, **kwargs) def GetSelectedFont(*args, **kwargs): """GetSelectedFont(self) -> Font""" return _controls_.FontPickerCtrl_GetSelectedFont(*args, **kwargs) def SetSelectedFont(*args, **kwargs): """SetSelectedFont(self, Font f)""" return _controls_.FontPickerCtrl_SetSelectedFont(*args, **kwargs) def SetMaxPointSize(*args, **kwargs): """SetMaxPointSize(self, unsigned int max)""" return _controls_.FontPickerCtrl_SetMaxPointSize(*args, **kwargs) def GetMaxPointSize(*args, **kwargs): """GetMaxPointSize(self) -> unsigned int""" return _controls_.FontPickerCtrl_GetMaxPointSize(*args, **kwargs) MaxPointSize = property(GetMaxPointSize,SetMaxPointSize,doc="See `GetMaxPointSize` and `SetMaxPointSize`") SelectedFont = property(GetSelectedFont,SetSelectedFont,doc="See `GetSelectedFont` and `SetSelectedFont`") _controls_.FontPickerCtrl_swigregister(FontPickerCtrl) FontPickerCtrlNameStr = cvar.FontPickerCtrlNameStr def PreFontPickerCtrl(*args, **kwargs): """PreFontPickerCtrl() -> FontPickerCtrl""" val = _controls_.new_PreFontPickerCtrl(*args, **kwargs) return val wxEVT_COMMAND_FONTPICKER_CHANGED = _controls_.wxEVT_COMMAND_FONTPICKER_CHANGED EVT_FONTPICKER_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_FONTPICKER_CHANGED, 1 ) class FontPickerEvent(_core.CommandEvent): """Proxy of C++ FontPickerEvent class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self, Object generator, int id, Font f) -> FontPickerEvent""" _controls_.FontPickerEvent_swiginit(self,_controls_.new_FontPickerEvent(*args, **kwargs)) def GetFont(*args, **kwargs): """GetFont(self) -> Font""" return _controls_.FontPickerEvent_GetFont(*args, **kwargs) def SetFont(*args, **kwargs): """SetFont(self, Font c)""" return _controls_.FontPickerEvent_SetFont(*args, **kwargs) Font = property(GetFont,SetFont,doc="See `GetFont` and `SetFont`") _controls_.FontPickerEvent_swigregister(FontPickerEvent) #--------------------------------------------------------------------------- CP_DEFAULT_STYLE = _controls_.CP_DEFAULT_STYLE CP_NO_TLW_RESIZE = _controls_.CP_NO_TLW_RESIZE class CollapsiblePane(_core.Control): """ A collapsable pane is a container with an embedded button-like control which can be used by the user to collapse or expand the pane's contents. Once constructed you should use the `GetPane` function to access the pane and add your controls inside it (i.e. use the window returned from `GetPane` as the parent for the controls which must go in the pane, NOT the wx.CollapsiblePane itself!). Note that because of its nature of control which can dynamically (and drastically) change its size at run-time under user-input, when putting a wx.CollapsiblePane inside a `wx.Sizer` you should be careful to add it with a proportion value of zero; this is because otherwise all other windows with non-zero proportion values would automatically get resized each time the user expands or collapses the pane window, usually resulting a weird, flickering effect. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int winid=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=CP_DEFAULT_STYLE, Validator val=DefaultValidator, String name=CollapsiblePaneNameStr) -> CollapsiblePane Create and show a wx.CollapsiblePane """ _controls_.CollapsiblePane_swiginit(self,_controls_.new_CollapsiblePane(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int winid=-1, String label=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=CP_DEFAULT_STYLE, Validator val=DefaultValidator, String name=CollapsiblePaneNameStr) -> bool """ return _controls_.CollapsiblePane_Create(*args, **kwargs) def Collapse(*args, **kwargs): """ Collapse(self, bool collapse=True) Collapses or expands the pane window. """ return _controls_.CollapsiblePane_Collapse(*args, **kwargs) def Expand(*args, **kwargs): """ Expand(self) Same as Collapse(False). """ return _controls_.CollapsiblePane_Expand(*args, **kwargs) def IsCollapsed(*args, **kwargs): """ IsCollapsed(self) -> bool Returns ``True`` if the pane window is currently hidden. """ return _controls_.CollapsiblePane_IsCollapsed(*args, **kwargs) def IsExpanded(*args, **kwargs): """ IsExpanded(self) -> bool Returns ``True`` if the pane window is currently shown. """ return _controls_.CollapsiblePane_IsExpanded(*args, **kwargs) def GetPane(*args, **kwargs): """ GetPane(self) -> Window Returns a reference to the pane window. Use the returned `wx.Window` as the parent of widgets to make them part of the collapsible area. """ return _controls_.CollapsiblePane_GetPane(*args, **kwargs) Expanded = property(IsExpanded) Collapsed = property(IsCollapsed) _controls_.CollapsiblePane_swigregister(CollapsiblePane) CollapsiblePaneNameStr = cvar.CollapsiblePaneNameStr def PreCollapsiblePane(*args, **kwargs): """ PreCollapsiblePane() -> CollapsiblePane Precreate a wx.CollapsiblePane for 2-phase creation. """ val = _controls_.new_PreCollapsiblePane(*args, **kwargs) return val wxEVT_COMMAND_COLLPANE_CHANGED = _controls_.wxEVT_COMMAND_COLLPANE_CHANGED EVT_COLLAPSIBLEPANE_CHANGED = wx.PyEventBinder( wxEVT_COMMAND_COLLPANE_CHANGED, 1 ) class CollapsiblePaneEvent(_core.CommandEvent): """Proxy of C++ CollapsiblePaneEvent class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self, Object generator, int id, bool collapsed) -> CollapsiblePaneEvent""" _controls_.CollapsiblePaneEvent_swiginit(self,_controls_.new_CollapsiblePaneEvent(*args, **kwargs)) def GetCollapsed(*args, **kwargs): """GetCollapsed(self) -> bool""" return _controls_.CollapsiblePaneEvent_GetCollapsed(*args, **kwargs) def SetCollapsed(*args, **kwargs): """SetCollapsed(self, bool c)""" return _controls_.CollapsiblePaneEvent_SetCollapsed(*args, **kwargs) Collapsed = property(GetCollapsed,SetCollapsed) _controls_.CollapsiblePaneEvent_swigregister(CollapsiblePaneEvent) #--------------------------------------------------------------------------- class SearchCtrlBase(_core.Control,_core.TextCtrlIface): """Proxy of C++ SearchCtrlBase class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') def __init__(self): raise AttributeError, "No constructor defined" __repr__ = _swig_repr _controls_.SearchCtrlBase_swigregister(SearchCtrlBase) SearchCtrlNameStr = cvar.SearchCtrlNameStr class SearchCtrl(SearchCtrlBase): """ A search control is a composite of a `wx.TextCtrl` with optional bitmap buttons and a drop-down menu. Controls like this can typically be found on a toolbar of applications that support some form of search functionality. On the Mac this control is implemented using the native HISearchField control, on the other platforms a generic control is used, although that may change in the future as more platforms introduce native search widgets. If you wish to use a drop-down menu with your wx.SearchCtrl then you will need to manage its content and handle the menu events yourself, but this is an easy thing to do. Simply build the menu, pass it to `SetMenu`, and also bind a handler for a range of EVT_MENU events. This gives you the flexibility to use the drop-down menu however you wish, such as for a history of searches, or as a way to select different kinds of searches. The ToolBar.py sample in the demo shows one way to do this. Since the control derives from `wx.TextCtrl` it is convenient to use the styles and events designed for `wx.TextCtrl`. For example you can use the ``wx.TE_PROCESS_ENTER`` style and catch the ``wx.EVT_TEXT_ENTER`` event to know when the user has pressed the Enter key in the control and wishes to start a search. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String value=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=SearchCtrlNameStr) -> SearchCtrl A search control is a composite of a `wx.TextCtrl` with optional bitmap buttons and a drop-down menu. Controls like this can typically be found on a toolbar of applications that support some form of search functionality. On the Mac this control is implemented using the native HISearchField control, on the other platforms a generic control is used, although that may change in the future as more platforms introduce native search widgets. If you wish to use a drop-down menu with your wx.SearchCtrl then you will need to manage its content and handle the menu events yourself, but this is an easy thing to do. Simply build the menu, pass it to `SetMenu`, and also bind a handler for a range of EVT_MENU events. This gives you the flexibility to use the drop-down menu however you wish, such as for a history of searches, or as a way to select different kinds of searches. The ToolBar.py sample in the demo shows one way to do this. Since the control derives from `wx.TextCtrl` it is convenient to use the styles and events designed for `wx.TextCtrl`. For example you can use the ``wx.TE_PROCESS_ENTER`` style and catch the ``wx.EVT_TEXT_ENTER`` event to know when the user has pressed the Enter key in the control and wishes to start a search. """ _controls_.SearchCtrl_swiginit(self,_controls_.new_SearchCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String value=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=SearchCtrlNameStr) -> bool """ return _controls_.SearchCtrl_Create(*args, **kwargs) def SetMenu(*args, **kwargs): """ SetMenu(self, Menu menu) Sets the search control's menu object. If there is already a menu associated with the search control it is deleted. """ return _controls_.SearchCtrl_SetMenu(*args, **kwargs) def GetMenu(*args, **kwargs): """ GetMenu(self) -> Menu Returns a pointer to the search control's menu object or None if there is no menu attached. """ return _controls_.SearchCtrl_GetMenu(*args, **kwargs) def ShowSearchButton(*args, **kwargs): """ ShowSearchButton(self, bool show) Sets the search button visibility value on the search control. If there is a menu attached, the search button will be visible regardless of the search button visibility value. This has no effect in Mac OS X v10.3 """ return _controls_.SearchCtrl_ShowSearchButton(*args, **kwargs) def IsSearchButtonVisible(*args, **kwargs): """ IsSearchButtonVisible(self) -> bool Returns the search button visibility value. If there is a menu attached, the search button will be visible regardless of the search button visibility value. This always returns false in Mac OS X v10.3 """ return _controls_.SearchCtrl_IsSearchButtonVisible(*args, **kwargs) def ShowCancelButton(*args, **kwargs): """ ShowCancelButton(self, bool show) Shows or hides the cancel button. """ return _controls_.SearchCtrl_ShowCancelButton(*args, **kwargs) def IsCancelButtonVisible(*args, **kwargs): """ IsCancelButtonVisible(self) -> bool Indicates whether the cancel button is visible. """ return _controls_.SearchCtrl_IsCancelButtonVisible(*args, **kwargs) def SetDescriptiveText(*args, **kwargs): """ SetDescriptiveText(self, String text) Set the text to be displayed when the user has not yet typed anything in the control. """ return _controls_.SearchCtrl_SetDescriptiveText(*args, **kwargs) def GetDescriptiveText(*args, **kwargs): """ GetDescriptiveText(self) -> String Get the text to be displayed when the user has not yet typed anything in the control. """ return _controls_.SearchCtrl_GetDescriptiveText(*args, **kwargs) def SetSearchBitmap(*args, **kwargs): """ SetSearchBitmap(self, Bitmap bitmap) Sets the bitmap to use for the search button. This currently does not work on the Mac. """ return _controls_.SearchCtrl_SetSearchBitmap(*args, **kwargs) def SetSearchMenuBitmap(*args, **kwargs): """ SetSearchMenuBitmap(self, Bitmap bitmap) Sets the bitmap to use for the search button when there is a drop-down menu associated with the search control. This currently does not work on the Mac. """ return _controls_.SearchCtrl_SetSearchMenuBitmap(*args, **kwargs) def SetCancelBitmap(*args, **kwargs): """ SetCancelBitmap(self, Bitmap bitmap) Sets the bitmap to use for the cancel button. This currently does not work on the Mac. """ return _controls_.SearchCtrl_SetCancelBitmap(*args, **kwargs) Menu = property(GetMenu,SetMenu) SearchButtonVisible = property(IsSearchButtonVisible,ShowSearchButton) CancelButtonVisible = property(IsCancelButtonVisible,ShowCancelButton) DescriptiveText = property(GetDescriptiveText,SetDescriptiveText) _controls_.SearchCtrl_swigregister(SearchCtrl) def PreSearchCtrl(*args, **kwargs): """ PreSearchCtrl() -> SearchCtrl Precreate a wx.SearchCtrl for 2-phase creation. """ val = _controls_.new_PreSearchCtrl(*args, **kwargs) return val wxEVT_COMMAND_SEARCHCTRL_CANCEL_BTN = _controls_.wxEVT_COMMAND_SEARCHCTRL_CANCEL_BTN wxEVT_COMMAND_SEARCHCTRL_SEARCH_BTN = _controls_.wxEVT_COMMAND_SEARCHCTRL_SEARCH_BTN EVT_SEARCHCTRL_CANCEL_BTN = wx.PyEventBinder( wxEVT_COMMAND_SEARCHCTRL_CANCEL_BTN, 1) EVT_SEARCHCTRL_SEARCH_BTN = wx.PyEventBinder( wxEVT_COMMAND_SEARCHCTRL_SEARCH_BTN, 1) #--------------------------------------------------------------------------- FC_OPEN = _controls_.FC_OPEN FC_SAVE = _controls_.FC_SAVE FC_MULTIPLE = _controls_.FC_MULTIPLE FC_NOSHOWHIDDEN = _controls_.FC_NOSHOWHIDDEN FC_DEFAULT_STYLE = _controls_.FC_DEFAULT_STYLE class FileCtrl(_core.Window): """ """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String defaultDirectory=wxEmptyString, String defaultFilename=wxEmptyString, String wildCard=wxFileSelectorDefaultWildcardStr, long style=FC_DEFAULT_STYLE, Point pos=DefaultPosition, Size size=DefaultSize, String name=FileCtrlNameStr) -> FileCtrl """ _controls_.FileCtrl_swiginit(self,_controls_.new_FileCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String defaultDirectory=wxEmptyString, String defaultFilename=wxEmptyString, String wildCard=wxFileSelectorDefaultWildcardStr, long style=FC_DEFAULT_STYLE, Point pos=DefaultPosition, Size size=DefaultSize, String name=FileCtrlNameStr) -> bool """ return _controls_.FileCtrl_Create(*args, **kwargs) def SetWildcard(*args, **kwargs): """SetWildcard(self, String wildCard)""" return _controls_.FileCtrl_SetWildcard(*args, **kwargs) def SetFilterIndex(*args, **kwargs): """SetFilterIndex(self, int filterindex)""" return _controls_.FileCtrl_SetFilterIndex(*args, **kwargs) def SetDirectory(*args, **kwargs): """SetDirectory(self, String dir) -> bool""" return _controls_.FileCtrl_SetDirectory(*args, **kwargs) def SetFilename(*args, **kwargs): """SetFilename(self, String name) -> bool""" return _controls_.FileCtrl_SetFilename(*args, **kwargs) def SetPath(*args, **kwargs): """SetPath(self, String path) -> bool""" return _controls_.FileCtrl_SetPath(*args, **kwargs) def GetFilename(*args, **kwargs): """GetFilename(self) -> String""" return _controls_.FileCtrl_GetFilename(*args, **kwargs) def GetDirectory(*args, **kwargs): """GetDirectory(self) -> String""" return _controls_.FileCtrl_GetDirectory(*args, **kwargs) def GetWildcard(*args, **kwargs): """GetWildcard(self) -> String""" return _controls_.FileCtrl_GetWildcard(*args, **kwargs) def GetPath(*args, **kwargs): """GetPath(self) -> String""" return _controls_.FileCtrl_GetPath(*args, **kwargs) def GetFilterIndex(*args, **kwargs): """GetFilterIndex(self) -> int""" return _controls_.FileCtrl_GetFilterIndex(*args, **kwargs) def GetPaths(*args, **kwargs): """GetPaths(self) -> wxArrayString""" return _controls_.FileCtrl_GetPaths(*args, **kwargs) def GetFilenames(*args, **kwargs): """GetFilenames(self) -> wxArrayString""" return _controls_.FileCtrl_GetFilenames(*args, **kwargs) def HasMultipleFileSelection(*args, **kwargs): """HasMultipleFileSelection(self) -> bool""" return _controls_.FileCtrl_HasMultipleFileSelection(*args, **kwargs) def ShowHidden(*args, **kwargs): """ShowHidden(self, bool show)""" return _controls_.FileCtrl_ShowHidden(*args, **kwargs) Filename = property(GetFilename,SetFilename) Directory = property(GetDirectory,SetDirectory) Wildcard = property(GetWildcard,SetWildcard) Path = property(GetPath,SetPath) FilterIndex = property(GetFilterIndex,SetFilterIndex) Paths = property(GetPaths) Filenames = property(GetFilenames) _controls_.FileCtrl_swigregister(FileCtrl) FileCtrlNameStr = cvar.FileCtrlNameStr def PreFileCtrl(*args, **kwargs): """ PreFileCtrl() -> FileCtrl Precreate a wx.FileCtrl for 2-phase creation. """ val = _controls_.new_PreFileCtrl(*args, **kwargs) return val class FileCtrlEvent(_core.CommandEvent): """Proxy of C++ FileCtrlEvent class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """__init__(self, EventType type, Object evtObject, int id) -> FileCtrlEvent""" _controls_.FileCtrlEvent_swiginit(self,_controls_.new_FileCtrlEvent(*args, **kwargs)) def SetFiles(*args, **kwargs): """SetFiles(self, wxArrayString files)""" return _controls_.FileCtrlEvent_SetFiles(*args, **kwargs) def SetDirectory(*args, **kwargs): """SetDirectory(self, String directory)""" return _controls_.FileCtrlEvent_SetDirectory(*args, **kwargs) def SetFilterIndex(*args, **kwargs): """SetFilterIndex(self, int filterIndex)""" return _controls_.FileCtrlEvent_SetFilterIndex(*args, **kwargs) def GetFiles(*args, **kwargs): """GetFiles(self) -> wxArrayString""" return _controls_.FileCtrlEvent_GetFiles(*args, **kwargs) def GetDirectory(*args, **kwargs): """GetDirectory(self) -> String""" return _controls_.FileCtrlEvent_GetDirectory(*args, **kwargs) def GetFilterIndex(*args, **kwargs): """GetFilterIndex(self) -> int""" return _controls_.FileCtrlEvent_GetFilterIndex(*args, **kwargs) def GetFile(*args, **kwargs): """GetFile(self) -> String""" return _controls_.FileCtrlEvent_GetFile(*args, **kwargs) Files = property(GetFiles,SetFiles) Directory = property(GetDirectory,SetDirectory) FilterIndex = property(GetFilterIndex,SetFilterIndex) _controls_.FileCtrlEvent_swigregister(FileCtrlEvent) wxEVT_FILECTRL_SELECTIONCHANGED = _controls_.wxEVT_FILECTRL_SELECTIONCHANGED wxEVT_FILECTRL_FILEACTIVATED = _controls_.wxEVT_FILECTRL_FILEACTIVATED wxEVT_FILECTRL_FOLDERCHANGED = _controls_.wxEVT_FILECTRL_FOLDERCHANGED wxEVT_FILECTRL_FILTERCHANGED = _controls_.wxEVT_FILECTRL_FILTERCHANGED EVT_FILECTRL_SELECTIONCHANGED = wx.PyEventBinder( wxEVT_FILECTRL_SELECTIONCHANGED, 1) EVT_FILECTRL_FILEACTIVATED = wx.PyEventBinder( wxEVT_FILECTRL_FILEACTIVATED, 1) EVT_FILECTRL_FOLDERCHANGED = wx.PyEventBinder( wxEVT_FILECTRL_FOLDERCHANGED, 1) EVT_FILECTRL_FILTERCHANGED = wx.PyEventBinder( wxEVT_FILECTRL_FILTERCHANGED, 1) #--------------------------------------------------------------------------- class InfoBar(_core.Control): """ An info bar is a transient window shown at top or bottom of its parent window to display non-critical information to the user. It works similarly to message bars in current web browsers. """ thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int winid=ID_ANY) -> InfoBar An info bar is a transient window shown at top or bottom of its parent window to display non-critical information to the user. It works similarly to message bars in current web browsers. """ _controls_.InfoBar_swiginit(self,_controls_.new_InfoBar(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int winid=ID_ANY) -> bool Do the 2nd phase and create the GUI control. """ return _controls_.InfoBar_Create(*args, **kwargs) def ShowMessage(*args, **kwargs): """ShowMessage(self, String msg, int flags=ICON_INFORMATION)""" return _controls_.InfoBar_ShowMessage(*args, **kwargs) def Dismiss(*args, **kwargs): """Dismiss(self)""" return _controls_.InfoBar_Dismiss(*args, **kwargs) def AddButton(*args, **kwargs): """AddButton(self, int btnid, String label=wxEmptyString)""" return _controls_.InfoBar_AddButton(*args, **kwargs) def RemoveButton(*args, **kwargs): """RemoveButton(self, int btnid)""" return _controls_.InfoBar_RemoveButton(*args, **kwargs) def SetShowHideEffects(*args, **kwargs): """SetShowHideEffects(self, int showEffect, int hideEffect)""" return _controls_.InfoBar_SetShowHideEffects(*args, **kwargs) def GetShowEffect(*args, **kwargs): """GetShowEffect(self) -> int""" return _controls_.InfoBar_GetShowEffect(*args, **kwargs) def GetHideEffect(*args, **kwargs): """GetHideEffect(self) -> int""" return _controls_.InfoBar_GetHideEffect(*args, **kwargs) def SetEffectDuration(*args, **kwargs): """SetEffectDuration(self, int duration)""" return _controls_.InfoBar_SetEffectDuration(*args, **kwargs) def GetEffectDuration(*args, **kwargs): """GetEffectDuration(self) -> int""" return _controls_.InfoBar_GetEffectDuration(*args, **kwargs) _controls_.InfoBar_swigregister(InfoBar) def PreInfoBar(*args, **kwargs): """ PreInfoBar() -> InfoBar An info bar is a transient window shown at top or bottom of its parent window to display non-critical information to the user. It works similarly to message bars in current web browsers. """ val = _controls_.new_PreInfoBar(*args, **kwargs) return val #--------------------------------------------------------------------------- class CommandLinkButton(Button): """Proxy of C++ CommandLinkButton class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String mainLabel=wxEmptyString, String note=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=wxButtonNameStr) -> CommandLinkButton """ _controls_.CommandLinkButton_swiginit(self,_controls_.new_CommandLinkButton(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String mainLabel=wxEmptyString, String note=wxEmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=wxButtonNameStr) -> bool """ return _controls_.CommandLinkButton_Create(*args, **kwargs) def SetMainLabelAndNote(*args, **kwargs): """SetMainLabelAndNote(self, String mainLabel, String note)""" return _controls_.CommandLinkButton_SetMainLabelAndNote(*args, **kwargs) def SetMainLabel(*args, **kwargs): """SetMainLabel(self, String mainLabel)""" return _controls_.CommandLinkButton_SetMainLabel(*args, **kwargs) def SetNote(*args, **kwargs): """SetNote(self, String note)""" return _controls_.CommandLinkButton_SetNote(*args, **kwargs) def GetMainLabel(*args, **kwargs): """GetMainLabel(self) -> String""" return _controls_.CommandLinkButton_GetMainLabel(*args, **kwargs) def GetNote(*args, **kwargs): """GetNote(self) -> String""" return _controls_.CommandLinkButton_GetNote(*args, **kwargs) MainLabel = property(GetMainLabel,SetMainLabel) Note = property(GetNote,SetNote) _controls_.CommandLinkButton_swigregister(CommandLinkButton) def PreCommandLinkButton(*args, **kwargs): """ PreCommandLinkButton() -> CommandLinkButton Precreate a Button for 2-phase creation. """ val = _controls_.new_PreCommandLinkButton(*args, **kwargs) return val
gpl-3.0
-3,839,353,247,363,315,700
41.465057
151
0.65503
false
blackbliss/callme
flask/lib/python2.7/site-packages/werkzeug/contrib/cache.py
306
23519
# -*- coding: utf-8 -*- """ werkzeug.contrib.cache ~~~~~~~~~~~~~~~~~~~~~~ The main problem with dynamic Web sites is, well, they're dynamic. Each time a user requests a page, the webserver executes a lot of code, queries the database, renders templates until the visitor gets the page he sees. This is a lot more expensive than just loading a file from the file system and sending it to the visitor. For most Web applications, this overhead isn't a big deal but once it becomes, you will be glad to have a cache system in place. How Caching Works ================= Caching is pretty simple. Basically you have a cache object lurking around somewhere that is connected to a remote cache or the file system or something else. When the request comes in you check if the current page is already in the cache and if so, you're returning it from the cache. Otherwise you generate the page and put it into the cache. (Or a fragment of the page, you don't have to cache the full thing) Here is a simple example of how to cache a sidebar for a template:: def get_sidebar(user): identifier = 'sidebar_for/user%d' % user.id value = cache.get(identifier) if value is not None: return value value = generate_sidebar_for(user=user) cache.set(identifier, value, timeout=60 * 5) return value Creating a Cache Object ======================= To create a cache object you just import the cache system of your choice from the cache module and instantiate it. Then you can start working with that object: >>> from werkzeug.contrib.cache import SimpleCache >>> c = SimpleCache() >>> c.set("foo", "value") >>> c.get("foo") 'value' >>> c.get("missing") is None True Please keep in mind that you have to create the cache and put it somewhere you have access to it (either as a module global you can import or you just put it into your WSGI application). :copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import os import re import tempfile from hashlib import md5 from time import time try: import cPickle as pickle except ImportError: import pickle from werkzeug._compat import iteritems, string_types, text_type, \ integer_types, to_bytes from werkzeug.posixemulation import rename def _items(mappingorseq): """Wrapper for efficient iteration over mappings represented by dicts or sequences:: >>> for k, v in _items((i, i*i) for i in xrange(5)): ... assert k*k == v >>> for k, v in _items(dict((i, i*i) for i in xrange(5))): ... assert k*k == v """ if hasattr(mappingorseq, "iteritems"): return mappingorseq.iteritems() elif hasattr(mappingorseq, "items"): return mappingorseq.items() return mappingorseq class BaseCache(object): """Baseclass for the cache systems. All the cache systems implement this API or a superset of it. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`set`. """ def __init__(self, default_timeout=300): self.default_timeout = default_timeout def get(self, key): """Looks up key in the cache and returns the value for it. If the key does not exist `None` is returned instead. :param key: the key to be looked up. """ return None def delete(self, key): """Deletes `key` from the cache. If it does not exist in the cache nothing happens. :param key: the key to delete. """ pass def get_many(self, *keys): """Returns a list of values for the given keys. For each key a item in the list is created. Example:: foo, bar = cache.get_many("foo", "bar") If a key can't be looked up `None` is returned for that key instead. :param keys: The function accepts multiple keys as positional arguments. """ return map(self.get, keys) def get_dict(self, *keys): """Works like :meth:`get_many` but returns a dict:: d = cache.get_dict("foo", "bar") foo = d["foo"] bar = d["bar"] :param keys: The function accepts multiple keys as positional arguments. """ return dict(zip(keys, self.get_many(*keys))) def set(self, key, value, timeout=None): """Adds a new key/value to the cache (overwrites value, if key already exists in the cache). :param key: the key to set :param value: the value for the key :param timeout: the cache timeout for the key (if not specified, it uses the default timeout). """ pass def add(self, key, value, timeout=None): """Works like :meth:`set` but does not overwrite the values of already existing keys. :param key: the key to set :param value: the value for the key :param timeout: the cache timeout for the key or the default timeout if not specified. """ pass def set_many(self, mapping, timeout=None): """Sets multiple keys and values from a mapping. :param mapping: a mapping with the keys/values to set. :param timeout: the cache timeout for the key (if not specified, it uses the default timeout). """ for key, value in _items(mapping): self.set(key, value, timeout) def delete_many(self, *keys): """Deletes multiple keys at once. :param keys: The function accepts multiple keys as positional arguments. """ for key in keys: self.delete(key) def clear(self): """Clears the cache. Keep in mind that not all caches support completely clearing the cache. """ pass def inc(self, key, delta=1): """Increments the value of a key by `delta`. If the key does not yet exist it is initialized with `delta`. For supporting caches this is an atomic operation. :param key: the key to increment. :param delta: the delta to add. """ self.set(key, (self.get(key) or 0) + delta) def dec(self, key, delta=1): """Decrements the value of a key by `delta`. If the key does not yet exist it is initialized with `-delta`. For supporting caches this is an atomic operation. :param key: the key to increment. :param delta: the delta to subtract. """ self.set(key, (self.get(key) or 0) - delta) class NullCache(BaseCache): """A cache that doesn't cache. This can be useful for unit testing. :param default_timeout: a dummy parameter that is ignored but exists for API compatibility with other caches. """ class SimpleCache(BaseCache): """Simple memory cache for single process environments. This class exists mainly for the development server and is not 100% thread safe. It tries to use as many atomic operations as possible and no locks for simplicity but it could happen under heavy load that keys are added multiple times. :param threshold: the maximum number of items the cache stores before it starts deleting some. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. """ def __init__(self, threshold=500, default_timeout=300): BaseCache.__init__(self, default_timeout) self._cache = {} self.clear = self._cache.clear self._threshold = threshold def _prune(self): if len(self._cache) > self._threshold: now = time() for idx, (key, (expires, _)) in enumerate(self._cache.items()): if expires <= now or idx % 3 == 0: self._cache.pop(key, None) def get(self, key): expires, value = self._cache.get(key, (0, None)) if expires > time(): return pickle.loads(value) def set(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout self._prune() self._cache[key] = (time() + timeout, pickle.dumps(value, pickle.HIGHEST_PROTOCOL)) def add(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout if len(self._cache) > self._threshold: self._prune() item = (time() + timeout, pickle.dumps(value, pickle.HIGHEST_PROTOCOL)) self._cache.setdefault(key, item) def delete(self, key): self._cache.pop(key, None) _test_memcached_key = re.compile(br'[^\x00-\x21\xff]{1,250}$').match class MemcachedCache(BaseCache): """A cache that uses memcached as backend. The first argument can either be an object that resembles the API of a :class:`memcache.Client` or a tuple/list of server addresses. In the event that a tuple/list is passed, Werkzeug tries to import the best available memcache library. Implementation notes: This cache backend works around some limitations in memcached to simplify the interface. For example unicode keys are encoded to utf-8 on the fly. Methods such as :meth:`~BaseCache.get_dict` return the keys in the same format as passed. Furthermore all get methods silently ignore key errors to not cause problems when untrusted user data is passed to the get methods which is often the case in web applications. :param servers: a list or tuple of server addresses or alternatively a :class:`memcache.Client` or a compatible client. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. :param key_prefix: a prefix that is added before all keys. This makes it possible to use the same memcached server for different applications. Keep in mind that :meth:`~BaseCache.clear` will also clear keys with a different prefix. """ def __init__(self, servers=None, default_timeout=300, key_prefix=None): BaseCache.__init__(self, default_timeout) if servers is None or isinstance(servers, (list, tuple)): if servers is None: servers = ['127.0.0.1:11211'] self._client = self.import_preferred_memcache_lib(servers) if self._client is None: raise RuntimeError('no memcache module found') else: # NOTE: servers is actually an already initialized memcache # client. self._client = servers self.key_prefix = to_bytes(key_prefix) def get(self, key): if isinstance(key, text_type): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key # memcached doesn't support keys longer than that. Because often # checks for so long keys can occour because it's tested from user # submitted data etc we fail silently for getting. if _test_memcached_key(key): return self._client.get(key) def get_dict(self, *keys): key_mapping = {} have_encoded_keys = False for key in keys: if isinstance(key, unicode): encoded_key = key.encode('utf-8') have_encoded_keys = True else: encoded_key = key if self.key_prefix: encoded_key = self.key_prefix + encoded_key if _test_memcached_key(key): key_mapping[encoded_key] = key d = rv = self._client.get_multi(key_mapping.keys()) if have_encoded_keys or self.key_prefix: rv = {} for key, value in iteritems(d): rv[key_mapping[key]] = value if len(rv) < len(keys): for key in keys: if key not in rv: rv[key] = None return rv def add(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout if isinstance(key, text_type): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key self._client.add(key, value, timeout) def set(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout if isinstance(key, text_type): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key self._client.set(key, value, timeout) def get_many(self, *keys): d = self.get_dict(*keys) return [d[key] for key in keys] def set_many(self, mapping, timeout=None): if timeout is None: timeout = self.default_timeout new_mapping = {} for key, value in _items(mapping): if isinstance(key, text_type): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key new_mapping[key] = value self._client.set_multi(new_mapping, timeout) def delete(self, key): if isinstance(key, unicode): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key if _test_memcached_key(key): self._client.delete(key) def delete_many(self, *keys): new_keys = [] for key in keys: if isinstance(key, unicode): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key if _test_memcached_key(key): new_keys.append(key) self._client.delete_multi(new_keys) def clear(self): self._client.flush_all() def inc(self, key, delta=1): if isinstance(key, unicode): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key self._client.incr(key, delta) def dec(self, key, delta=1): if isinstance(key, unicode): key = key.encode('utf-8') if self.key_prefix: key = self.key_prefix + key self._client.decr(key, delta) def import_preferred_memcache_lib(self, servers): """Returns an initialized memcache client. Used by the constructor.""" try: import pylibmc except ImportError: pass else: return pylibmc.Client(servers) try: from google.appengine.api import memcache except ImportError: pass else: return memcache.Client() try: import memcache except ImportError: pass else: return memcache.Client(servers) # backwards compatibility GAEMemcachedCache = MemcachedCache class RedisCache(BaseCache): """Uses the Redis key-value store as a cache backend. The first argument can be either a string denoting address of the Redis server or an object resembling an instance of a redis.Redis class. Note: Python Redis API already takes care of encoding unicode strings on the fly. .. versionadded:: 0.7 .. versionadded:: 0.8 `key_prefix` was added. .. versionchanged:: 0.8 This cache backend now properly serializes objects. .. versionchanged:: 0.8.3 This cache backend now supports password authentication. :param host: address of the Redis server or an object which API is compatible with the official Python Redis client (redis-py). :param port: port number on which Redis server listens for connections. :param password: password authentication for the Redis server. :param db: db (zero-based numeric index) on Redis Server to connect. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. :param key_prefix: A prefix that should be added to all keys. """ def __init__(self, host='localhost', port=6379, password=None, db=0, default_timeout=300, key_prefix=None): BaseCache.__init__(self, default_timeout) if isinstance(host, string_types): try: import redis except ImportError: raise RuntimeError('no redis module found') self._client = redis.Redis(host=host, port=port, password=password, db=db) else: self._client = host self.key_prefix = key_prefix or '' def dump_object(self, value): """Dumps an object into a string for redis. By default it serializes integers as regular string and pickle dumps everything else. """ t = type(value) if t in integer_types: return str(value).encode('ascii') return b'!' + pickle.dumps(value) def load_object(self, value): """The reversal of :meth:`dump_object`. This might be callde with None. """ if value is None: return None if value.startswith(b'!'): return pickle.loads(value[1:]) try: return int(value) except ValueError: # before 0.8 we did not have serialization. Still support that. return value def get(self, key): return self.load_object(self._client.get(self.key_prefix + key)) def get_many(self, *keys): if self.key_prefix: keys = [self.key_prefix + key for key in keys] return [self.load_object(x) for x in self._client.mget(keys)] def set(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout dump = self.dump_object(value) self._client.setex(self.key_prefix + key, dump, timeout) def add(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout dump = self.dump_object(value) added = self._client.setnx(self.key_prefix + key, dump) if added: self._client.expire(self.key_prefix + key, timeout) def set_many(self, mapping, timeout=None): if timeout is None: timeout = self.default_timeout pipe = self._client.pipeline() for key, value in _items(mapping): dump = self.dump_object(value) pipe.setex(self.key_prefix + key, dump, timeout) pipe.execute() def delete(self, key): self._client.delete(self.key_prefix + key) def delete_many(self, *keys): if not keys: return if self.key_prefix: keys = [self.key_prefix + key for key in keys] self._client.delete(*keys) def clear(self): if self.key_prefix: keys = self._client.keys(self.key_prefix + '*') if keys: self._client.delete(*keys) else: self._client.flushdb() def inc(self, key, delta=1): return self._client.incr(self.key_prefix + key, delta) def dec(self, key, delta=1): return self._client.decr(self.key_prefix + key, delta) class FileSystemCache(BaseCache): """A cache that stores the items on the file system. This cache depends on being the only user of the `cache_dir`. Make absolutely sure that nobody but this cache stores files there or otherwise the cache will randomly delete files therein. :param cache_dir: the directory where cache files are stored. :param threshold: the maximum number of items the cache stores before it starts deleting some. :param default_timeout: the default timeout that is used if no timeout is specified on :meth:`~BaseCache.set`. :param mode: the file mode wanted for the cache files, default 0600 """ #: used for temporary files by the FileSystemCache _fs_transaction_suffix = '.__wz_cache' def __init__(self, cache_dir, threshold=500, default_timeout=300, mode=0o600): BaseCache.__init__(self, default_timeout) self._path = cache_dir self._threshold = threshold self._mode = mode if not os.path.exists(self._path): os.makedirs(self._path) def _list_dir(self): """return a list of (fully qualified) cache filenames """ return [os.path.join(self._path, fn) for fn in os.listdir(self._path) if not fn.endswith(self._fs_transaction_suffix)] def _prune(self): entries = self._list_dir() if len(entries) > self._threshold: now = time() for idx, fname in enumerate(entries): remove = False f = None try: try: f = open(fname, 'rb') expires = pickle.load(f) remove = expires <= now or idx % 3 == 0 finally: if f is not None: f.close() except Exception: pass if remove: try: os.remove(fname) except (IOError, OSError): pass def clear(self): for fname in self._list_dir(): try: os.remove(fname) except (IOError, OSError): pass def _get_filename(self, key): if isinstance(key, text_type): key = key.encode('utf-8') #XXX unicode review hash = md5(key).hexdigest() return os.path.join(self._path, hash) def get(self, key): filename = self._get_filename(key) try: f = open(filename, 'rb') try: if pickle.load(f) >= time(): return pickle.load(f) finally: f.close() os.remove(filename) except Exception: return None def add(self, key, value, timeout=None): filename = self._get_filename(key) if not os.path.exists(filename): self.set(key, value, timeout) def set(self, key, value, timeout=None): if timeout is None: timeout = self.default_timeout filename = self._get_filename(key) self._prune() try: fd, tmp = tempfile.mkstemp(suffix=self._fs_transaction_suffix, dir=self._path) f = os.fdopen(fd, 'wb') try: pickle.dump(int(time() + timeout), f, 1) pickle.dump(value, f, pickle.HIGHEST_PROTOCOL) finally: f.close() rename(tmp, filename) os.chmod(filename, self._mode) except (IOError, OSError): pass def delete(self, key): try: os.remove(self._get_filename(key)) except (IOError, OSError): pass
mit
-7,111,811,701,270,589,000
33.637703
86
0.579106
false
pipet/pipet
pipet/sources/zendesk/tasks.py
2
1544
from contextlib import contextmanager from datetime import datetime from inspect import isclass from celery import chord, group from celery_once import QueueOnce from celery.schedules import crontab from celery.utils.log import get_task_logger from sqlalchemy.orm.attributes import flag_modified # from pipet import celery from pipet.models import db, Organization from pipet.sources.zendesk import ZendeskAccount from pipet.sources.zendesk.models import ( Base, CLASS_REGISTRY, ) logger = get_task_logger(__name__) # @celery.task(base=QueueOnce, once={'graceful': True}) def sync(account_id): with app.app_context(): account = ZendeskAccount.query.get(account_id) session = account.organization.create_session() for cls in [m for n, m in CLASS_REGISTRY.items() if isclass(m) and issubclass(m, Base)]: # TODO: Make these parallel to speed up execution while True: conn = session.connection() statments, cursor, has_more = cls.sync(account) account.cursors[cls.__tablename__] = cursor flag_modified(account, 'cursors') for statement in statments: conn.execute(statement) session.commit() db.session.add(account) db.session.commit() if not has_more: break # @celery.task def sync_all(): job = group([sync.s(account.id) for account in ZendeskAccount.query.all()]) job.apply_async()
apache-2.0
156,606,072,465,059,940
28.692308
96
0.645725
false
tomchristie/django
django/apps/config.py
55
8047
import os from importlib import import_module from django.core.exceptions import ImproperlyConfigured from django.utils.module_loading import module_has_submodule MODELS_MODULE_NAME = 'models' class AppConfig: """Class representing a Django application and its configuration.""" def __init__(self, app_name, app_module): # Full Python path to the application e.g. 'django.contrib.admin'. self.name = app_name # Root module for the application e.g. <module 'django.contrib.admin' # from 'django/contrib/admin/__init__.py'>. self.module = app_module # Reference to the Apps registry that holds this AppConfig. Set by the # registry when it registers the AppConfig instance. self.apps = None # The following attributes could be defined at the class level in a # subclass, hence the test-and-set pattern. # Last component of the Python path to the application e.g. 'admin'. # This value must be unique across a Django project. if not hasattr(self, 'label'): self.label = app_name.rpartition(".")[2] # Human-readable name for the application e.g. "Admin". if not hasattr(self, 'verbose_name'): self.verbose_name = self.label.title() # Filesystem path to the application directory e.g. # '/path/to/django/contrib/admin'. if not hasattr(self, 'path'): self.path = self._path_from_module(app_module) # Module containing models e.g. <module 'django.contrib.admin.models' # from 'django/contrib/admin/models.py'>. Set by import_models(). # None if the application doesn't have a models module. self.models_module = None # Mapping of lower case model names to model classes. Initially set to # None to prevent accidental access before import_models() runs. self.models = None def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self.label) def _path_from_module(self, module): """Attempt to determine app's filesystem path from its module.""" # See #21874 for extended discussion of the behavior of this method in # various cases. # Convert paths to list because Python's _NamespacePath doesn't support # indexing. paths = list(getattr(module, '__path__', [])) if len(paths) != 1: filename = getattr(module, '__file__', None) if filename is not None: paths = [os.path.dirname(filename)] else: # For unknown reasons, sometimes the list returned by __path__ # contains duplicates that must be removed (#25246). paths = list(set(paths)) if len(paths) > 1: raise ImproperlyConfigured( "The app module %r has multiple filesystem locations (%r); " "you must configure this app with an AppConfig subclass " "with a 'path' class attribute." % (module, paths)) elif not paths: raise ImproperlyConfigured( "The app module %r has no filesystem location, " "you must configure this app with an AppConfig subclass " "with a 'path' class attribute." % (module,)) return paths[0] @classmethod def create(cls, entry): """ Factory that creates an app config from an entry in INSTALLED_APPS. """ try: # If import_module succeeds, entry is a path to an app module, # which may specify an app config class with default_app_config. # Otherwise, entry is a path to an app config class or an error. module = import_module(entry) except ImportError: # Track that importing as an app module failed. If importing as an # app config class fails too, we'll trigger the ImportError again. module = None mod_path, _, cls_name = entry.rpartition('.') # Raise the original exception when entry cannot be a path to an # app config class. if not mod_path: raise else: try: # If this works, the app module specifies an app config class. entry = module.default_app_config except AttributeError: # Otherwise, it simply uses the default app config class. return cls(entry, module) else: mod_path, _, cls_name = entry.rpartition('.') # If we're reaching this point, we must attempt to load the app config # class located at <mod_path>.<cls_name> mod = import_module(mod_path) try: cls = getattr(mod, cls_name) except AttributeError: if module is None: # If importing as an app module failed, that error probably # contains the most informative traceback. Trigger it again. import_module(entry) else: raise # Check for obvious errors. (This check prevents duck typing, but # it could be removed if it became a problem in practice.) if not issubclass(cls, AppConfig): raise ImproperlyConfigured( "'%s' isn't a subclass of AppConfig." % entry) # Obtain app name here rather than in AppClass.__init__ to keep # all error checking for entries in INSTALLED_APPS in one place. try: app_name = cls.name except AttributeError: raise ImproperlyConfigured( "'%s' must supply a name attribute." % entry) # Ensure app_name points to a valid module. try: app_module = import_module(app_name) except ImportError: raise ImproperlyConfigured( "Cannot import '%s'. Check that '%s.%s.name' is correct." % ( app_name, mod_path, cls_name, ) ) # Entry is a path to an app config class. return cls(app_name, app_module) def get_model(self, model_name, require_ready=True): """ Return the model with the given case-insensitive model_name. Raise LookupError if no model exists with this name. """ if require_ready: self.apps.check_models_ready() else: self.apps.check_apps_ready() try: return self.models[model_name.lower()] except KeyError: raise LookupError( "App '%s' doesn't have a '%s' model." % (self.label, model_name)) def get_models(self, include_auto_created=False, include_swapped=False): """ Return an iterable of models. By default, the following models aren't included: - auto-created models for many-to-many relations without an explicit intermediate table, - models that have been swapped out. Set the corresponding keyword argument to True to include such models. Keyword arguments aren't documented; they're a private API. """ self.apps.check_models_ready() for model in self.models.values(): if model._meta.auto_created and not include_auto_created: continue if model._meta.swapped and not include_swapped: continue yield model def import_models(self): # Dictionary of models for this app, primarily maintained in the # 'all_models' attribute of the Apps this AppConfig is attached to. self.models = self.apps.all_models[self.label] if module_has_submodule(self.module, MODELS_MODULE_NAME): models_module_name = '%s.%s' % (self.name, MODELS_MODULE_NAME) self.models_module = import_module(models_module_name) def ready(self): """ Override this method in subclasses to run code when Django starts. """
bsd-3-clause
-8,530,773,113,433,397,000
38.640394
81
0.59227
false
prutseltje/ansible
test/units/modules/network/f5/test_bigip_gtm_datacenter.py
23
6819
# -*- 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.modules.bigip_gtm_datacenter import ApiParameters from library.modules.bigip_gtm_datacenter import ModuleParameters from library.modules.bigip_gtm_datacenter import ModuleManager from library.modules.bigip_gtm_datacenter 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_gtm_datacenter import ApiParameters from ansible.modules.network.f5.bigip_gtm_datacenter import ModuleParameters from ansible.modules.network.f5.bigip_gtm_datacenter import ModuleManager from ansible.modules.network.f5.bigip_gtm_datacenter 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( state='present', contact='foo', description='bar', location='baz', name='datacenter' ) p = ModuleParameters(params=args) assert p.state == 'present' def test_api_parameters(self): args = load_fixture('load_gtm_datacenter_default.json') p = ApiParameters(params=args) assert p.name == 'asd' def test_module_parameters_state_present(self): args = dict( state='present' ) p = ModuleParameters(params=args) assert p.state == 'present' assert p.enabled is True def test_module_parameters_state_absent(self): args = dict( state='absent' ) p = ModuleParameters(params=args) assert p.state == 'absent' def test_module_parameters_state_enabled(self): args = dict( state='enabled' ) p = ModuleParameters(params=args) assert p.state == 'enabled' assert p.enabled is True assert p.disabled is None def test_module_parameters_state_disabled(self): args = dict( state='disabled' ) p = ModuleParameters(params=args) assert p.state == 'disabled' assert p.enabled is None assert p.disabled is True class TestManager(unittest.TestCase): def setUp(self): self.spec = ArgumentSpec() def test_create_datacenter(self, *args): set_module_args(dict( state='present', password='admin', server='localhost', user='admin', name='foo' )) 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.exists = Mock(side_effect=[False, True]) mm.create_on_device = Mock(return_value=True) results = mm.exec_module() assert results['changed'] is True assert results['state'] == 'present' def test_create_disabled_datacenter(self, *args): set_module_args(dict( state='disabled', password='admin', server='localhost', user='admin', name='foo' )) 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.exists = Mock(side_effect=[False, True]) mm.create_on_device = Mock(return_value=True) results = mm.exec_module() assert results['changed'] is True assert results['enabled'] is False assert results['disabled'] is True def test_create_enabled_datacenter(self, *args): set_module_args(dict( state='enabled', password='admin', server='localhost', user='admin', name='foo' )) 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.exists = Mock(side_effect=[False, True]) mm.create_on_device = Mock(return_value=True) results = mm.exec_module() assert results['changed'] is True assert results['enabled'] is True assert results['disabled'] is False def test_idempotent_disable_datacenter(self, *args): set_module_args(dict( state='disabled', password='admin', server='localhost', user='admin', name='foo' )) module = AnsibleModule( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode ) current = ApiParameters(params=load_fixture('load_gtm_datacenter_disabled.json')) mm = ModuleManager(module=module) # Override methods to force specific logic in the module to happen mm.exists = Mock(return_value=True) mm.update_on_device = Mock(return_value=True) mm.read_current_from_device = Mock(return_value=current) results = mm.exec_module() assert results['changed'] is False
gpl-3.0
1,435,203,684,349,960,200
30.716279
91
0.628685
false
antb/TPT----My-old-mod
src/python/stdlib/ctypes/test/test_errno.py
115
2330
import unittest, os, errno from ctypes import * from ctypes.util import find_library from test import test_support try: import threading except ImportError: threading = None class Test(unittest.TestCase): def test_open(self): libc_name = find_library("c") if libc_name is None: raise unittest.SkipTest("Unable to find C library") libc = CDLL(libc_name, use_errno=True) if os.name == "nt": libc_open = libc._open else: libc_open = libc.open libc_open.argtypes = c_char_p, c_int self.assertEqual(libc_open("", 0), -1) self.assertEqual(get_errno(), errno.ENOENT) self.assertEqual(set_errno(32), errno.ENOENT) self.assertEqual(get_errno(), 32) if threading: def _worker(): set_errno(0) libc = CDLL(libc_name, use_errno=False) if os.name == "nt": libc_open = libc._open else: libc_open = libc.open libc_open.argtypes = c_char_p, c_int self.assertEqual(libc_open("", 0), -1) self.assertEqual(get_errno(), 0) t = threading.Thread(target=_worker) t.start() t.join() self.assertEqual(get_errno(), 32) set_errno(0) @unittest.skipUnless(os.name == "nt", 'Test specific to Windows') def test_GetLastError(self): dll = WinDLL("kernel32", use_last_error=True) GetModuleHandle = dll.GetModuleHandleA GetModuleHandle.argtypes = [c_wchar_p] self.assertEqual(0, GetModuleHandle("foo")) self.assertEqual(get_last_error(), 126) self.assertEqual(set_last_error(32), 126) self.assertEqual(get_last_error(), 32) def _worker(): set_last_error(0) dll = WinDLL("kernel32", use_last_error=False) GetModuleHandle = dll.GetModuleHandleW GetModuleHandle.argtypes = [c_wchar_p] GetModuleHandle("bar") self.assertEqual(get_last_error(), 0) t = threading.Thread(target=_worker) t.start() t.join() self.assertEqual(get_last_error(), 32) set_last_error(0) if __name__ == "__main__": unittest.main()
gpl-2.0
785,952,512,028,991,400
28.125
69
0.554077
false
Sarah-Alsinan/muypicky
lib/python3.6/site-packages/django/db/backends/sqlite3/creation.py
60
4965
import os import shutil import sys from django.core.exceptions import ImproperlyConfigured from django.db.backends.base.creation import BaseDatabaseCreation from django.utils.encoding import force_text from django.utils.six.moves import input class DatabaseCreation(BaseDatabaseCreation): @staticmethod def is_in_memory_db(database_name): return database_name == ':memory:' or 'mode=memory' in force_text(database_name) def _get_test_db_name(self): test_database_name = self.connection.settings_dict['TEST']['NAME'] can_share_in_memory_db = self.connection.features.can_share_in_memory_db if not test_database_name: test_database_name = ':memory:' if can_share_in_memory_db: if test_database_name == ':memory:': return 'file:memorydb_%s?mode=memory&cache=shared' % self.connection.alias elif 'mode=memory' in test_database_name: raise ImproperlyConfigured( "Using a shared memory database with `mode=memory` in the " "database name is not supported in your environment, " "use `:memory:` instead." ) return test_database_name def _create_test_db(self, verbosity, autoclobber, keepdb=False): test_database_name = self._get_test_db_name() if keepdb: return test_database_name if not self.is_in_memory_db(test_database_name): # Erase the old test database if verbosity >= 1: print("Destroying old test database for alias %s..." % ( self._get_database_display_str(verbosity, test_database_name), )) if os.access(test_database_name, os.F_OK): if not autoclobber: confirm = input( "Type 'yes' if you would like to try deleting the test " "database '%s', or 'no' to cancel: " % test_database_name ) if autoclobber or confirm == 'yes': try: os.remove(test_database_name) except Exception as e: sys.stderr.write("Got an error deleting the old test database: %s\n" % e) sys.exit(2) else: print("Tests cancelled.") sys.exit(1) return test_database_name def get_test_db_clone_settings(self, number): orig_settings_dict = self.connection.settings_dict source_database_name = orig_settings_dict['NAME'] if self.is_in_memory_db(source_database_name): return orig_settings_dict else: new_settings_dict = orig_settings_dict.copy() root, ext = os.path.splitext(orig_settings_dict['NAME']) new_settings_dict['NAME'] = '{}_{}.{}'.format(root, number, ext) return new_settings_dict def _clone_test_db(self, number, verbosity, keepdb=False): source_database_name = self.connection.settings_dict['NAME'] target_database_name = self.get_test_db_clone_settings(number)['NAME'] # Forking automatically makes a copy of an in-memory database. if not self.is_in_memory_db(source_database_name): # Erase the old test database if os.access(target_database_name, os.F_OK): if keepdb: return if verbosity >= 1: print("Destroying old test database for alias %s..." % ( self._get_database_display_str(verbosity, target_database_name), )) try: os.remove(target_database_name) except Exception as e: sys.stderr.write("Got an error deleting the old test database: %s\n" % e) sys.exit(2) try: shutil.copy(source_database_name, target_database_name) except Exception as e: sys.stderr.write("Got an error cloning the test database: %s\n" % e) sys.exit(2) def _destroy_test_db(self, test_database_name, verbosity): if test_database_name and not self.is_in_memory_db(test_database_name): # Remove the SQLite database file os.remove(test_database_name) def test_db_signature(self): """ Returns a tuple that uniquely identifies a test database. This takes into account the special cases of ":memory:" and "" for SQLite since the databases will be distinct despite having the same TEST NAME. See http://www.sqlite.org/inmemorydb.html """ test_database_name = self._get_test_db_name() sig = [self.connection.settings_dict['NAME']] if self.is_in_memory_db(test_database_name): sig.append(self.connection.alias) return tuple(sig)
mit
3,775,330,401,011,207,000
42.938053
97
0.576636
false
greenoaktree/MissionPlanner
Lib/sysconfig.py
42
25982
"""Provide access to Python's configuration information. """ import sys import os from os.path import pardir, realpath _INSTALL_SCHEMES = { 'posix_prefix': { 'stdlib': '{base}/lib/python{py_version_short}', 'platstdlib': '{platbase}/lib/python{py_version_short}', 'purelib': '{base}/lib/python{py_version_short}/site-packages', 'platlib': '{platbase}/lib/python{py_version_short}/site-packages', 'include': '{base}/include/python{py_version_short}', 'platinclude': '{platbase}/include/python{py_version_short}', 'scripts': '{base}/bin', 'data': '{base}', }, 'posix_home': { 'stdlib': '{base}/lib/python', 'platstdlib': '{base}/lib/python', 'purelib': '{base}/lib/python', 'platlib': '{base}/lib/python', 'include': '{base}/include/python', 'platinclude': '{base}/include/python', 'scripts': '{base}/bin', 'data' : '{base}', }, 'nt': { 'stdlib': '{base}/Lib', 'platstdlib': '{base}/Lib', 'purelib': '{base}/Lib/site-packages', 'platlib': '{base}/Lib/site-packages', 'include': '{base}/Include', 'platinclude': '{base}/Include', 'scripts': '{base}/Scripts', 'data' : '{base}', }, 'os2': { 'stdlib': '{base}/Lib', 'platstdlib': '{base}/Lib', 'purelib': '{base}/Lib/site-packages', 'platlib': '{base}/Lib/site-packages', 'include': '{base}/Include', 'platinclude': '{base}/Include', 'scripts': '{base}/Scripts', 'data' : '{base}', }, 'os2_home': { 'stdlib': '{userbase}/lib/python{py_version_short}', 'platstdlib': '{userbase}/lib/python{py_version_short}', 'purelib': '{userbase}/lib/python{py_version_short}/site-packages', 'platlib': '{userbase}/lib/python{py_version_short}/site-packages', 'include': '{userbase}/include/python{py_version_short}', 'scripts': '{userbase}/bin', 'data' : '{userbase}', }, 'nt_user': { 'stdlib': '{userbase}/IronPython{py_version_nodot}', 'platstdlib': '{userbase}/IronPython{py_version_nodot}', 'purelib': '{userbase}/IronPython{py_version_nodot}/site-packages', 'platlib': '{userbase}/IronPython{py_version_nodot}/site-packages', 'include': '{userbase}/IronPython{py_version_nodot}/Include', 'scripts': '{userbase}/Scripts', 'data' : '{userbase}', }, 'posix_user': { 'stdlib': '{userbase}/lib/python{py_version_short}', 'platstdlib': '{userbase}/lib/python{py_version_short}', 'purelib': '{userbase}/lib/python{py_version_short}/site-packages', 'platlib': '{userbase}/lib/python{py_version_short}/site-packages', 'include': '{userbase}/include/python{py_version_short}', 'scripts': '{userbase}/bin', 'data' : '{userbase}', }, 'osx_framework_user': { 'stdlib': '{userbase}/lib/python', 'platstdlib': '{userbase}/lib/python', 'purelib': '{userbase}/lib/python/site-packages', 'platlib': '{userbase}/lib/python/site-packages', 'include': '{userbase}/include', 'scripts': '{userbase}/bin', 'data' : '{userbase}', }, } _SCHEME_KEYS = ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include', 'scripts', 'data') _PY_VERSION = sys.version.split()[0] _PY_VERSION_SHORT = sys.version[:3] _PY_VERSION_SHORT_NO_DOT = _PY_VERSION[0] + _PY_VERSION[2] _PREFIX = os.path.normpath(sys.prefix) _EXEC_PREFIX = os.path.normpath(sys.exec_prefix) _CONFIG_VARS = None _USER_BASE = None def _safe_realpath(path): try: return realpath(path) except OSError: return path if sys.executable: _PROJECT_BASE = os.path.dirname(_safe_realpath(sys.executable)) else: # sys.executable can be empty if argv[0] has been changed and Python is # unable to retrieve the real program name _PROJECT_BASE = _safe_realpath(os.getcwd()) if os.name == "nt" and "pcbuild" in _PROJECT_BASE[-8:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir)) # PC/VS7.1 if os.name == "nt" and "\\pc\\v" in _PROJECT_BASE[-10:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir)) # PC/AMD64 if os.name == "nt" and "\\pcbuild\\amd64" in _PROJECT_BASE[-14:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir)) def is_python_build(): for fn in ("Setup.dist", "Setup.local"): if os.path.isfile(os.path.join(_PROJECT_BASE, "Modules", fn)): return True return False _PYTHON_BUILD = is_python_build() if _PYTHON_BUILD: for scheme in ('posix_prefix', 'posix_home'): _INSTALL_SCHEMES[scheme]['include'] = '{projectbase}/Include' _INSTALL_SCHEMES[scheme]['platinclude'] = '{srcdir}' def _subst_vars(s, local_vars): try: return s.format(**local_vars) except KeyError: try: return s.format(**os.environ) except KeyError, var: raise AttributeError('{%s}' % var) def _extend_dict(target_dict, other_dict): target_keys = target_dict.keys() for key, value in other_dict.items(): if key in target_keys: continue target_dict[key] = value def _expand_vars(scheme, vars): res = {} if vars is None: vars = {} _extend_dict(vars, get_config_vars()) for key, value in _INSTALL_SCHEMES[scheme].items(): if os.name in ('posix', 'nt'): value = os.path.expanduser(value) res[key] = os.path.normpath(_subst_vars(value, vars)) return res def _get_default_scheme(): if sys.platform == 'cli': return 'nt' if os.name == 'posix': # the default scheme for posix is posix_prefix return 'posix_prefix' return os.name def _getuserbase(): env_base = os.environ.get("IRONPYTHONUSERBASE", None) def joinuser(*args): return os.path.expanduser(os.path.join(*args)) # what about 'os2emx', 'riscos' ? if os.name == "nt": base = os.environ.get("APPDATA") or "~" return env_base if env_base else joinuser(base, "Python") if sys.platform == "darwin": framework = get_config_var("PYTHONFRAMEWORK") if framework: return joinuser("~", "Library", framework, "%d.%d"%( sys.version_info[:2])) return env_base if env_base else joinuser("~", ".local") def _parse_makefile(filename, vars=None): """Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ import re # Regexes needed for parsing Makefile (and similar syntaxes, # like old-style Setup files). _variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)") _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") if vars is None: vars = {} done = {} notdone = {} with open(filename) as f: lines = f.readlines() for line in lines: if line.startswith('#') or line.strip() == '': continue m = _variable_rx.match(line) if m: n, v = m.group(1, 2) v = v.strip() # `$$' is a literal `$' in make tmpv = v.replace('$$', '') if "$" in tmpv: notdone[n] = v else: try: v = int(v) except ValueError: # insert literal `$' done[n] = v.replace('$$', '$') else: done[n] = v # do variable interpolation here while notdone: for name in notdone.keys(): value = notdone[name] m = _findvar1_rx.search(value) or _findvar2_rx.search(value) if m: n = m.group(1) found = True if n in done: item = str(done[n]) elif n in notdone: # get it on a subsequent round found = False elif n in os.environ: # do it like make: fall back to environment item = os.environ[n] else: done[n] = item = "" if found: after = value[m.end():] value = value[:m.start()] + item + after if "$" in after: notdone[name] = value else: try: value = int(value) except ValueError: done[name] = value.strip() else: done[name] = value del notdone[name] else: # bogus variable reference; just drop it since we can't deal del notdone[name] # strip spurious spaces for k, v in done.items(): if isinstance(v, str): done[k] = v.strip() # save the results in the global dictionary vars.update(done) return vars def _get_makefile_filename(): if _PYTHON_BUILD: return os.path.join(_PROJECT_BASE, "Makefile") return os.path.join(get_path('platstdlib'), "config", "Makefile") def _init_posix(vars): """Initialize the module as appropriate for POSIX systems.""" # load the installed Makefile: makefile = _get_makefile_filename() try: _parse_makefile(makefile, vars) except IOError, e: msg = "invalid Python installation: unable to open %s" % makefile if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # load the installed pyconfig.h: config_h = get_config_h_filename() try: with open(config_h) as f: parse_config_h(f, vars) except IOError, e: msg = "invalid Python installation: unable to open %s" % config_h if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if _PYTHON_BUILD: vars['LDSHARED'] = vars['BLDSHARED'] def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # set basic install directories vars['LIBDEST'] = get_path('stdlib') vars['BINLIBDEST'] = get_path('platstdlib') vars['INCLUDEPY'] = get_path('include') vars['SO'] = '.pyd' vars['EXE'] = '.exe' vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable)) # # public APIs # def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ import re if vars is None: vars = {} define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n") while True: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = int(v) except ValueError: pass vars[n] = v else: m = undef_rx.match(line) if m: vars[m.group(1)] = 0 return vars def get_config_h_filename(): """Returns the path of pyconfig.h.""" if _PYTHON_BUILD: if os.name == "nt": inc_dir = os.path.join(_PROJECT_BASE, "PC") else: inc_dir = _PROJECT_BASE else: inc_dir = get_path('platinclude') return os.path.join(inc_dir, 'pyconfig.h') def get_scheme_names(): """Returns a tuple containing the schemes names.""" schemes = _INSTALL_SCHEMES.keys() schemes.sort() return tuple(schemes) def get_path_names(): """Returns a tuple containing the paths names.""" return _SCHEME_KEYS def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): """Returns a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. """ if expand: return _expand_vars(scheme, vars) else: return _INSTALL_SCHEMES[scheme] def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True): """Returns a path corresponding to the scheme. ``scheme`` is the install scheme name. """ return get_paths(scheme, vars, expand)[name] def get_config_vars(*args): """With no arguments, return a dictionary of all configuration variables relevant for the current platform. On Unix, this means every variable defined in Python's installed Makefile; On Windows and Mac OS it's a much smaller set. With arguments, return a list of values that result from looking up each argument in the configuration variable dictionary. """ import re global _CONFIG_VARS if _CONFIG_VARS is None: _CONFIG_VARS = {} # Normalized versions of prefix and exec_prefix are handy to have; # in fact, these are the standard versions used most places in the # Distutils. _CONFIG_VARS['prefix'] = _PREFIX _CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX _CONFIG_VARS['py_version'] = _PY_VERSION _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT _CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2] _CONFIG_VARS['base'] = _PREFIX _CONFIG_VARS['platbase'] = _EXEC_PREFIX _CONFIG_VARS['projectbase'] = _PROJECT_BASE if os.name in ('nt', 'os2') or sys.platform == 'cli': _init_non_posix(_CONFIG_VARS) elif os.name == 'posix': _init_posix(_CONFIG_VARS) # Setting 'userbase' is done below the call to the # init function to enable using 'get_config_var' in # the init-function. _CONFIG_VARS['userbase'] = _getuserbase() if 'srcdir' not in _CONFIG_VARS: _CONFIG_VARS['srcdir'] = _PROJECT_BASE # Convert srcdir into an absolute path if it appears necessary. # Normally it is relative to the build directory. However, during # testing, for example, we might be running a non-installed python # from a different directory. if _PYTHON_BUILD and os.name == "posix": base = _PROJECT_BASE try: cwd = os.getcwd() except OSError: cwd = None if (not os.path.isabs(_CONFIG_VARS['srcdir']) and base != cwd): # srcdir is relative and we are not in the same directory # as the executable. Assume executable is in the build # directory and make srcdir absolute. srcdir = os.path.join(base, _CONFIG_VARS['srcdir']) _CONFIG_VARS['srcdir'] = os.path.normpath(srcdir) if sys.platform == 'darwin': kernel_version = os.uname()[2] # Kernel version (8.4.3) major_version = int(kernel_version.split('.')[0]) if major_version < 8: # On Mac OS X before 10.4, check if -arch and -isysroot # are in CFLAGS or LDFLAGS and remove them if they are. # This is needed when building extensions on a 10.3 system # using a universal build of python. for key in ('LDFLAGS', 'BASECFLAGS', # a number of derived variables. These need to be # patched up as well. 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'): flags = _CONFIG_VARS[key] flags = re.sub('-arch\s+\w+\s', ' ', flags) flags = re.sub('-isysroot [^ \t]*', ' ', flags) _CONFIG_VARS[key] = flags else: # Allow the user to override the architecture flags using # an environment variable. # NOTE: This name was introduced by Apple in OSX 10.5 and # is used by several scripting languages distributed with # that OS release. if 'ARCHFLAGS' in os.environ: arch = os.environ['ARCHFLAGS'] for key in ('LDFLAGS', 'BASECFLAGS', # a number of derived variables. These need to be # patched up as well. 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'): flags = _CONFIG_VARS[key] flags = re.sub('-arch\s+\w+\s', ' ', flags) flags = flags + ' ' + arch _CONFIG_VARS[key] = flags # If we're on OSX 10.5 or later and the user tries to # compiles an extension using an SDK that is not present # on the current machine it is better to not use an SDK # than to fail. # # The major usecase for this is users using a Python.org # binary installer on OSX 10.6: that installer uses # the 10.4u SDK, but that SDK is not installed by default # when you install Xcode. # CFLAGS = _CONFIG_VARS.get('CFLAGS', '') m = re.search('-isysroot\s+(\S+)', CFLAGS) if m is not None: sdk = m.group(1) if not os.path.exists(sdk): for key in ('LDFLAGS', 'BASECFLAGS', # a number of derived variables. These need to be # patched up as well. 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'): flags = _CONFIG_VARS[key] flags = re.sub('-isysroot\s+\S+(\s|$)', ' ', flags) _CONFIG_VARS[key] = flags if args: vals = [] for name in args: vals.append(_CONFIG_VARS.get(name)) return vals else: return _CONFIG_VARS def get_config_var(name): """Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name) """ return get_config_vars().get(name) def get_platform(): """Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; eg. for IRIX the architecture isn't particularly important (IRIX only runs on SGI hardware), but for Linux the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u irix-5.3 irix64-6.2 Windows will return one of: win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win-ia64 (64bit Windows on Itanium) win32 (all others - specifically, sys.platform is returned) For other non-POSIX platforms, currently just returns 'sys.platform'. """ import re if os.name == 'nt': # sniff sys.version for architecture. prefix = " bit (" i = sys.version.find(prefix) if i == -1: return sys.platform j = sys.version.find(")", i) look = sys.version[i+len(prefix):j].lower() if look == 'amd64': return 'win-amd64' if look == 'itanium': return 'win-ia64' return sys.platform if os.name != "posix" or not hasattr(os, 'uname'): # XXX what about the architecture? NT is Intel or Alpha, # Mac OS is M68k or PPC, etc. return sys.platform # Try to distinguish various flavours of Unix osname, host, release, version, machine = os.uname() # Convert the OS name to lowercase, remove '/' characters # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh") osname = osname.lower().replace('/', '') machine = machine.replace(' ', '_') machine = machine.replace('/', '-') if osname[:5] == "linux": # At least on Linux/Intel, 'machine' is the processor -- # i386, etc. # XXX what about Alpha, SPARC, etc? return "%s-%s" % (osname, machine) elif osname[:5] == "sunos": if release[0] >= "5": # SunOS 5 == Solaris 2 osname = "solaris" release = "%d.%s" % (int(release[0]) - 3, release[2:]) # fall through to standard osname-release-machine representation elif osname[:4] == "irix": # could be "irix64"! return "%s-%s" % (osname, release) elif osname[:3] == "aix": return "%s-%s.%s" % (osname, version, release) elif osname[:6] == "cygwin": osname = "cygwin" rel_re = re.compile (r'[\d.]+') m = rel_re.match(release) if m: release = m.group() elif osname[:6] == "darwin": # # For our purposes, we'll assume that the system version from # distutils' perspective is what MACOSX_DEPLOYMENT_TARGET is set # to. This makes the compatibility story a bit more sane because the # machine is going to compile and link as if it were # MACOSX_DEPLOYMENT_TARGET. cfgvars = get_config_vars() macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET') if 1: # Always calculate the release of the running machine, # needed to determine if we can build fat binaries or not. macrelease = macver # Get the system version. Reading this plist is a documented # way to get the system version (see the documentation for # the Gestalt Manager) try: f = open('/System/Library/CoreServices/SystemVersion.plist') except IOError: # We're on a plain darwin box, fall back to the default # behaviour. pass else: try: m = re.search( r'<key>ProductUserVisibleVersion</key>\s*' + r'<string>(.*?)</string>', f.read()) if m is not None: macrelease = '.'.join(m.group(1).split('.')[:2]) # else: fall back to the default behaviour finally: f.close() if not macver: macver = macrelease if macver: release = macver osname = "macosx" if (macrelease + '.') >= '10.4.' and \ '-arch' in get_config_vars().get('CFLAGS', '').strip(): # The universal build will build fat binaries, but not on # systems before 10.4 # # Try to detect 4-way universal builds, those have machine-type # 'universal' instead of 'fat'. machine = 'fat' cflags = get_config_vars().get('CFLAGS') archs = re.findall('-arch\s+(\S+)', cflags) archs = tuple(sorted(set(archs))) if len(archs) == 1: machine = archs[0] elif archs == ('i386', 'ppc'): machine = 'fat' elif archs == ('i386', 'x86_64'): machine = 'intel' elif archs == ('i386', 'ppc', 'x86_64'): machine = 'fat3' elif archs == ('ppc64', 'x86_64'): machine = 'fat64' elif archs == ('i386', 'ppc', 'ppc64', 'x86_64'): machine = 'universal' else: raise ValueError( "Don't know machine value for archs=%r"%(archs,)) elif machine == 'i386': # On OSX the machine type returned by uname is always the # 32-bit variant, even if the executable architecture is # the 64-bit variant if sys.maxint >= 2**32: machine = 'x86_64' elif machine in ('PowerPC', 'Power_Macintosh'): # Pick a sane name for the PPC architecture. # See 'i386' case if sys.maxint >= 2**32: machine = 'ppc64' else: machine = 'ppc' return "%s-%s-%s" % (osname, release, machine) def get_python_version(): return _PY_VERSION_SHORT
gpl-3.0
4,023,357,260,781,965,000
35.709724
79
0.524132
false
marcoantoniooliveira/labweb
oscar/lib/python2.7/site-packages/debug_toolbar/panels/sql/forms.py
36
2784
from __future__ import absolute_import, unicode_literals import json import hashlib from django import forms from django.conf import settings from django.db import connections from django.utils.encoding import force_text from django.utils.functional import cached_property from django.core.exceptions import ValidationError from debug_toolbar.panels.sql.utils import reformat_sql class SQLSelectForm(forms.Form): """ Validate params sql: The sql statement with interpolated params raw_sql: The sql statement with placeholders params: JSON encoded parameter values duration: time for SQL to execute passed in from toolbar just for redisplay hash: the hash of (secret + sql + params) for tamper checking """ sql = forms.CharField() raw_sql = forms.CharField() params = forms.CharField() alias = forms.CharField(required=False, initial='default') duration = forms.FloatField() hash = forms.CharField() def __init__(self, *args, **kwargs): initial = kwargs.get('initial', None) if initial is not None: initial['hash'] = self.make_hash(initial) super(SQLSelectForm, self).__init__(*args, **kwargs) for name in self.fields: self.fields[name].widget = forms.HiddenInput() def clean_raw_sql(self): value = self.cleaned_data['raw_sql'] if not value.lower().strip().startswith('select'): raise ValidationError("Only 'select' queries are allowed.") return value def clean_params(self): value = self.cleaned_data['params'] try: return json.loads(value) except ValueError: raise ValidationError('Is not valid JSON') def clean_alias(self): value = self.cleaned_data['alias'] if value not in connections: raise ValidationError("Database alias '%s' not found" % value) return value def clean_hash(self): hash = self.cleaned_data['hash'] if hash != self.make_hash(self.data): raise ValidationError('Tamper alert') return hash def reformat_sql(self): return reformat_sql(self.cleaned_data['sql']) def make_hash(self, data): items = [settings.SECRET_KEY, data['sql'], data['params']] # Replace lines endings with spaces to preserve the hash value # even when the browser normalizes \r\n to \n in inputs. items = [' '.join(force_text(item).splitlines()) for item in items] return hashlib.sha1(''.join(items).encode('utf-8')).hexdigest() @property def connection(self): return connections[self.cleaned_data['alias']] @cached_property def cursor(self): return self.connection.cursor()
bsd-3-clause
-2,574,129,591,306,319,400
29.26087
83
0.64727
false
2asoft/tdesktop
Telegram/build/release.py
4
7388
import os, sys, requests, pprint, re, json from uritemplate import URITemplate, expand from subprocess import call changelog_file = '../../changelog.txt' token_file = '../../../TelegramPrivate/github-releases-token.txt' version = '' commit = '' for arg in sys.argv: if re.match(r'\d+\.\d+', arg): version = arg elif re.match(r'^[a-f0-9]{40}$', arg): commit = arg # thanks http://stackoverflow.com/questions/13909900/progress-of-python-requests-post class upload_in_chunks(object): def __init__(self, filename, chunksize=1 << 13): self.filename = filename self.chunksize = chunksize self.totalsize = os.path.getsize(filename) self.readsofar = 0 def __iter__(self): with open(self.filename, 'rb') as file: while True: data = file.read(self.chunksize) if not data: sys.stderr.write("\n") break self.readsofar += len(data) percent = self.readsofar * 1e2 / self.totalsize sys.stderr.write("\r{percent:3.0f}%".format(percent=percent)) yield data def __len__(self): return self.totalsize class IterableToFileAdapter(object): def __init__(self, iterable): self.iterator = iter(iterable) self.length = len(iterable) def read(self, size=-1): # TBD: add buffer for `len(data) > size` case return next(self.iterator, b'') def __len__(self): return self.length def checkResponseCode(result, right_code): if (result.status_code != right_code): print('Wrong result code: ' + str(result.status_code) + ', should be ' + str(right_code)) sys.exit(1) pp = pprint.PrettyPrinter(indent=2) url = 'https://api.github.com/' version_parts = version.split('.') stable = 1 alpha = 0 dev = 0 if len(version_parts) < 2: print('Error: expected at least major version ' + version) sys.exit(1) if len(version_parts) > 4: print('Error: bad version passed ' + version) sys.exit(1) version_major = version_parts[0] + '.' + version_parts[1] if len(version_parts) == 2: version = version_major + '.0' version_full = version else: version = version_major + '.' + version_parts[2] version_full = version if len(version_parts) == 4: if version_parts[3] == 'dev': dev = 1 stable = 0 version_full = version + '.dev' elif version_parts[3] == 'alpha': alpha = 1 stable = 0 version_full = version + '.alpha' else: print('Error: unexpected version part ' + version_parts[3]) sys.exit(1) access_token = '' if os.path.isfile(token_file): with open(token_file) as f: for line in f: access_token = line.replace('\n', '') if access_token == '': print('Access token not found!') sys.exit(1) print('Version: ' + version_full); local_folder = '/Volumes/Storage/backup/' + version_major + '/' + version_full if stable == 1: if os.path.isdir(local_folder + '.dev'): dev = 1 stable = 0 version_full = version + '.dev' local_folder = local_folder + '.dev' elif os.path.isdir(local_folder + '.alpha'): alpha = 1 stable = 0 version_full = version + '.alpha' local_folder = local_folder + '.alpha' if not os.path.isdir(local_folder): print('Storage path not found!') sys.exit(1) local_folder = local_folder + '/' files = [] files.append({ 'local': 'tsetup.' + version_full + '.exe', 'remote': 'tsetup.' + version_full + '.exe', 'backup_folder': 'tsetup', 'mime': 'application/octet-stream', 'label': 'Windows: Installer', }) files.append({ 'local': 'tportable.' + version_full + '.zip', 'remote': 'tportable.' + version_full + '.zip', 'backup_folder': 'tsetup', 'mime': 'application/zip', 'label': 'Windows: Portable', }) files.append({ 'local': 'tsetup.' + version_full + '.dmg', 'remote': 'tsetup.' + version_full + '.dmg', 'backup_folder': 'tmac', 'mime': 'application/octet-stream', 'label': 'macOS and OS X 10.8+: Installer', }) files.append({ 'local': 'tsetup32.' + version_full + '.dmg', 'remote': 'tsetup32.' + version_full + '.dmg', 'backup_folder': 'tmac32', 'mime': 'application/octet-stream', 'label': 'OS X 10.6 and 10.7: Installer', }) files.append({ 'local': 'tsetup.' + version_full + '.tar.xz', 'remote': 'tsetup.' + version_full + '.tar.xz', 'backup_folder': 'tlinux', 'mime': 'application/octet-stream', 'label': 'Linux 64 bit: Binary', }) files.append({ 'local': 'tsetup32.' + version_full + '.tar.xz', 'remote': 'tsetup32.' + version_full + '.tar.xz', 'backup_folder': 'tlinux32', 'mime': 'application/octet-stream', 'label': 'Linux 32 bit: Binary', }) r = requests.get(url + 'repos/telegramdesktop/tdesktop/releases/tags/v' + version) if r.status_code == 404: print('Release not found, creating.') if commit == '': print('Error: specify the commit.') sys.exit(1) if not os.path.isfile(changelog_file): print('Error: Changelog file not found.') sys.exit(1) changelog = '' started = 0 with open(changelog_file) as f: for line in f: if started == 1: if re.match(r'^\d+\.\d+', line): break; if re.match(r'^\s+$', line): continue changelog += line else: if re.match(r'^\d+\.\d+', line): if line[0:len(version) + 1] == version + ' ': started = 1 elif line[0:len(version_major) + 1] == version_major + ' ': if version_major + '.0' == version: started = 1 if started != 1: print('Error: Changelog not found.') sys.exit(1) changelog = changelog.strip() print('Changelog: '); print(changelog); r = requests.post(url + 'repos/telegramdesktop/tdesktop/releases', headers={'Authorization': 'token ' + access_token}, data=json.dumps({ 'tag_name': 'v' + version, 'target_commitish': commit, 'name': 'v ' + version, 'body': changelog, 'prerelease': (dev == 1 or alpha == 1), })) checkResponseCode(r, 201) r = requests.get(url + 'repos/telegramdesktop/tdesktop/releases/tags/v' + version) checkResponseCode(r, 200); release_data = r.json() #pp.pprint(release_data) release_id = release_data['id'] print('Release ID: ' + str(release_id)) r = requests.get(url + 'repos/telegramdesktop/tdesktop/releases/' + str(release_id) + '/assets'); checkResponseCode(r, 200); assets = release_data['assets'] for asset in assets: name = asset['name'] found = 0 for file in files: if file['remote'] == name: print('Already uploaded: ' + name) file['already'] = 1 found = 1 break if found == 0: print('Warning: strange asset: ' + name) for file in files: if 'already' in file: continue file_path = local_folder + file['backup_folder'] + '/' + file['local'] if not os.path.isfile(file_path): print('Warning: file not found ' + file['local']) continue upload_url = expand(release_data['upload_url'], {'name': file['remote'], 'label': file['label']}) + '&access_token=' + access_token; content = upload_in_chunks(file_path, 10) print('Uploading: ' + file['remote'] + ' (' + str(round(len(content) / 10000) / 100.) + ' MB)') r = requests.post(upload_url, headers={"Content-Type": file['mime']}, data=IterableToFileAdapter(content)) checkResponseCode(r, 201) print('Success! Removing.') return_code = call(["rm", file_path]) if return_code != 0: print('Bad rm code: ' + str(return_code)) sys.exit(1) sys.exit()
gpl-3.0
-4,684,818,419,198,945,000
27.859375
138
0.614781
false
UASLab/ImageAnalysis
video/hud.py
1
43557
import datetime import ephem # dnf install python3-pyephem import math import navpy import numpy as np # find our custom built opencv first import sys sys.path.insert(0, "/usr/local/opencv3/lib/python2.7/site-packages/") import cv2 sys.path.append('../scripts') from lib import transformations import airports # helpful constants d2r = math.pi / 180.0 r2d = 180.0 / math.pi mps2kt = 1.94384 kt2mps = 1 / mps2kt ft2m = 0.3048 m2ft = 1 / ft2m # color definitions green2 = (0, 238, 0) red2 = (0, 0, 238) medium_orchid = (186, 85, 211) yellow = (50, 255, 255) white = (255, 255, 255) class HUD: def __init__(self, K): self.K = K self.PROJ = None self.cam_yaw = 0.0 self.cam_pitch = 0.0 self.cam_roll = 0.0 self.line_width = 1 self.color = green2 self.font = cv2.FONT_HERSHEY_SIMPLEX self.font_size = 0.6 self.render_w = 0 self.render_h = 0 self.lla = [0.0, 0.0, 0.0] self.time = 0 self.unixtime = 0 self.ned = [0.0, 0.0, 0.0] self.ned_history = [] self.ned_last_time = 0.0 self.grid = [] self.ref = None self.vn = 0.0 self.ve = 0.0 self.vd = 0.0 self.vel_filt = [0.0, 0.0, 0.0] self.phi_rad = 0 self.the_rad = 0 self.psi_rad = 0 self.frame = None self.airspeed_units = 'kt' self.altitude_units = 'ft' self.airspeed_kt = 0 self.altitude_m = 0 self.ground_m = 0 self.flight_mode = 'none' self.ap_roll = 0 self.ap_pitch = 0 self.ap_hdg = 0 self.ap_speed = 0 self.ap_altitude_ft = 0 self.alpha_rad = 0 self.beta_rad = 0 self.filter_vn = 0.0 self.filter_ve = 0.0 self.tf_vel = 0.5 self.pilot_ail = 0.0 self.pilot_ele = 0.0 self.pilot_thr = 0.0 self.pilot_rud = 0.0 self.act_ail = 0.0 self.act_ele = 0.0 self.act_thr = 0.0 self.act_rud = 0.0 self.airports = [] self.features = [] def set_render_size(self, w, h): self.render_w = w self.render_h = h def set_line_width(self, line_width): self.line_width = line_width if self.line_width < 1: self.line_width = 1 def set_color(self, color): self.color = color def set_font_size(self, font_size): self.font_size = font_size if self.font_size < 0.4: self.font_size = 0.4 def set_units(self, airspeed_units, altitude_units): self.airspeed_units = airspeed_units self.altitude_units = altitude_units def set_ned_ref(self, lat, lon): self.ref = [ lat, lon, 0.0] def load_airports(self): if self.ref: self.airports = airports.load('apt.csv', self.ref, 30000) else: print('no ned ref set, unable to load nearby airports.') def set_ground_m(self, ground_m): self.ground_m = ground_m def update_frame(self, frame): self.frame = frame def update_lla(self, lla): self.lla = lla def update_time(self, time, unixtime): self.time = time self.unixtime = unixtime def update_test_index(self, mode, index): self.excite_mode = mode self.test_index = index def update_ned_history(self, ned, seconds): if int(self.time) > self.ned_last_time: self.ned_last_time = int(self.time) self.ned_history.append(ned) while len(self.ned_history) > seconds: self.ned_history.pop(0) def update_ned(self, ned, seconds): self.ned = ned[:] self.update_ned_history(ned, seconds) def update_features(self, feature_list): self.features = feature_list def update_proj(self, PROJ): self.PROJ = PROJ def update_cam_att(self, cam_yaw, cam_pitch, cam_roll): self.cam_yaw = cam_yaw self.cam_pitch = cam_pitch self.cam_roll = cam_roll def update_vel(self, vn, ve, vd): self.vn = vn self.ve = ve self.vd = vd def update_att_rad(self, phi_rad, the_rad, psi_rad): self.phi_rad = phi_rad self.the_rad = the_rad self.psi_rad = psi_rad def update_airdata(self, airspeed_kt, altitude_m, alpha_rad=0, beta_rad=0): self.airspeed_kt = airspeed_kt self.altitude_m = altitude_m self.alpha_rad = alpha_rad self.beta_rad = beta_rad def update_ap(self, flight_mode, ap_roll, ap_pitch, ap_hdg, ap_speed, ap_altitude_ft): self.flight_mode = flight_mode self.ap_roll = ap_roll self.ap_pitch = ap_pitch self.ap_hdg = ap_hdg self.ap_speed = ap_speed self.ap_altitude_ft = ap_altitude_ft def update_pilot(self, aileron, elevator, throttle, rudder): self.pilot_ail = aileron self.pilot_ele = elevator self.pilot_thr = throttle self.pilot_rud = rudder def update_act(self, aileron, elevator, throttle, rudder): self.act_ail = aileron self.act_ele = elevator self.act_thr = throttle self.act_rud = rudder def compute_sun_moon_ned(self, lon_deg, lat_deg, alt_m, timestamp): d = datetime.datetime.utcfromtimestamp(timestamp) #d = datetime.datetime.utcnow() ed = ephem.Date(d) #print 'ephem time utc:', ed #print 'localtime:', ephem.localtime(ed) ownship = ephem.Observer() ownship.lon = '%.8f' % lon_deg ownship.lat = '%.8f' % lat_deg ownship.elevation = alt_m ownship.date = ed sun = ephem.Sun(ownship) moon = ephem.Moon(ownship) sun_ned = [ math.cos(sun.az) * math.cos(sun.alt), math.sin(sun.az) * math.cos(sun.alt), -math.sin(sun.alt) ] moon_ned = [ math.cos(moon.az) * math.cos(moon.alt), math.sin(moon.az) * math.cos(moon.alt), -math.sin(moon.alt) ] return sun_ned, moon_ned def project_point(self, ned): uvh = self.K.dot( self.PROJ.dot( [ned[0], ned[1], ned[2], 1.0] ).T ) if uvh[2] > 0.2: uvh /= uvh[2] uv = ( int(np.squeeze(uvh[0,0])), int(np.squeeze(uvh[1,0])) ) return uv else: return None def draw_horizon(self): divs = 10 pts = [] for i in range(divs + 1): a = (float(i) * 360/float(divs)) * d2r n = math.cos(a) e = math.sin(a) d = 0.0 pts.append( [n, e, d] ) for i in range(divs): p1 = pts[i] p2 = pts[i+1] uv1 = self.project_point( [self.ned[0] + p1[0], self.ned[1] + p1[1], self.ned[2] + p1[2]] ) uv2 = self.project_point( [self.ned[0] + p2[0], self.ned[1] + p2[1], self.ned[2] + p2[2]] ) if uv1 != None and uv2 != None: cv2.line(self.frame, uv1, uv2, self.color, self.line_width, cv2.LINE_AA) def ladder_helper(self, q0, a0, a1): q1 = transformations.quaternion_from_euler(-a1*d2r, -a0*d2r, 0.0, 'rzyx') q = transformations.quaternion_multiply(q1, q0) v = transformations.quaternion_transform(q, [1.0, 0.0, 0.0]) uv = self.project_point( [self.ned[0] + v[0], self.ned[1] + v[1], self.ned[2] + v[2]] ) return uv def draw_pitch_ladder(self, beta_rad=0.0): a1 = 2.0 a2 = 8.0 #slide_rad = self.psi_rad - beta_rad slide_rad = self.psi_rad q0 = transformations.quaternion_about_axis(slide_rad, [0.0, 0.0, -1.0]) for a0 in range(5,35,5): # above horizon # right horizontal uv1 = self.ladder_helper(q0, a0, a1) uv2 = self.ladder_helper(q0, a0, a2) if uv1 != None and uv2 != None: cv2.line(self.frame, uv1, uv2, self.color, self.line_width, cv2.LINE_AA) du = uv2[0] - uv1[0] dv = uv2[1] - uv1[1] uv = ( uv1[0] + int(1.25*du), uv1[1] + int(1.25*dv) ) self.draw_label("%d" % a0, uv, self.font_size, self.line_width) # right tick uv1 = self.ladder_helper(q0, a0-0.5, a1) uv2 = self.ladder_helper(q0, a0, a1) if uv1 != None and uv2 != None: cv2.line(self.frame, uv1, uv2, self.color, self.line_width, cv2.LINE_AA) # left horizontal uv1 = self.ladder_helper(q0, a0, -a1) uv2 = self.ladder_helper(q0, a0, -a2) if uv1 != None and uv2 != None: cv2.line(self.frame, uv1, uv2, self.color, self.line_width, cv2.LINE_AA) du = uv2[0] - uv1[0] dv = uv2[1] - uv1[1] uv = ( uv1[0] + int(1.25*du), uv1[1] + int(1.25*dv) ) self.draw_label("%d" % a0, uv, self.font_size, self.line_width) # left tick uv1 = self.ladder_helper(q0, a0-0.5, -a1) uv2 = self.ladder_helper(q0, a0, -a1) if uv1 != None and uv2 != None: cv2.line(self.frame, uv1, uv2, self.color, self.line_width, cv2.LINE_AA) # below horizon # right horizontal uv1 = self.ladder_helper(q0, -a0, a1) uv2 = self.ladder_helper(q0, -a0-0.5, a2) if uv1 != None and uv2 != None: du = uv2[0] - uv1[0] dv = uv2[1] - uv1[1] for i in range(0,3): tmp1 = (uv1[0] + int(0.375*i*du), uv1[1] + int(0.375*i*dv)) tmp2 = (tmp1[0] + int(0.25*du), tmp1[1] + int(0.25*dv)) cv2.line(self.frame, tmp1, tmp2, self.color, self.line_width, cv2.LINE_AA) uv = ( uv1[0] + int(1.25*du), uv1[1] + int(1.25*dv) ) self.draw_label("%d" % a0, uv, self.font_size, self.line_width) # right tick uv1 = self.ladder_helper(q0, -a0+0.5, a1) uv2 = self.ladder_helper(q0, -a0, a1) if uv1 != None and uv2 != None: cv2.line(self.frame, uv1, uv2, self.color, self.line_width, cv2.LINE_AA) # left horizontal uv1 = self.ladder_helper(q0, -a0, -a1) uv2 = self.ladder_helper(q0, -a0-0.5, -a2) if uv1 != None and uv2 != None: du = uv2[0] - uv1[0] dv = uv2[1] - uv1[1] for i in range(0,3): tmp1 = (uv1[0] + int(0.375*i*du), uv1[1] + int(0.375*i*dv)) tmp2 = (tmp1[0] + int(0.25*du), tmp1[1] + int(0.25*dv)) cv2.line(self.frame, tmp1, tmp2, self.color, self.line_width, cv2.LINE_AA) uv = ( uv1[0] + int(1.25*du), uv1[1] + int(1.25*dv) ) self.draw_label("%d" % a0, uv, self.font_size, self.line_width) # left tick uv1 = self.ladder_helper(q0, -a0+0.5, -a1) uv2 = self.ladder_helper(q0, -a0, -a1) if uv1 != None and uv2 != None: cv2.line(self.frame, uv1, uv2, self.color, self.line_width, cv2.LINE_AA) def draw_alpha_beta_marker(self): if self.alpha_rad == None or self.beta_rad == None: return q0 = transformations.quaternion_about_axis(self.psi_rad, [0.0, 0.0, -1.0]) a0 = self.the_rad * r2d center = self.ladder_helper(q0, a0, 0.0) alpha = self.alpha_rad * r2d beta = self.beta_rad * r2d tmp = self.ladder_helper(q0, a0-alpha, beta) if tmp != None: uv = self.rotate_pt(tmp, center, self.phi_rad) if uv != None: r1 = int(round(self.render_h / 60)) r2 = int(round(self.render_h / 30)) uv1 = (uv[0]+r1, uv[1]) uv2 = (uv[0]+r2, uv[1]) uv3 = (uv[0]-r1, uv[1]) uv4 = (uv[0]-r2, uv[1]) uv5 = (uv[0], uv[1]-r1) uv6 = (uv[0], uv[1]-r2) cv2.circle(self.frame, uv, r1, self.color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv1, uv2, self.color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv3, uv4, self.color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv5, uv6, self.color, self.line_width, cv2.LINE_AA) def rotate_pt(self, p, center, a): #print p, center x = math.cos(a) * (p[0]-center[0]) - math.sin(a) * (p[1]-center[1]) + center[0] y = math.sin(a) * (p[0]-center[0]) + math.cos(a) * (p[1]-center[1]) + center[1] return (int(x), int(y)) def draw_vbars(self): color = medium_orchid size = self.line_width a1 = 10.0 a2 = 1.5 a3 = 3.0 q0 = transformations.quaternion_about_axis(self.psi_rad, [0.0, 0.0, -1.0]) a0 = self.ap_pitch # rotation point (about nose) rot = self.ladder_helper(q0, self.the_rad*r2d, 0.0) if rot == None: return # center point tmp1 = self.ladder_helper(q0, a0, 0.0) if tmp1 == None: return center = self.rotate_pt(tmp1, rot, self.ap_roll*d2r) # right vbar tmp1 = self.ladder_helper(q0, a0-a3, a1) tmp2 = self.ladder_helper(q0, a0-a3, a1+a3) tmp3 = self.ladder_helper(q0, a0-a2, a1+a3) if tmp1 != None and tmp2 != None and tmp3 != None: uv1 = self.rotate_pt(tmp1, rot, self.ap_roll*d2r) uv2 = self.rotate_pt(tmp2, rot, self.ap_roll*d2r) uv3 = self.rotate_pt(tmp3, rot, self.ap_roll*d2r) if uv1 != None and uv2 != None and uv3 != None: cv2.line(self.frame, center, uv1, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, center, uv3, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv1, uv3, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv2, uv3, color, self.line_width, cv2.LINE_AA) # left vbar tmp1 = self.ladder_helper(q0, a0-a3, -a1) tmp2 = self.ladder_helper(q0, a0-a3, -a1-a3) tmp3 = self.ladder_helper(q0, a0-a2, -a1-a3) if tmp1 != None and tmp2 != None and tmp3 != None: uv1 = self.rotate_pt(tmp1, rot, self.ap_roll*d2r) uv2 = self.rotate_pt(tmp2, rot, self.ap_roll*d2r) uv3 = self.rotate_pt(tmp3, rot, self.ap_roll*d2r) if uv1 != None and uv2 != None and uv3 != None: cv2.line(self.frame, center, uv1, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, center, uv3, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv1, uv3, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv2, uv3, color, self.line_width, cv2.LINE_AA) def draw_heading_bug(self): color = medium_orchid size = 2 a = math.atan2(self.ve, self.vn) q0 = transformations.quaternion_about_axis(self.ap_hdg*d2r, [0.0, 0.0, -1.0]) center = self.ladder_helper(q0, 0, 0) pts = [] pts.append( self.ladder_helper(q0, 0, 2.0) ) pts.append( self.ladder_helper(q0, 0.0, -2.0) ) pts.append( self.ladder_helper(q0, 1.5, -2.0) ) pts.append( self.ladder_helper(q0, 1.5, -1.0) ) pts.append( center ) pts.append( self.ladder_helper(q0, 1.5, 1.0) ) pts.append( self.ladder_helper(q0, 1.5, 2.0) ) for i, p in enumerate(pts): if p == None or center == None: return cv2.line(self.frame, pts[0], pts[1], color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, pts[1], pts[2], color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, pts[2], pts[3], color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, pts[3], pts[4], color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, pts[4], pts[5], color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, pts[5], pts[6], color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, pts[6], pts[0], color, self.line_width, cv2.LINE_AA) def draw_bird(self): color = yellow size = 2 a1 = 10.0 a2 = 3.0 q0 = transformations.quaternion_about_axis(self.psi_rad, [0.0, 0.0, -1.0]) a0 = self.the_rad*r2d # print 'pitch:', a0, 'ap:', self.ap_pitch # center point center = self.ladder_helper(q0, a0, 0.0) if center == None: return # right vbar tmp1 = self.ladder_helper(q0, a0-a2, a1) tmp2 = self.ladder_helper(q0, a0-a2, a1-a2) if tmp1 != None and tmp2 != None: uv1 = self.rotate_pt(tmp1, center, self.phi_rad) uv2 = self.rotate_pt(tmp2, center, self.phi_rad) if uv1 != None and uv2 != None: cv2.line(self.frame, center, uv1, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, center, uv2, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA) # left vbar tmp1 = self.ladder_helper(q0, a0-a2, -a1) tmp2 = self.ladder_helper(q0, a0-a2, -a1+a2) if tmp1 != None and tmp2 != None: uv1 = self.rotate_pt(tmp1, center, self.phi_rad) uv2 = self.rotate_pt(tmp2, center, self.phi_rad) if uv1 != None and uv2 != None: cv2.line(self.frame, center, uv1, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, center, uv2, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA) def draw_course(self): color = yellow size = 2 self.filter_vn = (1.0 - self.tf_vel) * self.filter_vn + self.tf_vel * self.vn self.filter_ve = (1.0 - self.tf_vel) * self.filter_ve + self.tf_vel * self.ve a = math.atan2(self.filter_ve, self.filter_vn) q0 = transformations.quaternion_about_axis(a, [0.0, 0.0, -1.0]) uv1 = self.ladder_helper(q0, 0, 0) uv2 = self.ladder_helper(q0, 1.5, 1.0) uv3 = self.ladder_helper(q0, 1.5, -1.0) if uv1 != None and uv2 != None and uv3 != None : #uv2 = self.rotate_pt(tmp2, tmp1, -self.cam_roll*d2r) #uv3 = self.rotate_pt(tmp3, tmp1, -self.cam_roll*d2r) cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv1, uv3, color, self.line_width, cv2.LINE_AA) def draw_label(self, label, uv, font_scale, thickness, horiz='center', vert='center'): size = cv2.getTextSize(label, self.font, font_scale, thickness) if horiz == 'center': u = uv[0] - (size[0][0] / 2) else: u = uv[0] if vert == 'above': v = uv[1] elif vert == 'below': v = uv[1] + size[0][1] elif vert == 'center': v = uv[1] + (size[0][1] / 2) uv = (int(u), int(v)) cv2.putText(self.frame, label, uv, self.font, font_scale, self.color, thickness, cv2.LINE_AA) def draw_ned_point(self, ned, label=None, scale=1, vert='above'): uv = self.project_point([ned[0], ned[1], ned[2]]) if uv != None: cv2.circle(self.frame, uv, 4+self.line_width, self.color, self.line_width, cv2.LINE_AA) if label: if vert == 'above': uv = self.project_point([ned[0], ned[1], ned[2] - 0.02]) else: uv = self.project_point([ned[0], ned[1], ned[2] + 0.02]) if uv != None: self.draw_label(label, uv, scale, self.line_width, vert=vert) def draw_lla_point(self, lla, label): pt_ned = navpy.lla2ned( lla[0], lla[1], lla[2], self.ref[0], self.ref[1], self.ref[2] ) rel_ned = [ pt_ned[0] - self.ned[0], pt_ned[1] - self.ned[1], pt_ned[2] - self.ned[2] ] hdist = math.sqrt(rel_ned[0]*rel_ned[0] + rel_ned[1]*rel_ned[1]) dist = math.sqrt(rel_ned[0]*rel_ned[0] + rel_ned[1]*rel_ned[1] + rel_ned[2]*rel_ned[2]) m2sm = 0.000621371 hdist_sm = hdist * m2sm if hdist_sm <= 10.0: scale = 0.7 - (hdist_sm / 10.0) * 0.4 if hdist_sm <= 7.5: label += " (%.1f)" % hdist_sm # normalize, and draw relative to aircraft ned so that label # separation works better rel_ned[0] /= dist rel_ned[1] /= dist rel_ned[2] /= dist self.draw_ned_point([self.ned[0] + rel_ned[0], self.ned[1] + rel_ned[1], self.ned[2] + rel_ned[2]], label, scale=scale, vert='below') def draw_compass_points(self): # 30 Ticks divs = 12 pts = [] for i in range(divs): a = (float(i) * 360/float(divs)) * d2r n = math.cos(a) e = math.sin(a) uv1 = self.project_point([self.ned[0] + n, self.ned[1] + e, self.ned[2] - 0.0]) uv2 = self.project_point([self.ned[0] + n, self.ned[1] + e, self.ned[2] - 0.02]) if uv1 != None and uv2 != None: cv2.line(self.frame, uv1, uv2, self.color, self.line_width, cv2.LINE_AA) # North uv = self.project_point([self.ned[0] + 1.0, self.ned[1] + 0.0, self.ned[2] - 0.03]) if uv != None: self.draw_label('N', uv, 1, self.line_width, vert='above') # South uv = self.project_point([self.ned[0] - 1.0, self.ned[1] + 0.0, self.ned[2] - 0.03]) if uv != None: self.draw_label('S', uv, 1, self.line_width, vert='above') # East uv = self.project_point([self.ned[0] + 0.0, self.ned[1] + 1.0, self.ned[2] - 0.03]) if uv != None: self.draw_label('E', uv, 1, self.line_width, vert='above') # West uv = self.project_point([self.ned[0] + 0.0, self.ned[1] - 1.0, self.ned[2] - 0.03]) if uv != None: self.draw_label('W', uv, 1, self.line_width, vert='above') def draw_astro(self): sun_ned, moon_ned = self.compute_sun_moon_ned(self.lla[1], self.lla[0], self.lla[2], self.unixtime) if sun_ned == None or moon_ned == None: return # Sun self.draw_ned_point([self.ned[0] + sun_ned[0], self.ned[1] + sun_ned[1], self.ned[2] + sun_ned[2]], 'Sun') # shadow (if sun above horizon) if sun_ned[2] < 0.0: self.draw_ned_point([self.ned[0] - sun_ned[0], self.ned[1] - sun_ned[1], self.ned[2] - sun_ned[2]], 'shadow', scale=0.7) # Moon self.draw_ned_point([self.ned[0] + moon_ned[0], self.ned[1] + moon_ned[1], self.ned[2] + moon_ned[2]], 'Moon') def draw_airports(self): for apt in self.airports: self.draw_lla_point([ apt[1], apt[2], apt[3] ], apt[0]) def draw_nose(self): ned2body = transformations.quaternion_from_euler(self.psi_rad, self.the_rad, self.phi_rad, 'rzyx') body2ned = transformations.quaternion_inverse(ned2body) vec = transformations.quaternion_transform(body2ned, [1.0, 0.0, 0.0]) uv = self.project_point([self.ned[0] + vec[0], self.ned[1] + vec[1], self.ned[2]+ vec[2]]) r1 = int(round(self.render_h / 80)) r2 = int(round(self.render_h / 40)) if uv != None: cv2.circle(self.frame, uv, r1, self.color, self.line_width, cv2.LINE_AA) cv2.circle(self.frame, uv, r2, self.color, self.line_width, cv2.LINE_AA) def draw_velocity_vector(self): tf = 0.2 vel = [self.vn, self.ve, self.vd] # filter coding convenience for i in range(3): self.vel_filt[i] = (1.0 - tf) * self.vel_filt[i] + tf * vel[i] uv = self.project_point([self.ned[0] + self.vel_filt[0], self.ned[1] + self.vel_filt[1], self.ned[2] + self.vel_filt[2]]) if uv != None: cv2.circle(self.frame, uv, 4, self.color, 1, cv2.LINE_AA) def draw_speed_tape(self, airspeed, ap_speed, units_label): color = self.color size = 1 pad = 5 + self.line_width*2 h, w, d = self.frame.shape # reference point cy = int(h * 0.5) cx = int(w * 0.2) miny = int(h * 0.2) maxy = int(h - miny) # current airspeed label = "%.0f" % airspeed lsize = cv2.getTextSize(label, self.font, self.font_size, self.line_width) xsize = lsize[0][0] + pad ysize = lsize[0][1] + pad uv = ( int(cx + ysize*0.7), int(cy + lsize[0][1] / 2)) cv2.putText(self.frame, label, uv, self.font, self.font_size, color, self.line_width, cv2.LINE_AA) uv1 = (cx, cy) uv2 = (cx + int(ysize*0.7), int(cy - ysize / 2) ) uv3 = (cx + int(ysize*0.7) + xsize, int(cy - ysize / 2) ) uv4 = (cx + int(ysize*0.7) + xsize, int(cy + ysize / 2 + 1) ) uv5 = (cx + int(ysize*0.7), int(cy + ysize / 2 + 1) ) cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv2, uv3, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv3, uv4, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv4, uv5, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv5, uv1, color, self.line_width, cv2.LINE_AA) # speed tics spacing = lsize[0][1] y = cy - int((0 - airspeed) * spacing) if y < miny: y = miny if y > maxy: y = maxy uv1 = (cx, y) y = cy - int((70 - airspeed) * spacing) if y < miny: y = miny if y > maxy: y = maxy uv2 = (cx, y) cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA) for i in range(0, 65, 1): offset = int((i - airspeed) * spacing) if cy - offset >= miny and cy - offset <= maxy: uv1 = (cx, cy - offset) if i % 5 == 0: uv2 = (cx - 6, cy - offset) else: uv2 = (cx - 4, cy - offset) cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA) for i in range(0, 65, 5): offset = int((i - airspeed) * spacing) if cy - offset >= miny and cy - offset <= maxy: label = "%d" % i lsize = cv2.getTextSize(label, self.font, self.font_size, self.line_width) uv3 = (cx - 8 - lsize[0][0], cy - offset + int(lsize[0][1] / 2)) cv2.putText(self.frame, label, uv3, self.font, self.font_size, color, self.line_width, cv2.LINE_AA) # units lsize = cv2.getTextSize(units_label, self.font, self.font_size, self.line_width) uv = (cx - int(lsize[0][1]*0.5), maxy + lsize[0][1] + self.line_width*2) cv2.putText(self.frame, units_label, uv, self.font, self.font_size, color, self.line_width, cv2.LINE_AA) # speed bug offset = int((ap_speed - airspeed) * spacing) if self.flight_mode == 'auto' and cy - offset >= miny and cy - offset <= maxy: uv1 = (cx, cy - offset) uv2 = (cx + int(ysize*0.7), cy - offset - int(ysize / 2) ) uv3 = (cx + int(ysize*0.7), cy - offset - ysize ) uv4 = (cx, cy - offset - ysize ) uv5 = (cx, cy - offset + ysize ) uv6 = (cx + int(ysize*0.7), cy - offset + ysize ) uv7 = (cx + int(ysize*0.7), cy - offset + int(ysize / 2) ) cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv2, uv3, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv3, uv4, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv4, uv5, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv5, uv6, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv6, uv7, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv7, uv1, color, self.line_width, cv2.LINE_AA) def draw_altitude_tape(self, altitude, ap_alt, units_label): color = self.color size = 1 pad = 5 + self.line_width*2 h, w, d = self.frame.shape # reference point cy = int(h * 0.5) cx = int(w * 0.8) miny = int(h * 0.2) maxy = int(h - miny) minrange = int(altitude/100)*10 - 30 maxrange = int(altitude/100)*10 + 30 # current altitude (computed first so we can size all elements) label = "%.0f" % (round(altitude/10.0) * 10) lsize = cv2.getTextSize(label, self.font, self.font_size, self.line_width) spacing = lsize[0][1] xsize = lsize[0][0] + pad ysize = lsize[0][1] + pad # draw ground if self.altitude_units == 'm': offset = int((self.ground_m - altitude)/10.0 * spacing) else: offset = int((self.ground_m*m2ft - altitude)/10.0 * spacing) if cy - offset >= miny and cy - offset <= maxy: uv1 = (cx, cy - offset) uv2 = (cx + int(ysize*3), cy - offset) cv2.line(self.frame, uv1, uv2, red2, self.line_width*2, cv2.LINE_AA) # draw max altitude if self.altitude_units == 'm': offset = int((self.ground_m + 121.92 - altitude)/10.0 * spacing) else: offset = int((self.ground_m*m2ft + 400.0 - altitude)/10.0 * spacing) if cy - offset >= miny and cy - offset <= maxy: uv1 = (cx, cy - offset) uv2 = (cx + int(ysize*2), cy - offset) cv2.line(self.frame, uv1, uv2, yellow, self.line_width*2, cv2.LINE_AA) # draw current altitude uv = ( int(cx - ysize*0.7 - lsize[0][0]), cy + int(lsize[0][1] / 2)) cv2.putText(self.frame, label, uv, self.font, self.font_size, color, self.line_width, cv2.LINE_AA) uv1 = (cx, cy) uv2 = (cx - int(ysize*0.7), cy - int(ysize / 2) ) uv3 = (cx - int(ysize*0.7) - xsize, cy - int(ysize / 2) ) uv4 = (cx - int(ysize*0.7) - xsize, cy + int(ysize / 2) + 1 ) uv5 = (cx - int(ysize*0.7), cy + int(ysize / 2) + 1 ) cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv2, uv3, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv3, uv4, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv4, uv5, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv5, uv1, color, self.line_width, cv2.LINE_AA) # msl tics y = cy - int((minrange*10 - altitude)/10 * spacing) if y < miny: y = miny if y > maxy: y = maxy uv1 = (cx, y) y = cy - int((maxrange*10 - altitude)/10 * spacing) if y < miny: y = miny if y > maxy: y = maxy uv2 = (cx, y) cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA) for i in range(minrange, maxrange, 1): offset = int((i*10 - altitude)/10 * spacing) if cy - offset >= miny and cy - offset <= maxy: uv1 = (cx, cy - offset) if i % 5 == 0: uv2 = (cx + 6, cy - offset) else: uv2 = (cx + 4, cy - offset) cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA) for i in range(minrange, maxrange, 5): offset = int((i*10 - altitude)/10 * spacing) if cy - offset >= miny and cy - offset <= maxy: label = "%d" % (i*10) lsize = cv2.getTextSize(label, self.font, self.font_size, self.line_width) uv3 = (cx + 8 , cy - offset + int(lsize[0][1] / 2)) cv2.putText(self.frame, label, uv3, self.font, self.font_size, color, self.line_width, cv2.LINE_AA) # units lsize = cv2.getTextSize(units_label, self.font, self.font_size, self.line_width) uv = (cx - int(lsize[0][1]*0.5), maxy + lsize[0][1] + self.line_width*2) cv2.putText(self.frame, units_label, uv, self.font, self.font_size, color, self.line_width, cv2.LINE_AA) # altitude bug offset = int((ap_alt - altitude)/10.0 * spacing) if self.flight_mode == 'auto' and cy - offset >= miny and cy - offset <= maxy: uv1 = (cx, cy - offset) uv2 = (cx - int(ysize*0.7), cy - offset - int(ysize / 2) ) uv3 = (cx - int(ysize*0.7), cy - offset - ysize ) uv4 = (cx, cy - offset - ysize ) uv5 = (cx, cy - offset + ysize ) uv6 = (cx - int(ysize*0.7), cy - offset + ysize ) uv7 = (cx - int(ysize*0.7), cy - offset + int(ysize / 2) ) cv2.line(self.frame, uv1, uv2, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv2, uv3, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv3, uv4, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv4, uv5, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv5, uv6, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv6, uv7, color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, uv7, uv1, color, self.line_width, cv2.LINE_AA) # draw stick positions (rc transmitter sticks) def draw_sticks(self): if self.flight_mode == 'auto': aileron = self.act_ail elevator = self.act_ele throttle = self.act_thr rudder = self.act_rud else: aileron = self.pilot_ail elevator = self.pilot_ele throttle = self.pilot_thr rudder = self.pilot_rud h, w, d = self.frame.shape lx = int(h * 0.1) ly = int(h * 0.8) rx = w - int(h * 0.1) ry = int(h * 0.8) r1 = int(round(h * 0.09)) if r1 < 10: r1 = 10 r2 = int(round(h * 0.01)) if r2 < 2: r2 = 2 cv2.circle(self.frame, (lx,ly), r1, self.color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, (lx,ly-r1), (lx,ly+r1), self.color, 1, cv2.LINE_AA) cv2.line(self.frame, (lx-r1,ly), (lx+r1,ly), self.color, 1, cv2.LINE_AA) cv2.circle(self.frame, (rx,ry), r1, self.color, self.line_width, cv2.LINE_AA) cv2.line(self.frame, (rx,ry-r1), (rx,ry+r1), self.color, 1, cv2.LINE_AA) cv2.line(self.frame, (rx-r1,ry), (rx+r1,ry), self.color, 1, cv2.LINE_AA) lsx = lx + int(round(rudder * r1)) lsy = ly + r1 - int(round(2 * throttle * r1)) cv2.circle(self.frame, (lsx,lsy), r2, self.color, self.line_width, cv2.LINE_AA) rsx = rx + int(round(aileron * r1)) rsy = ry - int(round(elevator * r1)) cv2.circle(self.frame, (rsx,rsy), r2, self.color, self.line_width, cv2.LINE_AA) def draw_time(self): h, w, d = self.frame.shape label = '%.1f' % self.time size = cv2.getTextSize(label, self.font, 0.7, self.line_width) uv = (2, h - int(size[0][1]*0.5) + 2) cv2.putText(self.frame, label, uv, self.font, 0.7, self.color, self.line_width, cv2.LINE_AA) def draw_test_index(self): if not hasattr(self, 'excite_mode'): return if not self.excite_mode: return h, w, d = self.frame.shape label = 'T%d' % self.test_index size = cv2.getTextSize(label, self.font, 0.7, self.line_width) uv = (w - int(size[0][0]) - 2, h - int(size[0][1]*0.5) + 2) cv2.putText(self.frame, label, uv, self.font, 0.7, self.color, self.line_width, cv2.LINE_AA) # draw actual flight track in 3d def draw_track(self): uv_list = [] dist_list = [] for ned in self.ned_history: dn = self.ned[0] - ned[0] de = self.ned[1] - ned[1] dd = self.ned[2] - ned[2] dist = math.sqrt(dn*dn + de*de + dd*dd) dist_list.append(dist) if dist > 5: uv = self.project_point([ned[0], ned[1], ned[2]]) else: uv = None uv_list.append(uv) if len(uv_list) > 1: for i in range(len(uv_list) - 1): dist = dist_list[i] if dist > 0.0: size = int(round(200.0 / dist)) else: size = 2 if size < 2: size = 2 uv1 = uv_list[i] uv2 = uv_list[i+1] if uv1 != None and uv2 != None: if uv1[0] < -self.render_w * 0.25 and uv2[0] > self.render_w * 1.25: pass elif uv2[0] < -self.render_w * 0.25 and uv1[0] > self.render_w * 1.25: pass elif abs(uv1[0] - uv2[0]) > self.render_w * 1.5: pass elif uv1[1] < -self.render_h * 0.25 and uv2[1] > self.render_h * 1.25: pass elif uv2[1] < -self.render_h * 0.25 and uv1[1] > self.render_h * 1.25: pass elif abs(uv1[1] - uv2[1]) > self.render_h * 1.5: pass else: cv2.line(self.frame, uv1, uv2, white, 1, cv2.LINE_AA) if uv1 != None: cv2.circle(self.frame, uv1, size, white, self.line_width, cv2.LINE_AA) # draw externally provided point db features def draw_features(self): uv_list = [] for ned in self.features: uv = self.project_point([ned[0], ned[1], ned[2]]) if uv != None: uv_list.append(uv) for uv in uv_list: size = 2 if uv[0] > -self.render_w * 0.25 \ and uv[0] < self.render_w * 1.25 \ and uv[1] > -self.render_h * 0.25 \ and uv[1] < self.render_h * 1.25: cv2.circle(self.frame, uv, size, white, self.line_width, cv2.LINE_AA) # draw a 3d reference grid in space def draw_grid(self): if len(self.grid) == 0: # build the grid h = 100 v = 75 for n in range(-5*h, 5*h+1, h): for e in range(-5*h, 5*h+1, h): for d in range(int(-self.ground_m) - 4*v, int(-self.ground_m) + 1, v): self.grid.append( [n, e, d] ) uv_list = [] dist_list = [] for ned in self.grid: dn = self.ned[0] - ned[0] de = self.ned[1] - ned[1] dd = self.ned[2] - ned[2] dist = math.sqrt(dn*dn + de*de + dd*dd) dist_list.append(dist) uv = self.project_point( ned ) uv_list.append(uv) for i in range(len(uv_list)): dist = dist_list[i] size = int(round(1000.0 / dist)) if size < 1: size = 1 uv = uv_list[i] if uv != None: cv2.circle(self.frame, uv, size, white, 1, cv2.LINE_AA) # draw the conformal components of the hud (those that should # 'stick' to the real world view. def draw_conformal(self): # things near infinity self.draw_horizon() self.draw_compass_points() self.draw_astro() # midrange things self.draw_airports() self.draw_track() self.draw_features() # cockpit things self.draw_pitch_ladder(beta_rad=0.0) self.draw_alpha_beta_marker() self.draw_velocity_vector() # draw the fixed indications (that always stay in the same place # on the hud.) note: also draw speed/alt bugs here def draw_fixed(self): if self.airspeed_units == 'mps': airspeed = self.airspeed_kt * kt2mps ap_speed = self.ap_speed * kt2mps else: airspeed = self.airspeed_kt ap_speed = self.ap_speed self.draw_speed_tape(airspeed, ap_speed, self.airspeed_units.capitalize()) if self.altitude_units == 'm': altitude = self.altitude_m ap_altitude = self.ap_altitude_ft * ft2m else: altitude = self.altitude_m * m2ft ap_altitude = self.ap_altitude_ft self.draw_altitude_tape(altitude, ap_altitude, self.altitude_units.capitalize()) self.draw_sticks() self.draw_time() self.draw_test_index() # draw autopilot symbology def draw_ap(self): if self.flight_mode == 'manual': self.draw_nose() else: self.draw_vbars() self.draw_heading_bug() self.draw_bird() self.draw_course() def draw(self): self.draw_conformal() self.draw_fixed() self.draw_ap()
mit
-679,292,853,521,603,500
40.601719
115
0.489497
false
jdemel/gnuradio
gr-utils/modtool/templates/gr-newmod/docs/doxygen/doxyxml/text.py
3
1295
# # Copyright 2010 Free Software Foundation, Inc. # # This file was generated by gr_modtool, a tool from the GNU Radio framework # This file is a part of gr-howto # # SPDX-License-Identifier: GPL-3.0-or-later # # """ Utilities for extracting text from generated classes. """ from __future__ import unicode_literals def is_string(txt): if isinstance(txt, str): return True try: if isinstance(txt, str): return True except NameError: pass return False def description(obj): if obj is None: return None return description_bit(obj).strip() def description_bit(obj): if hasattr(obj, 'content'): contents = [description_bit(item) for item in obj.content] result = ''.join(contents) elif hasattr(obj, 'content_'): contents = [description_bit(item) for item in obj.content_] result = ''.join(contents) elif hasattr(obj, 'value'): result = description_bit(obj.value) elif is_string(obj): return obj else: raise Exception('Expecting a string or something with content, content_ or value attribute') # If this bit is a paragraph then add one some line breaks. if hasattr(obj, 'name') and obj.name == 'para': result += "\n\n" return result
gpl-3.0
-4,949,053,946,127,237,000
27.152174
100
0.642471
false
dilawar/moose-full
moose-core/python/moose/neuroml2/test_hhfit.py
2
6303
# test_hhfit.py --- # # Filename: test_hhfit.py # Description: # Author: # Maintainer: # Created: Tue May 21 16:34:45 2013 (+0530) # Version: # Last-Updated: Tue May 21 16:37:28 2013 (+0530) # By: subha # Update #: 9 # URL: # Keywords: # Compatibility: # # # Commentary: # # # # # Change log: # # Tue May 21 16:34:53 IST 2013 - Subha moved code from # test_converter.py to test_hhfit.py. # # # 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, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth # Floor, Boston, MA 02110-1301, USA. # # # Code: import os import numpy as np import uuid import unittest import pylab import hhfit class TestFindRateFn(unittest.TestCase): def setUp(self): self.vmin = -120e-3 self.vmax = 40e-3 self.vdivs = 640 self.v_array = np.linspace(self.vmin, self.vmax, self.vdivs+1) # Parameters for sigmoid function - from traub2005, NaF->m_inf p_sigmoid = (1.0, 1/-10e-3, -38e-3, 0.0) self.sigmoid = p_sigmoid[0] / (1.0 + np.exp(p_sigmoid[1] * (self.v_array - p_sigmoid[2]))) + p_sigmoid[3] self.p_sigmoid = p_sigmoid # Parameters for exponential function - from traub2005, KC->n_inf p_exp = (2e3, 1/-27e-3, -53.5e-3, 0.0) self.exp = p_exp[0] * np.exp(p_exp[1] * (self.v_array - p_exp[2])) + p_exp[3] self.p_exp = p_exp # Parameters for linoid function: alpha_n from original Hodgkin-Huxley K channel. p_linoid = (-0.01*1e3, -1/10e-3, 10e-3, 0.0) self.linoid = p_linoid[3] + p_linoid[0] * (self.v_array - p_linoid[2]) / (np.exp(p_linoid[1] * (self.v_array - p_linoid[2])) - 1) self.p_linoid = p_linoid # This is tau_m of transient Ca2+ current (eq. 7) from # Huguenard and McCormick, J Neurophysiol, 68:1373-1383, # 1992.; #1e-3 * (0.612 + 1 / (np.exp((self.v_array*1e3 + 132)/-16.7) + np.exp((self.v_array*1e3 + 16.8)/18.2))) p_dblexp = (1e-3, -1/16.7e-3, -132e-3, 1/18.2e-3, -16.8e-3, 0.612e-3) self.dblexp = p_dblexp[5] + p_dblexp[0] / (np.exp(p_dblexp[1] * (self.v_array - p_dblexp[2])) + np.exp(p_dblexp[3] * (self.v_array - p_dblexp[4]))) self.p_dblexp = p_dblexp def test_sigmoid(self): print 'Testing sigmoid' fn, params = hhfit.find_ratefn(self.v_array, self.sigmoid) print 'Sigmoid params original:', self.p_sigmoid, 'detected:', params pylab.plot(self.v_array, self.sigmoid, 'y-', self.v_array, hhfit.sigmoid(self.v_array, *self.p_sigmoid), 'b--', self.v_array, fn(self.v_array, *params), 'r-.') pylab.legend(('original sigmoid', 'computed', 'fitted %s' % (fn))) pylab.show() self.assertEqual(hhfit.sigmoid, fn) rms_error = np.sqrt(np.mean((self.sigmoid - fn(self.v_array, *params))**2)) self.assertAlmostEqual(rms_error/max(abs(self.sigmoid)), 0.0, places=3) def test_exponential(self): print 'Testing exponential' fn, params = hhfit.find_ratefn(self.v_array, self.exp) print 'Exponential params original:', self.p_exp, 'detected:', params fnval = hhfit.exponential(self.v_array, *params) pylab.plot(self.v_array, self.exp, 'y-', self.v_array, hhfit.exponential(self.v_array, *self.p_exp), 'b--', self.v_array, fnval, 'r-.') pylab.legend(('original exp', 'computed', 'fitted %s' % (fn))) pylab.show() self.assertEqual(hhfit.exponential, fn) # The same exponential can be satisfied by an infinite number # of parameter values. Hence we cannot compare the parameters, # but only the fit rms_error = np.sqrt(np.sum((self.exp - fnval)**2)) # pylab.plot(self.v_array, self.exp, 'b-') # pylab.plot(self.v_array, fnval, 'r-.') # pylab.show() print rms_error, rms_error/max(self.exp) self.assertAlmostEqual(rms_error/max(self.exp), 0.0, places=3) def test_linoid(self): print 'Testing linoid' fn, params = hhfit.find_ratefn(self.v_array, self.linoid) print 'Linoid params original:', self.p_linoid, 'detected:', params pylab.plot(self.v_array, self.linoid, 'y-', self.v_array, hhfit.linoid(self.v_array, *self.p_linoid), 'b--', self.v_array, fn(self.v_array, *params), 'r-.') pylab.legend(('original linoid', 'computed', 'fitted %s' % (fn))) pylab.show() self.assertEqual(hhfit.linoid, fn) fnval = fn(self.v_array, *params) rms_error = np.sqrt(np.mean((self.linoid - fnval)**2)) self.assertAlmostEqual(rms_error/max(self.linoid), 0.0, places=3) # errors = params - np.array(self.p_linoid) # for orig, err in zip(self.p_linoid, errors): # self.assertAlmostEqual(abs(err/orig), 0.0, places=2) def test_dblexponential(self): print 'Testing double exponential' fn, params = hhfit.find_ratefn(self.v_array, self.dblexp) fnval = fn(self.v_array, *params) pylab.plot(self.v_array, self.dblexp, 'y-', self.v_array, hhfit.double_exp(self.v_array, *self.p_dblexp), 'b--', self.v_array, fnval, 'r-.') pylab.legend(('original dblexp', 'computed', 'fitted %s' % (fn))) pylab.show() self.assertEqual(hhfit.double_exp, fn) rms_error = np.sqrt(np.mean((self.dblexp - fnval)**2)) print params, rms_error self.assertAlmostEqual(rms_error/max(self.dblexp), 0.0, places=3) if __name__ == '__main__': unittest.main() # # test_hhfit.py ends here
gpl-2.0
3,486,434,100,067,372,500
39.664516
137
0.596859
false
4rado/RepositoryForProject
Lib/site-packages/scipy/linalg/decomp_schur.py
55
5250
"""Schur decomposition functions.""" import numpy from numpy import asarray_chkfinite, single # Local imports. import misc from misc import LinAlgError, _datacopied from lapack import get_lapack_funcs from decomp import eigvals __all__ = ['schur', 'rsf2csf'] _double_precision = ['i','l','d'] def schur(a, output='real', lwork=None, overwrite_a=False): """Compute Schur decomposition of a matrix. The Schur decomposition is A = Z T Z^H where Z is unitary and T is either upper-triangular, or for real Schur decomposition (output='real'), quasi-upper triangular. In the quasi-triangular form, 2x2 blocks describing complex-valued eigenvalue pairs may extrude from the diagonal. Parameters ---------- a : array, shape (M, M) Matrix to decompose output : {'real', 'complex'} Construct the real or complex Schur decomposition (for real matrices). lwork : integer Work array size. If None or -1, it is automatically computed. overwrite_a : boolean Whether to overwrite data in a (may improve performance) Returns ------- T : array, shape (M, M) Schur form of A. It is real-valued for the real Schur decomposition. Z : array, shape (M, M) An unitary Schur transformation matrix for A. It is real-valued for the real Schur decomposition. See also -------- rsf2csf : Convert real Schur form to complex Schur form """ if not output in ['real','complex','r','c']: raise ValueError("argument must be 'real', or 'complex'") a1 = asarray_chkfinite(a) if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]): raise ValueError('expected square matrix') typ = a1.dtype.char if output in ['complex','c'] and typ not in ['F','D']: if typ in _double_precision: a1 = a1.astype('D') typ = 'D' else: a1 = a1.astype('F') typ = 'F' overwrite_a = overwrite_a or (_datacopied(a1, a)) gees, = get_lapack_funcs(('gees',), (a1,)) if lwork is None or lwork == -1: # get optimal work array result = gees(lambda x: None, a1, lwork=-1) lwork = result[-2][0].real.astype(numpy.int) result = gees(lambda x: None, a1, lwork=lwork, overwrite_a=overwrite_a) info = result[-1] if info < 0: raise ValueError('illegal value in %d-th argument of internal gees' % -info) elif info > 0: raise LinAlgError("Schur form not found. Possibly ill-conditioned.") return result[0], result[-3] eps = numpy.finfo(float).eps feps = numpy.finfo(single).eps _array_kind = {'b':0, 'h':0, 'B': 0, 'i':0, 'l': 0, 'f': 0, 'd': 0, 'F': 1, 'D': 1} _array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1} _array_type = [['f', 'd'], ['F', 'D']] def _commonType(*arrays): kind = 0 precision = 0 for a in arrays: t = a.dtype.char kind = max(kind, _array_kind[t]) precision = max(precision, _array_precision[t]) return _array_type[kind][precision] def _castCopy(type, *arrays): cast_arrays = () for a in arrays: if a.dtype.char == type: cast_arrays = cast_arrays + (a.copy(),) else: cast_arrays = cast_arrays + (a.astype(type),) if len(cast_arrays) == 1: return cast_arrays[0] else: return cast_arrays def rsf2csf(T, Z): """Convert real Schur form to complex Schur form. Convert a quasi-diagonal real-valued Schur form to the upper triangular complex-valued Schur form. Parameters ---------- T : array, shape (M, M) Real Schur form of the original matrix Z : array, shape (M, M) Schur transformation matrix Returns ------- T : array, shape (M, M) Complex Schur form of the original matrix Z : array, shape (M, M) Schur transformation matrix corresponding to the complex form See also -------- schur : Schur decompose a matrix """ Z, T = map(asarray_chkfinite, (Z, T)) if len(Z.shape) != 2 or Z.shape[0] != Z.shape[1]: raise ValueError("matrix must be square.") if len(T.shape) != 2 or T.shape[0] != T.shape[1]: raise ValueError("matrix must be square.") if T.shape[0] != Z.shape[0]: raise ValueError("matrices must be same dimension.") N = T.shape[0] arr = numpy.array t = _commonType(Z, T, arr([3.0],'F')) Z, T = _castCopy(t, Z, T) conj = numpy.conj dot = numpy.dot r_ = numpy.r_ transp = numpy.transpose for m in range(N-1, 0, -1): if abs(T[m,m-1]) > eps*(abs(T[m-1,m-1]) + abs(T[m,m])): k = slice(m-1, m+1) mu = eigvals(T[k,k]) - T[m,m] r = misc.norm([mu[0], T[m,m-1]]) c = mu[0] / r s = T[m,m-1] / r G = r_[arr([[conj(c), s]], dtype=t), arr([[-s, c]], dtype=t)] Gc = conj(transp(G)) j = slice(m-1, N) T[k,j] = dot(G, T[k,j]) i = slice(0, m+1) T[i,k] = dot(T[i,k], Gc) i = slice(0, N) Z[i,k] = dot(Z[i,k], Gc) T[m,m-1] = 0.0; return T, Z
gpl-3.0
-8,418,565,791,650,039,000
30.437126
83
0.555619
false
savi-dev/keystone
keystone/common/kvs.py
4
1477
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack LLC # # 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 keystone import exception class DictKvs(dict): def get(self, key, default=None): try: return self[key] except KeyError: if default is not None: return default raise exception.NotFound(target=key) def set(self, key, value): if isinstance(value, dict): self[key] = value.copy() else: self[key] = value[:] def delete(self, key): """Deletes an item, returning True on success, False otherwise.""" try: del self[key] except KeyError: raise exception.NotFound(target=key) INMEMDB = DictKvs() class Base(object): def __init__(self, db=None): if db is None: db = INMEMDB elif isinstance(db, dict): db = DictKvs(db) self.db = db
apache-2.0
1,685,284,111,099,958,500
27.403846
75
0.631009
false
zasdfgbnm/tensorflow
tensorflow/examples/tutorials/mnist/mnist_softmax_xla.py
37
3631
# 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. # ============================================================================== """Simple MNIST classifier example with JIT XLA and timelines. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import sys import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from tensorflow.python.client import timeline FLAGS = None def main(_): # Import data mnist = input_data.read_data_sets(FLAGS.data_dir) # Create the model x = tf.placeholder(tf.float32, [None, 784]) w = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.matmul(x, w) + b # Define loss and optimizer y_ = tf.placeholder(tf.int64, [None]) # The raw formulation of cross-entropy, # # tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)), # reduction_indices=[1])) # # can be numerically unstable. # # So here we use tf.losses.sparse_softmax_cross_entropy on the raw # logit outputs of 'y', and then average across the batch. cross_entropy = tf.losses.sparse_softmax_cross_entropy(labels=y_, logits=y) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) config = tf.ConfigProto() jit_level = 0 if FLAGS.xla: # Turns on XLA JIT compilation. jit_level = tf.OptimizerOptions.ON_1 config.graph_options.optimizer_options.global_jit_level = jit_level run_metadata = tf.RunMetadata() sess = tf.Session(config=config) tf.global_variables_initializer().run(session=sess) # Train train_loops = 1000 for i in range(train_loops): batch_xs, batch_ys = mnist.train.next_batch(100) # Create a timeline for the last loop and export to json to view with # chrome://tracing/. if i == train_loops - 1: sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}, options=tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE), run_metadata=run_metadata) trace = timeline.Timeline(step_stats=run_metadata.step_stats) with open('timeline.ctf.json', 'w') as trace_file: trace_file.write(trace.generate_chrome_trace_format()) else: sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Test trained model correct_prediction = tf.equal(tf.argmax(y, 1), y_) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) sess.close() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data', help='Directory for storing input data') parser.add_argument( '--xla', type=bool, default=True, help='Turn xla via JIT on') FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
apache-2.0
5,282,069,357,783,920,000
33.254717
80
0.657119
false
alex/fabric
fabric/network.py
8
24613
""" Classes and subroutines dealing with network connections and related topics. """ from __future__ import with_statement from functools import wraps import getpass import os import re import time import socket import sys from StringIO import StringIO from fabric.auth import get_password, set_password from fabric.utils import abort, handle_prompt_abort, warn from fabric.exceptions import NetworkError try: import warnings warnings.simplefilter('ignore', DeprecationWarning) import paramiko as ssh except ImportError, e: import traceback traceback.print_exc() msg = """ There was a problem importing our SSH library (see traceback above). Please make sure all dependencies are installed and importable. """.rstrip() sys.stderr.write(msg + '\n') sys.exit(1) ipv6_regex = re.compile('^\[?(?P<host>[0-9A-Fa-f:]+)\]?(:(?P<port>\d+))?$') def direct_tcpip(client, host, port): return client.get_transport().open_channel( 'direct-tcpip', (host, int(port)), ('', 0) ) def is_key_load_error(e): return ( e.__class__ is ssh.SSHException and 'Unable to parse key file' in str(e) ) def _tried_enough(tries): from fabric.state import env return tries >= env.connection_attempts def get_gateway(host, port, cache, replace=False): """ Create and return a gateway socket, if one is needed. This function checks ``env`` for gateway or proxy-command settings and returns the necessary socket-like object for use by a final host connection. :param host: Hostname of target server. :param port: Port to connect to on target server. :param cache: A ``HostConnectionCache`` object, in which gateway ``SSHClient`` objects are to be retrieved/cached. :param replace: Whether to forcibly replace a cached gateway client object. :returns: A ``socket.socket``-like object, or ``None`` if none was created. """ from fabric.state import env, output sock = None proxy_command = ssh_config().get('proxycommand', None) if env.gateway: gateway = normalize_to_string(env.gateway) # ensure initial gateway connection if replace or gateway not in cache: if output.debug: print "Creating new gateway connection to %r" % gateway cache[gateway] = connect(*normalize(gateway) + (cache, False)) # now we should have an open gw connection and can ask it for a # direct-tcpip channel to the real target. (bypass cache's own # __getitem__ override to avoid hilarity - this is usually called # within that method.) sock = direct_tcpip(dict.__getitem__(cache, gateway), host, port) elif proxy_command: sock = ssh.ProxyCommand(proxy_command) return sock class HostConnectionCache(dict): """ Dict subclass allowing for caching of host connections/clients. This subclass will intelligently create new client connections when keys are requested, or return previously created connections instead. It also handles creating new socket-like objects when required to implement gateway connections and `ProxyCommand`, and handing them to the inner connection methods. Key values are the same as host specifiers throughout Fabric: optional username + ``@``, mandatory hostname, optional ``:`` + port number. Examples: * ``example.com`` - typical Internet host address. * ``firewall`` - atypical, but still legal, local host address. * ``user@example.com`` - with specific username attached. * ``bob@smith.org:222`` - with specific nonstandard port attached. When the username is not given, ``env.user`` is used. ``env.user`` defaults to the currently running user at startup but may be overwritten by user code or by specifying a command-line flag. Note that differing explicit usernames for the same hostname will result in multiple client connections being made. For example, specifying ``user1@example.com`` will create a connection to ``example.com``, logged in as ``user1``; later specifying ``user2@example.com`` will create a new, 2nd connection as ``user2``. The same applies to ports: specifying two different ports will result in two different connections to the same host being made. If no port is given, 22 is assumed, so ``example.com`` is equivalent to ``example.com:22``. """ def connect(self, key): """ Force a new connection to ``key`` host string. """ user, host, port = normalize(key) key = normalize_to_string(key) self[key] = connect(user, host, port, cache=self) def __getitem__(self, key): """ Autoconnect + return connection object """ key = normalize_to_string(key) if key not in self: self.connect(key) return dict.__getitem__(self, key) # # Dict overrides that normalize input keys # def __setitem__(self, key, value): return dict.__setitem__(self, normalize_to_string(key), value) def __delitem__(self, key): return dict.__delitem__(self, normalize_to_string(key)) def __contains__(self, key): return dict.__contains__(self, normalize_to_string(key)) def ssh_config(host_string=None): """ Return ssh configuration dict for current env.host_string host value. Memoizes the loaded SSH config file, but not the specific per-host results. This function performs the necessary "is SSH config enabled?" checks and will simply return an empty dict if not. If SSH config *is* enabled and the value of env.ssh_config_path is not a valid file, it will abort. May give an explicit host string as ``host_string``. """ from fabric.state import env dummy = {} if not env.use_ssh_config: return dummy if '_ssh_config' not in env: try: conf = ssh.SSHConfig() path = os.path.expanduser(env.ssh_config_path) with open(path) as fd: conf.parse(fd) env._ssh_config = conf except IOError: warn("Unable to load SSH config file '%s'" % path) return dummy host = parse_host_string(host_string or env.host_string)['host'] return env._ssh_config.lookup(host) def key_filenames(): """ Returns list of SSH key filenames for the current env.host_string. Takes into account ssh_config and env.key_filename, including normalization to a list. Also performs ``os.path.expanduser`` expansion on any key filenames. """ from fabric.state import env keys = env.key_filename # For ease of use, coerce stringish key filename into list if isinstance(env.key_filename, basestring) or env.key_filename is None: keys = [keys] # Strip out any empty strings (such as the default value...meh) keys = filter(bool, keys) # Honor SSH config conf = ssh_config() if 'identityfile' in conf: # Assume a list here as we require Paramiko 1.10+ keys.extend(conf['identityfile']) return map(os.path.expanduser, keys) def key_from_env(passphrase=None): """ Returns a paramiko-ready key from a text string of a private key """ from fabric.state import env, output if 'key' in env: if output.debug: # NOTE: this may not be the most secure thing; OTOH anybody running # the process must by definition have access to the key value, # so only serious problem is if they're logging the output. sys.stderr.write("Trying to honor in-memory key %r\n" % env.key) for pkey_class in (ssh.rsakey.RSAKey, ssh.dsskey.DSSKey): if output.debug: sys.stderr.write("Trying to load it as %s\n" % pkey_class) try: return pkey_class.from_private_key(StringIO(env.key), passphrase) except Exception, e: # File is valid key, but is encrypted: raise it, this will # cause cxn loop to prompt for passphrase & retry if 'Private key file is encrypted' in e: raise # Otherwise, it probably means it wasn't a valid key of this # type, so try the next one. else: pass def parse_host_string(host_string): # Split host_string to user (optional) and host/port user_hostport = host_string.rsplit('@', 1) hostport = user_hostport.pop() user = user_hostport[0] if user_hostport and user_hostport[0] else None # Split host/port string to host and optional port # For IPv6 addresses square brackets are mandatory for host/port separation if hostport.count(':') > 1: # Looks like IPv6 address r = ipv6_regex.match(hostport).groupdict() host = r['host'] or None port = r['port'] or None else: # Hostname or IPv4 address host_port = hostport.rsplit(':', 1) host = host_port.pop(0) or None port = host_port[0] if host_port and host_port[0] else None return {'user': user, 'host': host, 'port': port} def normalize(host_string, omit_port=False): """ Normalizes a given host string, returning explicit host, user, port. If ``omit_port`` is given and is True, only the host and user are returned. This function will process SSH config files if Fabric is configured to do so, and will use them to fill in some default values or swap in hostname aliases. """ from fabric.state import env # Gracefully handle "empty" input by returning empty output if not host_string: return ('', '') if omit_port else ('', '', '') # Parse host string (need this early on to look up host-specific ssh_config # values) r = parse_host_string(host_string) host = r['host'] # Env values (using defaults if somehow earlier defaults were replaced with # empty values) user = env.user or env.local_user port = env.port or env.default_port # SSH config data conf = ssh_config(host_string) # Only use ssh_config values if the env value appears unmodified from # the true defaults. If the user has tweaked them, that new value # takes precedence. if user == env.local_user and 'user' in conf: user = conf['user'] if port == env.default_port and 'port' in conf: port = conf['port'] # Also override host if needed if 'hostname' in conf: host = conf['hostname'] # Merge explicit user/port values with the env/ssh_config derived ones # (Host is already done at this point.) user = r['user'] or user port = r['port'] or port if omit_port: return user, host return user, host, port def to_dict(host_string): user, host, port = normalize(host_string) return { 'user': user, 'host': host, 'port': port, 'host_string': host_string } def from_dict(arg): return join_host_strings(arg['user'], arg['host'], arg['port']) def denormalize(host_string): """ Strips out default values for the given host string. If the user part is the default user, it is removed; if the port is port 22, it also is removed. """ from fabric.state import env r = parse_host_string(host_string) user = '' if r['user'] is not None and r['user'] != env.user: user = r['user'] + '@' port = '' if r['port'] is not None and r['port'] != '22': port = ':' + r['port'] host = r['host'] host = '[%s]' % host if port and host.count(':') > 1 else host return user + host + port def join_host_strings(user, host, port=None): """ Turns user/host/port strings into ``user@host:port`` combined string. This function is not responsible for handling missing user/port strings; for that, see the ``normalize`` function. If ``host`` looks like IPv6 address, it will be enclosed in square brackets If ``port`` is omitted, the returned string will be of the form ``user@host``. """ if port: # Square brackets are necessary for IPv6 host/port separation template = "%s@[%s]:%s" if host.count(':') > 1 else "%s@%s:%s" return template % (user, host, port) else: return "%s@%s" % (user, host) def normalize_to_string(host_string): """ normalize() returns a tuple; this returns another valid host string. """ return join_host_strings(*normalize(host_string)) def connect(user, host, port, cache, seek_gateway=True): """ Create and return a new SSHClient instance connected to given host. :param user: Username to connect as. :param host: Network hostname. :param port: SSH daemon port. :param cache: A ``HostConnectionCache`` instance used to cache/store gateway hosts when gatewaying is enabled. :param seek_gateway: Whether to try setting up a gateway socket for this connection. Used so the actual gateway connection can prevent recursion. """ from state import env, output # # Initialization # # Init client client = ssh.SSHClient() # Load system hosts file (e.g. /etc/ssh/ssh_known_hosts) known_hosts = env.get('system_known_hosts') if known_hosts: client.load_system_host_keys(known_hosts) # Load known host keys (e.g. ~/.ssh/known_hosts) unless user says not to. if not env.disable_known_hosts: client.load_system_host_keys() # Unless user specified not to, accept/add new, unknown host keys if not env.reject_unknown_hosts: client.set_missing_host_key_policy(ssh.AutoAddPolicy()) # # Connection attempt loop # # Initialize loop variables connected = False password = get_password(user, host, port) tries = 0 sock = None # Loop until successful connect (keep prompting for new password) while not connected: # Attempt connection try: tries += 1 # (Re)connect gateway socket, if needed. # Nuke cached client object if not on initial try. if seek_gateway: sock = get_gateway(host, port, cache, replace=tries > 0) # Ready to connect client.connect( hostname=host, port=int(port), username=user, password=password, pkey=key_from_env(password), key_filename=key_filenames(), timeout=env.timeout, allow_agent=not env.no_agent, look_for_keys=not env.no_keys, sock=sock ) connected = True # set a keepalive if desired if env.keepalive: client.get_transport().set_keepalive(env.keepalive) return client # BadHostKeyException corresponds to key mismatch, i.e. what on the # command line results in the big banner error about man-in-the-middle # attacks. except ssh.BadHostKeyException, e: raise NetworkError("Host key for %s did not match pre-existing key! Server's key was changed recently, or possible man-in-the-middle attack." % host, e) # Prompt for new password to try on auth failure except ( ssh.AuthenticationException, ssh.PasswordRequiredException, ssh.SSHException ), e: msg = str(e) # If we get SSHExceptionError and the exception message indicates # SSH protocol banner read failures, assume it's caused by the # server load and try again. if e.__class__ is ssh.SSHException \ and msg == 'Error reading SSH protocol banner': if _tried_enough(tries): raise NetworkError(msg, e) continue # For whatever reason, empty password + no ssh key or agent # results in an SSHException instead of an # AuthenticationException. Since it's difficult to do # otherwise, we must assume empty password + SSHException == # auth exception. # # Conversely: if we get SSHException and there # *was* a password -- it is probably something non auth # related, and should be sent upwards. (This is not true if the # exception message does indicate key parse problems.) # # This also holds true for rejected/unknown host keys: we have to # guess based on other heuristics. if e.__class__ is ssh.SSHException \ and (password or msg.startswith('Unknown server')) \ and not is_key_load_error(e): raise NetworkError(msg, e) # Otherwise, assume an auth exception, and prompt for new/better # password. # Paramiko doesn't handle prompting for locked private # keys (i.e. keys with a passphrase and not loaded into an agent) # so we have to detect this and tweak our prompt slightly. # (Otherwise, however, the logic flow is the same, because # ssh's connect() method overrides the password argument to be # either the login password OR the private key passphrase. Meh.) # # NOTE: This will come up if you normally use a # passphrase-protected private key with ssh-agent, and enter an # incorrect remote username, because ssh.connect: # * Tries the agent first, which will fail as you gave the wrong # username, so obviously any loaded keys aren't gonna work for a # nonexistent remote account; # * Then tries the on-disk key file, which is passphrased; # * Realizes there's no password to try unlocking that key with, # because you didn't enter a password, because you're using # ssh-agent; # * In this condition (trying a key file, password is None) # ssh raises PasswordRequiredException. text = None if e.__class__ is ssh.PasswordRequiredException \ or is_key_load_error(e): # NOTE: we can't easily say WHICH key's passphrase is needed, # because ssh doesn't provide us with that info, and # env.key_filename may be a list of keys, so we can't know # which one raised the exception. Best not to try. prompt = "[%s] Passphrase for private key" text = prompt % env.host_string password = prompt_for_password(text) # Update env.password, env.passwords if empty set_password(user, host, port, password) # Ctrl-D / Ctrl-C for exit except (EOFError, TypeError): # Print a newline (in case user was sitting at prompt) print('') sys.exit(0) # Handle DNS error / name lookup failure except socket.gaierror, e: raise NetworkError('Name lookup failed for %s' % host, e) # Handle timeouts and retries, including generic errors # NOTE: In 2.6, socket.error subclasses IOError except socket.error, e: not_timeout = type(e) is not socket.timeout giving_up = _tried_enough(tries) # Baseline error msg for when debug is off msg = "Timed out trying to connect to %s" % host # Expanded for debug on err = msg + " (attempt %s of %s)" % (tries, env.connection_attempts) if giving_up: err += ", giving up" err += ")" # Debuggin' if output.debug: sys.stderr.write(err + '\n') # Having said our piece, try again if not giving_up: # Sleep if it wasn't a timeout, so we still get timeout-like # behavior if not_timeout: time.sleep(env.timeout) continue # Override eror msg if we were retrying other errors if not_timeout: msg = "Low level socket error connecting to host %s on port %s: %s" % ( host, port, e[1] ) # Here, all attempts failed. Tweak error msg to show # tries. # TODO: find good humanization module, jeez s = "s" if env.connection_attempts > 1 else "" msg += " (tried %s time%s)" % (env.connection_attempts, s) raise NetworkError(msg, e) # Ensure that if we terminated without connecting and we were given an # explicit socket, close it out. finally: if not connected and sock is not None: sock.close() def _password_prompt(prompt, stream): # NOTE: Using encode-to-ascii to prevent (Windows, at least) getpass from # choking if given Unicode. return getpass.getpass(prompt.encode('ascii', 'ignore'), stream) def prompt_for_password(prompt=None, no_colon=False, stream=None): """ Prompts for and returns a new password if required; otherwise, returns None. A trailing colon is appended unless ``no_colon`` is True. If the user supplies an empty password, the user will be re-prompted until they enter a non-empty password. ``prompt_for_password`` autogenerates the user prompt based on the current host being connected to. To override this, specify a string value for ``prompt``. ``stream`` is the stream the prompt will be printed to; if not given, defaults to ``sys.stderr``. """ from fabric.state import env handle_prompt_abort("a connection or sudo password") stream = stream or sys.stderr # Construct prompt default = "[%s] Login password for '%s'" % (env.host_string, env.user) password_prompt = prompt if (prompt is not None) else default if not no_colon: password_prompt += ": " # Get new password value new_password = _password_prompt(password_prompt, stream) # Otherwise, loop until user gives us a non-empty password (to prevent # returning the empty string, and to avoid unnecessary network overhead.) while not new_password: print("Sorry, you can't enter an empty password. Please try again.") new_password = _password_prompt(password_prompt, stream) return new_password def needs_host(func): """ Prompt user for value of ``env.host_string`` when ``env.host_string`` is empty. This decorator is basically a safety net for silly users who forgot to specify the host/host list in one way or another. It should be used to wrap operations which require a network connection. Due to how we execute commands per-host in ``main()``, it's not possible to specify multiple hosts at this point in time, so only a single host will be prompted for. Because this decorator sets ``env.host_string``, it will prompt once (and only once) per command. As ``main()`` clears ``env.host_string`` between commands, this decorator will also end up prompting the user once per command (in the case where multiple commands have no hosts set, of course.) """ from fabric.state import env @wraps(func) def host_prompting_wrapper(*args, **kwargs): while not env.get('host_string', False): handle_prompt_abort("the target host connection string") host_string = raw_input("No hosts found. Please specify (single)" " host string for connection: ") env.update(to_dict(host_string)) return func(*args, **kwargs) host_prompting_wrapper.undecorated = func return host_prompting_wrapper def disconnect_all(): """ Disconnect from all currently connected servers. Used at the end of ``fab``'s main loop, and also intended for use by library users. """ from fabric.state import connections, output # Explicitly disconnect from all servers for key in connections.keys(): if output.status: # Here we can't use the py3k print(x, end=" ") # because 2.5 backwards compatibility sys.stdout.write("Disconnecting from %s... " % denormalize(key)) connections[key].close() del connections[key] if output.status: sys.stdout.write("done.\n")
bsd-2-clause
-4,666,307,345,220,745,000
36.236006
164
0.621826
false
adrianholovaty/django
django/contrib/gis/admin/widgets.py
10
4344
from django.forms.widgets import Textarea from django.template import loader, Context from django.templatetags.static import static from django.utils import translation from django.contrib.gis.gdal import OGRException from django.contrib.gis.geos import GEOSGeometry, GEOSException # Creating a template context that contains Django settings # values needed by admin map templates. geo_context = Context({'LANGUAGE_BIDI' : translation.get_language_bidi()}) class OpenLayersWidget(Textarea): """ Renders an OpenLayers map using the WKT of the geometry. """ def render(self, name, value, attrs=None): # Update the template parameters with any attributes passed in. if attrs: self.params.update(attrs) # Defaulting the WKT value to a blank string -- this # will be tested in the JavaScript and the appropriate # interface will be constructed. self.params['wkt'] = '' # If a string reaches here (via a validation error on another # field) then just reconstruct the Geometry. if isinstance(value, basestring): try: value = GEOSGeometry(value) except (GEOSException, ValueError): value = None if value and value.geom_type.upper() != self.geom_type: value = None # Constructing the dictionary of the map options. self.params['map_options'] = self.map_options() # Constructing the JavaScript module name using the name of # the GeometryField (passed in via the `attrs` keyword). # Use the 'name' attr for the field name (rather than 'field') self.params['name'] = name # note: we must switch out dashes for underscores since js # functions are created using the module variable js_safe_name = self.params['name'].replace('-','_') self.params['module'] = 'geodjango_%s' % js_safe_name if value: # Transforming the geometry to the projection used on the # OpenLayers map. srid = self.params['srid'] if value.srid != srid: try: ogr = value.ogr ogr.transform(srid) wkt = ogr.wkt except OGRException: wkt = '' else: wkt = value.wkt # Setting the parameter WKT with that of the transformed # geometry. self.params['wkt'] = wkt return loader.render_to_string(self.template, self.params, context_instance=geo_context) def map_options(self): "Builds the map options hash for the OpenLayers template." # JavaScript construction utilities for the Bounds and Projection. def ol_bounds(extent): return 'new OpenLayers.Bounds(%s)' % str(extent) def ol_projection(srid): return 'new OpenLayers.Projection("EPSG:%s")' % srid # An array of the parameter name, the name of their OpenLayers # counterpart, and the type of variable they are. map_types = [('srid', 'projection', 'srid'), ('display_srid', 'displayProjection', 'srid'), ('units', 'units', str), ('max_resolution', 'maxResolution', float), ('max_extent', 'maxExtent', 'bounds'), ('num_zoom', 'numZoomLevels', int), ('max_zoom', 'maxZoomLevels', int), ('min_zoom', 'minZoomLevel', int), ] # Building the map options hash. map_options = {} for param_name, js_name, option_type in map_types: if self.params.get(param_name, False): if option_type == 'srid': value = ol_projection(self.params[param_name]) elif option_type == 'bounds': value = ol_bounds(self.params[param_name]) elif option_type in (float, int): value = self.params[param_name] elif option_type in (str,): value = '"%s"' % self.params[param_name] else: raise TypeError map_options[js_name] = value return map_options
bsd-3-clause
8,129,332,532,780,420,000
39.981132
74
0.5686
false
sankhesh/VTK
ThirdParty/Twisted/twisted/conch/ui/ansi.py
59
7222
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. # """Module to parse ANSI escape sequences Maintainer: Jean-Paul Calderone """ import string # Twisted imports from twisted.python import log class ColorText: """ Represents an element of text along with the texts colors and additional attributes. """ # The colors to use COLORS = ('b', 'r', 'g', 'y', 'l', 'm', 'c', 'w') BOLD_COLORS = tuple([x.upper() for x in COLORS]) BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(len(COLORS)) # Color names COLOR_NAMES = ( 'Black', 'Red', 'Green', 'Yellow', 'Blue', 'Magenta', 'Cyan', 'White' ) def __init__(self, text, fg, bg, display, bold, underline, flash, reverse): self.text, self.fg, self.bg = text, fg, bg self.display = display self.bold = bold self.underline = underline self.flash = flash self.reverse = reverse if self.reverse: self.fg, self.bg = self.bg, self.fg class AnsiParser: """ Parser class for ANSI codes. """ # Terminators for cursor movement ansi controls - unsupported CURSOR_SET = ('H', 'f', 'A', 'B', 'C', 'D', 'R', 's', 'u', 'd','G') # Terminators for erasure ansi controls - unsupported ERASE_SET = ('J', 'K', 'P') # Terminators for mode change ansi controls - unsupported MODE_SET = ('h', 'l') # Terminators for keyboard assignment ansi controls - unsupported ASSIGN_SET = ('p',) # Terminators for color change ansi controls - supported COLOR_SET = ('m',) SETS = (CURSOR_SET, ERASE_SET, MODE_SET, ASSIGN_SET, COLOR_SET) def __init__(self, defaultFG, defaultBG): self.defaultFG, self.defaultBG = defaultFG, defaultBG self.currentFG, self.currentBG = self.defaultFG, self.defaultBG self.bold, self.flash, self.underline, self.reverse = 0, 0, 0, 0 self.display = 1 self.prepend = '' def stripEscapes(self, string): """ Remove all ANSI color escapes from the given string. """ result = '' show = 1 i = 0 L = len(string) while i < L: if show == 0 and string[i] in _sets: show = 1 elif show: n = string.find('\x1B', i) if n == -1: return result + string[i:] else: result = result + string[i:n] i = n show = 0 i = i + 1 return result def writeString(self, colorstr): pass def parseString(self, str): """ Turn a string input into a list of L{ColorText} elements. """ if self.prepend: str = self.prepend + str self.prepend = '' parts = str.split('\x1B') if len(parts) == 1: self.writeString(self.formatText(parts[0])) else: self.writeString(self.formatText(parts[0])) for s in parts[1:]: L = len(s) i = 0 type = None while i < L: if s[i] not in string.digits+'[;?': break i+=1 if not s: self.prepend = '\x1b' return if s[0]!='[': self.writeString(self.formatText(s[i+1:])) continue else: s=s[1:] i-=1 if i==L-1: self.prepend = '\x1b[' return type = _setmap.get(s[i], None) if type is None: continue if type == AnsiParser.COLOR_SET: self.parseColor(s[:i + 1]) s = s[i + 1:] self.writeString(self.formatText(s)) elif type == AnsiParser.CURSOR_SET: cursor, s = s[:i+1], s[i+1:] self.parseCursor(cursor) self.writeString(self.formatText(s)) elif type == AnsiParser.ERASE_SET: erase, s = s[:i+1], s[i+1:] self.parseErase(erase) self.writeString(self.formatText(s)) elif type == AnsiParser.MODE_SET: mode, s = s[:i+1], s[i+1:] #self.parseErase('2J') self.writeString(self.formatText(s)) elif i == L: self.prepend = '\x1B[' + s else: log.msg('Unhandled ANSI control type: %c' % (s[i],)) s = s[i + 1:] self.writeString(self.formatText(s)) def parseColor(self, str): """ Handle a single ANSI color sequence """ # Drop the trailing 'm' str = str[:-1] if not str: str = '0' try: parts = map(int, str.split(';')) except ValueError: log.msg('Invalid ANSI color sequence (%d): %s' % (len(str), str)) self.currentFG, self.currentBG = self.defaultFG, self.defaultBG return for x in parts: if x == 0: self.currentFG, self.currentBG = self.defaultFG, self.defaultBG self.bold, self.flash, self.underline, self.reverse = 0, 0, 0, 0 self.display = 1 elif x == 1: self.bold = 1 elif 30 <= x <= 37: self.currentFG = x - 30 elif 40 <= x <= 47: self.currentBG = x - 40 elif x == 39: self.currentFG = self.defaultFG elif x == 49: self.currentBG = self.defaultBG elif x == 4: self.underline = 1 elif x == 5: self.flash = 1 elif x == 7: self.reverse = 1 elif x == 8: self.display = 0 elif x == 22: self.bold = 0 elif x == 24: self.underline = 0 elif x == 25: self.blink = 0 elif x == 27: self.reverse = 0 elif x == 28: self.display = 1 else: log.msg('Unrecognised ANSI color command: %d' % (x,)) def parseCursor(self, cursor): pass def parseErase(self, erase): pass def pickColor(self, value, mode, BOLD = ColorText.BOLD_COLORS): if mode: return ColorText.COLORS[value] else: return self.bold and BOLD[value] or ColorText.COLORS[value] def formatText(self, text): return ColorText( text, self.pickColor(self.currentFG, 0), self.pickColor(self.currentBG, 1), self.display, self.bold, self.underline, self.flash, self.reverse ) _sets = ''.join(map(''.join, AnsiParser.SETS)) _setmap = {} for s in AnsiParser.SETS: for r in s: _setmap[r] = s del s
bsd-3-clause
-1,011,474,705,869,925,900
29.091667
80
0.467599
false
samcavallieri/weblogic_project_automation
crwls.py
1
35330
# encoding:UTF-8 import sys import os import time import wlstModule as wlst import ConfigParser from java.util import Properties from java.lang import System from java.io import FileInputStream from java.io import FileOutputStream from weblogic.security.internal import SerializedSystemIni from weblogic.security.internal.encryption import ClearOrEncryptedService config = None class crtwls: def log(cls, message): print("\n*** %s" % message) log = classmethod(log) def connectToAdminServer(cls): adminAddress = config.get('crtwls', 'admin-address') cls.log("Conectando ao AdminServer %s" % adminAddress) wlst.connect(url='t3://' + adminAddress) connectToAdminServer = classmethod(connectToAdminServer) def edit(cls, waitTime=0, timeout=0, start=True): cls.log("Indo para arvore de edicao") wlst.edit() if start: cls.log("Obtendo Lock da Console") wlst.startEdit(waitTime, timeout) edit = classmethod(edit) def save(cls): cls.log("Salvando a modificacao") wlst.save() cls.log("Ativando as mudancas") wlst.activate(block='true') save = classmethod(save) def getDomainName(cls): return wlst.cmo.getName() getDomainName = classmethod(getDomainName) def getAdminAddress(cls): adminAddress = config.get('crtwls', 'admin-address') return adminAddress getAdminAddress = classmethod(getAdminAddress) def getEnvSuffix(cls): envSuffix = config.get('crtwls', 'env-suffix') return envSuffix getEnvSuffix = classmethod(getEnvSuffix) # ================================== def _wait(progress): crtwls.log("Aguardando a operacao %s" % progress.getCommandType()) while progress.isRunning() == 1: progress.printStatus() print '##############################.', time.sleep(1) print '.' progress.printStatus() completed = progress.isCompleted() == 1 crtwls.log("Operacao completada? %s" % completed) return completed class Application: def __init__(self, name): if not name: raise ValueError("name required") name = name.strip() if len(name) == 0: raise ValueError("name required") self.name = name if not config.has_section(self.name): config.add_section(self.name) def group(self, group=None): if group: config.set(self.name, 'group', group) else: if config.has_option(self.name, 'group'): group = config.get(self.name, 'group') else: group = self.name return group def redeploy(self, path): crtwls.connectToAdminServer() reinstall = False remove = False applications = wlst.cmo.getAppDeployments() for application in applications: if application.getName() == self.name: reinstall = True break # if reinstall and application.getSourcePath() != path: if True: remove = True reinstall = False target = Cluster.resolveClusterName(self) try: if reinstall: crtwls.edit(10 * 60 * 1000, 5 * 60 * 1000) crtwls.log("Fazendo redeploy da Aplicacao '%s'" % self.name) progress = wlst.redeploy(self.name, block='true') wlst.activate() else: if remove: crtwls.edit(10 * 60 * 1000, 5 * 60 * 1000) crtwls.log( "Fazendo undeploy da Aplicacao '%s'" % self.name) progress = wlst.undeploy(self.name, block='true') wlst.activate() crtwls.edit(10 * 60 * 1000, 5 * 60 * 1000) crtwls.log("Fazendo deploy da Aplicacao '%s'" % self.name) progress = wlst.deploy(self.name, path, target, block='true') wlst.activate() except wlst.WLSTException as e: e.printStackTrace() raise e def __findSid__(self, url): idx = url.find('SERVICE_NAME') if idx < 0: idx = url.find('SID') if not idx < 0: sta = url.find('=', idx) + 1 end = url.find(')', sta) return url[sta:end].strip() idx = url.find('@') sta = url.rfind('/', idx) if sta < 0: sta = url.rfind(':', idx) sta = sta + 1 return url[sta:].strip() def newDatasource(self, name, url, username, password, isXA): # Reduz espaços repetidos url = ' '.join(url.split()) sid = self.__findSid__(url) dsName = "%s / %s" % (username, sid) dsName = dsName.lower() if isXA: dsName = dsName + ' - XA' #config.set(self.name, 'ds.'+name+'.url', url) #config.set(self.name, 'ds.'+name+'.username', username) #config.set(self.name, 'ds.'+name+'.password', password) crtwls.connectToAdminServer() crtwls.edit() cluster = Cluster.findCluster(self) if not cluster: raise Exception( "Cluster da aplicacao %s nao encontrado" % self.name) crtwls.log("Criando o DataSource") datasource = wlst.cmo.createJDBCSystemResource(dsName) jdbcResource = datasource.getJDBCResource() jdbcResource.setName(dsName) jndiName = '%s.ds.%s' % (self.name, name) jdbcResource.getJDBCDataSourceParams().setJNDINames([jndiName]) jdbcResource.getJDBCConnectionPoolParams().setInitialCapacity(0) jdbcResource.getJDBCConnectionPoolParams().setMaxCapacity(20) jdbcResource.getJDBCConnectionPoolParams().setShrinkFrequencySeconds(900) jdbcResource.getJDBCConnectionPoolParams().setTestConnectionsOnReserve(True) jdbcResource.getJDBCConnectionPoolParams().setStatementCacheSize(30) jdbcResource.getJDBCConnectionPoolParams().setStatementCacheType('LRU') if isXA: jdbcResource.getJDBCDriverParams().setDriverName( 'oracle.jdbc.xa.client.OracleXADataSource') else: jdbcResource.getJDBCDriverParams().setDriverName('oracle.jdbc.OracleDriver') jdbcResource.getJDBCDriverParams().setPassword(password) jdbcResource.getJDBCDriverParams().setUrl(url) props = jdbcResource.getJDBCDriverParams().getProperties() props.createProperty('user') props.lookupProperty('user').setValue(username) crtwls.log("Ajustando Target") datasource.addTarget(cluster) crtwls.save() def newMultiDatasource(self, name, dsList): dsName = "%s.ds.%s" % (self.name, name) dsName = dsName.lower() crtwls.connectToAdminServer() crtwls.edit() cluster = Cluster.findCluster(self) if not cluster: raise Exception( "Cluster da aplicacao %s nao encontrado" % self.name) crtwls.log("Criando o MultiDataSource") datasource = wlst.cmo.createJDBCSystemResource(dsName) jdbcResource = datasource.getJDBCResource() jdbcResource.setName(dsName) jndiName = '%s.ds.%s' % (self.name, name) jdbcResource.getJDBCDataSourceParams().setJNDINames([jndiName]) jdbcResource.getJDBCDataSourceParams().setAlgorithmType('Load-Balancing') jdbcResource.getJDBCDataSourceParams().setDataSourceList(dsList) crtwls.log("Ajustando Target") datasource.addTarget(cluster) crtwls.save() def createEnv(self, group=None): crtwls.connectToAdminServer() domainApp = System.getenv("DOMAIN_APP") usrRoot = System.getenv("USR_ROOT") if os.path.exists('%s/install/%s' % (domainApp, self.name)): raise Exception("Ambiente de %s já existe" % self.name) self.group(group) site = self.name cfgvars = {'APP_NAME': self.name, 'SITE': site, 'ENV': crtwls.getEnvSuffix(), 'DOMAIN_APP': domainApp, 'DOMAIN_NAME': crtwls.getDomainName(), 'CLUSTER': '${WLS_CLUSTER_%s}' % self.group()} crtwls.log("Criando diretórios") DIRS = ['appfiles', 'applogs', 'config', 'deployments', 'docroot', 'install'] for d in DIRS: os.makedirs('%s/%s/%s' % (domainApp, d, self.name)) crtwls.log("Criando arquivo config.properties") template = open( '%s/tools/config-properties.tmpl' % usrRoot, 'r').read() cfgname = '%s/config/%s/config.properties' % (domainApp, self.name) cfgfile = open(cfgname, 'w') cfgfile.write(template % cfgvars) cfgfile.close() cfgname = '%s/httpconf/%s.cfg' % (domainApp, site) if not os.path.exists(cfgname): crtwls.log("Criando Apache VirtualHost '%s'" % site) template = open('%s/tools/virtualhost.tmpl' % usrRoot, 'r').read() cfgfile = open(cfgname, 'w') cfgfile.write(template % cfgvars) cfgfile.close() os.makedirs('%s/httplogs/%s' % (domainApp, site)) else: crtwls.log("Apache VirtualHost '%s' já existe" % site) class JMSModule: def resolveJMSModuleName(cls, application): group = application.group() jmsModuleName = '%s-jms' % group return jmsModuleName resolveJMSModuleName = classmethod(resolveJMSModuleName) def findJMSModule(cls, application): jmsName = cls.resolveJMSModuleName(application) crtwls.log("Buscando o JMS Module %s" % jmsName) jmsModule = wlst.cmo.lookupJMSSystemResource(jmsName) return jmsModule findJMSModule = classmethod(findJMSModule) def ensureJMSServers(cls, cluster): servers = cluster.getServers() for server in servers: serverName = server.getName() jmsServerName = serverName + '-jms' jmsserver = wlst.cmo.lookupJMSServer(jmsServerName) if not jmsserver: crtwls.log("Criando o JMSServer '%s'" % jmsServerName) jmsserver = wlst.cmo.createJMSServer(jmsServerName) jmsserver.addTarget(server) crtwls.log("Configurando o JMSServer Log") jmsserver.getJMSMessageLogFile().setFileName('logs/%s-jms.log' % serverName) jmsserver.getJMSMessageLogFile().setFileMinSize(40000) jmsserver.getJMSMessageLogFile().setNumberOfFilesLimited(True) jmsserver.getJMSMessageLogFile().setFileCount(5) ensureJMSServers = classmethod(ensureJMSServers) def __createJMSModule(cls, application, cluster): jmsName = cls.resolveJMSModuleName(application) crtwls.log("Criando o JmsModule") cls.ensureJMSServers(cluster) jmsmodule = wlst.cmo.createJMSSystemResource(jmsName) crtwls.log("Ajustando Targets") jmsmodule.addTarget(cluster) crtwls.log("Criando Default Connection Factory") connection = jmsmodule.getJMSResource().createConnectionFactory( 'jms.ConnectionFactory.default') connection.setJNDIName('jms.ConnectionFactory.default') connection.setDefaultTargetingEnabled(True) return jmsmodule __createJMSModule = classmethod(__createJMSModule) def createJMSQueue(cls, application, name): crtwls.connectToAdminServer() cluster = Cluster.findCluster(application) if not cluster: raise Exception( "Cluster da aplicacao %s nao encontrado" % application.name) crtwls.edit() jmsmodule = cls.findJMSModule(application) if not jmsmodule: jmsmodule = cls.__createJMSModule(application, cluster) # raise Exception("JMS Module da aplicacao %s nao encontrado" % application.name) crtwls.log("Criando o JmsQueue") jmsQueueName = '%s.jms.%s' % (application.name, name) jmsQueue = jmsmodule.getJMSResource().createUniformDistributedQueue(jmsQueueName) jmsQueue.setJNDIName(jmsQueueName) jmsQueue.setDefaultTargetingEnabled(True) crtwls.save() createJMSQueue = classmethod(createJMSQueue) class Cluster: def createCluster(cls, application): clusterName = cls.resolveClusterName(application) crtwls.connectToAdminServer() crtwls.edit() crtwls.log("Criando o Cluster") cluster = wlst.cmo.createCluster(clusterName) crtwls.log("Configurando o Cluster %s" % clusterName) cluster.setWeblogicPluginEnabled(True) cluster.setClusterMessagingMode('unicast') crtwls.log("Ajustando Targets dos MailSession") mailsessions = wlst.cmo.getMailSessions() for mailsession in mailsessions: mailsession.addTarget(cluster) crtwls.log(".. %s" % mailsession.getName()) crtwls.save() createCluster = classmethod(createCluster) def resolveClusterName(cls, application): mask = '%s-cluster' if config.has_option('crtwls', 'cluster-name-mask'): mask = config.get('crtwls', 'cluster-name-mask') group = application.group() clusterName = mask % group return clusterName resolveClusterName = classmethod(resolveClusterName) def findCluster(cls, application): clusterName = cls.resolveClusterName(application) crtwls.log("Buscando o Cluster %s" % clusterName) cluster = wlst.cmo.lookupCluster(clusterName) return cluster findCluster = classmethod(findCluster) __JROCKIT = '-jrockit -Xms%s -Xmx%s -Xgc:genpar \ -Xmanagement:ssl=false,port=%d -Dweblogic.wsee.useRequestHost=true \ -Djava.awt.headless=true -Dconfig.applogssuffix=${weblogic.Name} \ -Dconfig.applogspath=%s/applogs' __HOTSPOT = '-server -Xms%s -Xmx%s -XX:MaxPermSize=256M \ -Dcom.sun.management.jmxremote.port=%d -Dcom.sun.management.jmxremote.ssl=false \ -Djavax.management.builder.initial=weblogic.management.jmx.mbeanserver.WLSMBeanServerBuilder \ -Dweblogic.wsee.useRequestHost=true \ -Djava.awt.headless=true -Dconfig.applogssuffix=${weblogic.Name} \ -Dconfig.applogspath=%s/applogs' def createManagedServer( cls, application, hostname, port, serial, memory='1G'): vendor = System.getenv("JAVA_VENDOR") CMDLINE = vendor == 'SUN' and cls.__HOTSPOT or cls.__JROCKIT if not memory: memory = '1G' crtwls.connectToAdminServer() crtwls.edit() cluster = cls.findCluster(application) if not cluster: raise Exception( "Cluster da aplicacao %s nao encontrado" % application.name) mcn = Domain.findMachine(hostname) if not mcn: raise Exception("Machine do hostname %s nao encontrado" % hostname) domainName = crtwls.getDomainName() shortname = hostname.split('.')[0] group = application.group() serverName = '%s-%s-%s-%s' % (domainName, group, shortname, serial) crtwls.log("Buscando o Server") server = wlst.cmo.lookupServer(serverName) if not server: crtwls.log("Criando o Server") server = wlst.cmo.createServer(serverName) server.setCluster(cluster) server.setMachine(mcn) crtwls.log("Configurando o Server '%s'" % serverName) server.setListenAddress(hostname) server.setListenPort(port) server.setWeblogicPluginEnabled(True) server.getSSL().setEnabled(True) server.getSSL().setListenPort(int(port) + 1) crtwls.log("Ajustando Deployment Options") server.setUploadDirectoryName('/nonexistent') server.setStagingMode('nostage') crtwls.log("Ajustando Server StartUp Options") domainApp = System.getenv("DOMAIN_APP") cmdLine = CMDLINE % (memory, memory, port + 2, domainApp) server.getServerStart().setArguments(cmdLine) crtwls.log("Configurando o Server Log") server.getLog().setFileName('logs/%s-server.log' % serverName) server.getLog().setFileMinSize(40000) server.getLog().setNumberOfFilesLimited(True) server.getLog().setFileCount(5) crtwls.log("Configurando o WebServer") server.getWebServer().setMaxPostSize(23068672) crtwls.log("Configurando o WebServer Log") server.getWebServer().getWebServerLog().setFileName( 'logs/%s-access.log' % serverName) server.getWebServer().getWebServerLog().setFileMinSize(40000) server.getWebServer().getWebServerLog().setNumberOfFilesLimited(True) server.getWebServer().getWebServerLog().setFileCount(5) crtwls.log("Criando link simbolico em serverlogs") relativeLogPath = "../../../domains/" + \ domainName + "/servers/" + serverName + "/logs" linkName = domainApp + "/serverlogs/" + serverName os.system('ln -s ' + relativeLogPath + ' ' + linkName) jmsModule = JMSModule.findJMSModule(application) if jmsModule: JMSModule.ensureJMSServers(cluster) crtwls.save() createManagedServer = classmethod(createManagedServer) class Domain: def create(cls, domainName, envSuffix, adminAddress): wlHome = System.getenv('WL_HOME') usrRoot = System.getenv("USR_ROOT") appRoot = System.getenv('APP_ROOT') domainRoot = System.getenv('DOMAIN_ROOT') apacheRoot = System.getenv('APACHE_ROOT') hostname, port = adminAddress.split(':') port = int(port) adminName = '%s-adminserver' % domainName domainHome = '%s/%s' % (domainRoot, domainName) domainApp = "%s/%s" % (appRoot, domainName) cfgvars = {'DOMAIN_NAME': domainName, 'CLUSTER': adminAddress, 'ENV': envSuffix} wlst.readTemplate('%s/../basedomain.jar' % wlHome) wlst.cmo.setName(domainName) wlst.cmo.getServers()[0].setName(adminName) wlst.cmo.getServers()[0].setListenAddress(hostname) wlst.cmo.getServers()[0].setListenPort(port) wlst.cmo.setAdminServerName(adminName) wlst.writeDomain(domainHome) crtwls.log("Criando diretórios") os.makedirs('%s/jmsstores' % (domainHome)) DIRS = ['appfiles', 'applogs', 'config', 'deployments', 'docroot', 'install', 'httplogs', 'httpconf', 'serverlogs'] for d in DIRS: os.makedirs('%s/%s' % (domainApp, d)) crtwls.log("Criando common.properties") cfgname = '%s/config/common.properties' % (domainApp) cfgfile = open(cfgname, 'w') cfgfile.write('allowjobfrom=\n') cfgfile.close() crtwls.log("Criando Apache VirtualHost") template = open('%s/tools/domainhost.tmpl' % usrRoot, 'r').read() cfgname = '%s/httpconf/default.conf' % (domainApp) cfgfile = open(cfgname, 'w') cfgfile.write(template % cfgvars) cfgfile.close() open('%s/httpconf/manutencao.txt' % (domainApp), 'w').close() os.makedirs('%s/httplogs/default' % (domainApp)) crtwls.log("Incluindo o VirtualHost no Apache Conf") template = 'Include ${APP_ROOT}/%(DOMAIN_NAME)s/httpconf/default.conf\n' cfgname = '%s/conf.d/%s.cfg' % (apacheRoot, domainName) cfgfile = open(cfgname, 'w') cfgfile.write(template % cfgvars) cfgfile.close() crtwls.log("Criando crtwls.cfg") template = '[crtwls]\nadmin-address = %(CLUSTER)s\nenv-suffix = %(ENV)s\n' cfgname = '%s/crtwls.cfg' % (domainHome) cfgfile = open(cfgname, 'w') cfgfile.write(template % cfgvars) cfgfile.close() crtwls.log("Criando startEnv.sh") template = 'ADMIN_NAME=%s\nNM_PORT=%d\n' cfgname = '%s/startEnv.sh' % (domainHome) cfgfile = open(cfgname, 'w') cfgfile.write(template % (adminName, port + 4)) cfgfile.close() crtwls.log("Copiando boot.properties") template = open('%s/servers/%s/security/boot.properties' % (domainHome, adminName), 'r').read() cfgname = '%s/boot.properties' % (domainHome) cfgfile = open(cfgname, 'w') cfgfile.write(template) cfgfile.close() create = classmethod(create) def authenticator(cls): crtwls.connectToAdminServer() crtwls.edit() crtwls.log("Identificando o REALM") realm = wlst.cmo.getSecurityConfiguration().getDefaultRealm() crtwls.log("Buscando o autenticador 'Petrobras AD Authenticator'") auth = realm.lookupAuthenticationProvider('Petrobras AD Authenticator') if not auth: crtwls.log("Criando o autenticador 'Petrobras AD Authenticator'") auth = realm.createAuthenticationProvider( 'Petrobras AD Authenticator', 'weblogic.security.providers.authentication.ActiveDirectoryAuthenticator') crtwls.log("Configurando o autenticador 'Petrobras AD Authenticator'") auth.setGroupBaseDN('DC=biz') auth.setUserNameAttribute('sAMAccountName') auth.setConnectionRetryLimit(3) auth.setConnectTimeout(10) auth.setParallelConnectDelay(5) auth.setResultsTimeLimit(1000) auth.setAllUsersFilter('objectClass=user') auth.setPropagateCauseForLoginException(False) auth.setHost( 'sptbrdc04.petrobras.biz sptbrdc14.petrobras.biz sptbrdc08.petrobras.biz sptbrdc02.petrobras.biz') auth.setAllGroupsFilter('objectClass=group') auth.setUseTokenGroupsForGroupMembershipLookup(True) auth.setUserFromNameFilter('(&(samAccountName=%u)(objectclass=user))') auth.setGroupFromNameFilter( '(&(sAMAccountName=%g)(objectclass=group))') auth.setPort(3268) auth.setUserBaseDN('DC=biz') auth.setStaticGroupNameAttribute('sAMAccountName') auth.setPrincipal('sacduxba@petrobras.biz') auth.setCredential('--------') auth.setControlFlag('SUFFICIENT') auth.setEnableSIDtoGroupLookupCaching(True) crtwls.log("Configurando outros autenticadores") from weblogic.management.security.authentication import AuthenticatorMBean for tmp in realm.getAuthenticationProviders(): if isinstance(tmp, AuthenticatorMBean): crtwls.log( ".. Ajustando ControlFlag de '%s' para SUFFICIENT" % tmp.getName()) tmp.setControlFlag('SUFFICIENT') crtwls.save() crtwls.log("Configurando grupo Administrador") wlst.serverConfig() realm = wlst.cmo.getSecurityConfiguration().getDefaultRealm() mapper = realm.lookupRoleMapper('XACMLRoleMapper') expr = '{Grp(Administrators)|Grp(GG_BA_TICBA_UNIX_WEB_ADMINS)}' mapper.setRoleExpression(None, 'Admin', expr) expr = '{Grp(AppTesters)|Usr(sawjciba)}' mapper.setRoleExpression(None, 'AppTester', expr) authenticator = classmethod(authenticator) def configure(cls): crtwls.connectToAdminServer() crtwls.edit() domainName = wlst.cmo.getName() crtwls.log("Configurando o Domain Log") wlst.cmo.getLog().setFileMinSize(40000) wlst.cmo.getLog().setNumberOfFilesLimited(True) wlst.cmo.getLog().setFileCount(5) crtwls.log("AdminServer - Configurando") server = wlst.cmo.lookupServer(domainName + '-adminserver') crtwls.log("AdminServer - Ajustando WeblogicPluginEnabled") server.setWeblogicPluginEnabled(True) crtwls.log("AdminServer - Ajustando UploadDirectoryName") server.setUploadDirectoryName('/nonexistent') crtwls.log("AdminServer - Configurando o Server Log") server.getLog().setFileMinSize(40000) server.getLog().setNumberOfFilesLimited(True) server.getLog().setFileCount(5) crtwls.log("AdminServer - Configurando o WebServer") server.getWebServer().setMaxPostSize(15728640) server.getWebServer().setFrontendHost('%s.petrobras.com.br' % domainName) server.getWebServer().setFrontendHTTPPort(80) crtwls.log("AdminServer - Configurando o WebServer Log") server.getWebServer().getWebServerLog().setFileMinSize(40000) server.getWebServer().getWebServerLog().setNumberOfFilesLimited(True) server.getWebServer().getWebServerLog().setFileCount(5) crtwls.save() configure = classmethod(configure) def listDatasource(cls): crtwls.connectToAdminServer() crtwls.edit(False) datasources = wlst.cmo.getJDBCSystemResources() for datasource in datasources: jdbcResource = datasource.getJDBCResource() jndiName = jdbcResource.getJDBCDataSourceParams().getJNDINames()[0] jndiName = jndiName.split('.') appName = jndiName[0] name = jndiName[2] dsList = jdbcResource.getJDBCDataSourceParams().getDataSourceList() if dsList: print '%s new-multidatasource %s "%s"' % (appName, name, dsList) else: drivername = jdbcResource.getJDBCDriverParams().getDriverName() password = jdbcResource.getJDBCDriverParams().getPassword() url = jdbcResource.getJDBCDriverParams().getUrl() props = jdbcResource.getJDBCDriverParams().getProperties() username = props.lookupProperty('user').getValue() if drivername == 'oracle.jdbc.xa.client.OracleXADataSource': cmd = 'new-xadatasource' else: cmd = 'new-datasource' print '%s %s %s "%s" %s %s' % (appName, cmd, name, url, username, password) listDatasource = classmethod(listDatasource) def findMachine(cls, hostname): machines = wlst.cmo.getMachines() for machine in machines: if machine.getNodeManager().getListenAddress() == hostname: return machine findMachine = classmethod(findMachine) def createMachine(cls, hostname): adminAddress = crtwls.getAdminAddress() port = int(adminAddress.split(':')[1]) + 4 name = hostname.split('.')[0] crtwls.connectToAdminServer() crtwls.edit() crtwls.log("Criando a Machine") nmgr = wlst.cmo.createMachine(name) crtwls.log("Configurando a Machine %s" % name) nmgr.getNodeManager().setListenAddress(hostname) nmgr.getNodeManager().setListenPort(port) nmgr.getNodeManager().setDebugEnabled(True) crtwls.save() createMachine = classmethod(createMachine) def mailSession(cls): crtwls.connectToAdminServer() crtwls.edit() crtwls.log("Buscando o MailSession") mailsession = wlst.cmo.lookupMailSession('mail.default') if not mailsession: crtwls.log("Criando o MailSession") mailsession = wlst.cmo.createMailSession('mail.default') mailsession.setJNDIName('mail.default') crtwls.log("Ajustando Targets") clusters = wlst.cmo.getClusters() for cluster in clusters: mailsession.addTarget(cluster) crtwls.log(".. %s" % cluster.getName()) crtwls.log("Ajustando as configurações de SMTP") props = Properties() props.setProperty('mail.transport.protocol', 'smtp') props.setProperty('mail.smtp.host', 'smtp.petrobras.com.br') props.setProperty('mail.smtp.port', '25') props.setProperty('mail.smtp.connectiontimeout', '5000') props.setProperty('mail.smtp.timeout', '10000') mailsession.setProperties(props) crtwls.save() mailSession = classmethod(mailSession) def undeployApps(): crtwls.connectToAdminServer() crtwls.log("Obtendo lista de Aplicacoes") appList = wlst.cmo.getAppDeployments() for app in appList: if not app.getName().startswith('crtwls-'): crtwls.log("Desinstalando Aplicacao: " + app.getName()) wlst.undeploy(app.getName()) undeployApps = classmethod(undeployApps) def decrypt(cls, encryptedText): domainHome = System.getenv("DOMAIN_HOME") encryptionService = SerializedSystemIni.getEncryptionService( domainHome) ceService = ClearOrEncryptedService(encryptionService) clearText = ceService.decrypt(encryptedText) print '>>', clearText decrypt = classmethod(decrypt) def decryptProperties(cls, propertiesFile): domainApp = System.getenv("DOMAIN_APP") domainHome = System.getenv("DOMAIN_HOME") encryptionService = SerializedSystemIni.getEncryptionService( domainHome) ceService = ClearOrEncryptedService(encryptionService) propertiesFile = '%s/%s' % (domainApp, propertiesFile) fis = FileInputStream(propertiesFile) props = Properties() props.load(fis) fis.close() changed = False for entry in props.entrySet(): value = entry.getValue() if ceService.isEncrypted(value): clearText = ceService.decrypt(value) props.setProperty(entry.getKey(), clearText) changed = True if changed: fos = FileOutputStream(propertiesFile) props.store(fos, None) fos.close() decryptProperties = classmethod(decryptProperties) def restartRunningManagedServers(cls): crtwls.connectToAdminServer() wlst.domainRuntime() server_lifecycles = wlst.cmo.getServerLifeCycleRuntimes() for server_lifecycle in server_lifecycles: if (server_lifecycle.getState() == 'RUNNING' and server_lifecycle.getName() != wlst.serverName): wlst.shutdown( server_lifecycle.getName(), 'Server', 'true', 1000, block='true') print "Waiting process to shutdown..." while (server_lifecycle.getState() != "SHUTDOWN"): time.sleep(1) print "." print "OK" wlst.start(server_lifecycle.getName()) else: print 'Doing nothing: ' + server_lifecycle.getName() + ' state: ' + server_lifecycle.getState() restartRunningManagedServers = classmethod(restartRunningManagedServers) def usage(): print "Usage: %s" % sys.argv[0] print """ domain create <domainName> <envSuffix> <adminAddress> domain configure domain configure-authenticator domain configure-mailsession domain create-machine <hostname> domain list-datasource domain undeploy-apps domain decrypt <text> domain decrypt-properties <file> #inline decrypt domain restart-running-servers application <appname> create-env [group] application <appname> create-cluster application <appname> create-server <hostname> <port> <serial> [memory] application <appname> new-datasource <name> <url> <username> <password> application <appname> new-xadatasource <name> <url> <username> <password> application <appname> new-multidatasource <name> <dslist> application <appname> new-jmsqueue <name> application <appname> redeploy <path> """ sys.exit(2) def openConfig(): global config config = ConfigParser.ConfigParser() try: cfgfile = open('crtwls.cfg') config.readfp(cfgfile) except IOError as e: pass def closeConfig(): global config cfgfile = open('crtwls.cfg', 'wb') config.write(cfgfile) def argv(idx): if len(sys.argv) <= idx: usage() return sys.argv[idx] if __name__ == "__main__": try: openConfig() cmd = argv(1) if cmd == 'application': appName = argv(2) subcmd = argv(3) application = Application(appName) if subcmd == 'create-env': group = None if len(sys.argv) > 4: group = argv(4) application.createEnv(group) elif subcmd == 'create-cluster': Cluster.createCluster(application) elif subcmd == 'create-server': hostname = argv(4) port = int(argv(5)) serial = argv(6) memory = None if len(sys.argv) > 7: memory = argv(7) Cluster.createManagedServer( application, hostname, port, serial, memory) elif subcmd == 'new-datasource': name = argv(4) url = argv(5) username = argv(6) password = argv(7) application.newDatasource(name, url, username, password, False) elif subcmd == 'new-xadatasource': name = argv(4) url = argv(5) username = argv(6) password = argv(7) application.newDatasource(name, url, username, password, True) elif subcmd == 'new-multidatasource': name = argv(4) dsList = argv(5) application.newMultiDatasource(name, dsList) elif subcmd == 'new-jmsqueue': name = argv(4) JMSModule.createJMSQueue(application, name) elif subcmd == 'redeploy': path = argv(4) application.redeploy(path) elif cmd == 'domain': subcmd = argv(2) if subcmd == 'create': domainName = argv(3) envSuffix = argv(4) adminAddress = argv(5) Domain.create(domainName, envSuffix, adminAddress) elif subcmd == 'configure': Domain.configure() elif subcmd == 'configure-authenticator': Domain.authenticator() elif subcmd == 'list-datasource': Domain.listDatasource() elif subcmd == 'configure-mailsession': Domain.mailSession() elif subcmd == 'create-machine': hostname = argv(3) Domain.createMachine(hostname) elif subcmd == 'undeploy-apps': Domain.undeployApps() elif subcmd == 'decrypt': text = argv(3) Domain.decrypt(text) elif subcmd == 'decrypt-properties': propertiesFile = argv(3) Domain.decryptProperties(propertiesFile) elif subcmd == 'restart-running-servers': Domain.restartRunningManagedServers() else: usage() finally: closeConfig()
gpl-3.0
-8,570,533,955,969,258,000
31.525783
111
0.60898
false
vikatory/kbengine
kbe/src/lib/python/Lib/idlelib/idle_test/test_formatparagraph.py
73
14351
# Test the functions and main class method of FormatParagraph.py import unittest from idlelib import FormatParagraph as fp from idlelib.EditorWindow import EditorWindow from tkinter import Tk, Text, TclError from test.support import requires class Is_Get_Test(unittest.TestCase): """Test the is_ and get_ functions""" test_comment = '# This is a comment' test_nocomment = 'This is not a comment' trailingws_comment = '# This is a comment ' leadingws_comment = ' # This is a comment' leadingws_nocomment = ' This is not a comment' def test_is_all_white(self): self.assertTrue(fp.is_all_white('')) self.assertTrue(fp.is_all_white('\t\n\r\f\v')) self.assertFalse(fp.is_all_white(self.test_comment)) def test_get_indent(self): Equal = self.assertEqual Equal(fp.get_indent(self.test_comment), '') Equal(fp.get_indent(self.trailingws_comment), '') Equal(fp.get_indent(self.leadingws_comment), ' ') Equal(fp.get_indent(self.leadingws_nocomment), ' ') def test_get_comment_header(self): Equal = self.assertEqual # Test comment strings Equal(fp.get_comment_header(self.test_comment), '#') Equal(fp.get_comment_header(self.trailingws_comment), '#') Equal(fp.get_comment_header(self.leadingws_comment), ' #') # Test non-comment strings Equal(fp.get_comment_header(self.leadingws_nocomment), ' ') Equal(fp.get_comment_header(self.test_nocomment), '') class FindTest(unittest.TestCase): """Test the find_paragraph function in FormatParagraph. Using the runcase() function, find_paragraph() is called with 'mark' set at multiple indexes before and inside the test paragraph. It appears that code with the same indentation as a quoted string is grouped as part of the same paragraph, which is probably incorrect behavior. """ @classmethod def setUpClass(cls): from idlelib.idle_test.mock_tk import Text cls.text = Text() def runcase(self, inserttext, stopline, expected): # Check that find_paragraph returns the expected paragraph when # the mark index is set to beginning, middle, end of each line # up to but not including the stop line text = self.text text.insert('1.0', inserttext) for line in range(1, stopline): linelength = int(text.index("%d.end" % line).split('.')[1]) for col in (0, linelength//2, linelength): tempindex = "%d.%d" % (line, col) self.assertEqual(fp.find_paragraph(text, tempindex), expected) text.delete('1.0', 'end') def test_find_comment(self): comment = ( "# Comment block with no blank lines before\n" "# Comment line\n" "\n") self.runcase(comment, 3, ('1.0', '3.0', '#', comment[0:58])) comment = ( "\n" "# Comment block with whitespace line before and after\n" "# Comment line\n" "\n") self.runcase(comment, 4, ('2.0', '4.0', '#', comment[1:70])) comment = ( "\n" " # Indented comment block with whitespace before and after\n" " # Comment line\n" "\n") self.runcase(comment, 4, ('2.0', '4.0', ' #', comment[1:82])) comment = ( "\n" "# Single line comment\n" "\n") self.runcase(comment, 3, ('2.0', '3.0', '#', comment[1:23])) comment = ( "\n" " # Single line comment with leading whitespace\n" "\n") self.runcase(comment, 3, ('2.0', '3.0', ' #', comment[1:51])) comment = ( "\n" "# Comment immediately followed by code\n" "x = 42\n" "\n") self.runcase(comment, 3, ('2.0', '3.0', '#', comment[1:40])) comment = ( "\n" " # Indented comment immediately followed by code\n" "x = 42\n" "\n") self.runcase(comment, 3, ('2.0', '3.0', ' #', comment[1:53])) comment = ( "\n" "# Comment immediately followed by indented code\n" " x = 42\n" "\n") self.runcase(comment, 3, ('2.0', '3.0', '#', comment[1:49])) def test_find_paragraph(self): teststring = ( '"""String with no blank lines before\n' 'String line\n' '"""\n' '\n') self.runcase(teststring, 4, ('1.0', '4.0', '', teststring[0:53])) teststring = ( "\n" '"""String with whitespace line before and after\n' 'String line.\n' '"""\n' '\n') self.runcase(teststring, 5, ('2.0', '5.0', '', teststring[1:66])) teststring = ( '\n' ' """Indented string with whitespace before and after\n' ' Comment string.\n' ' """\n' '\n') self.runcase(teststring, 5, ('2.0', '5.0', ' ', teststring[1:85])) teststring = ( '\n' '"""Single line string."""\n' '\n') self.runcase(teststring, 3, ('2.0', '3.0', '', teststring[1:27])) teststring = ( '\n' ' """Single line string with leading whitespace."""\n' '\n') self.runcase(teststring, 3, ('2.0', '3.0', ' ', teststring[1:55])) class ReformatFunctionTest(unittest.TestCase): """Test the reformat_paragraph function without the editor window.""" def test_reformat_paragrah(self): Equal = self.assertEqual reform = fp.reformat_paragraph hw = "O hello world" Equal(reform(' ', 1), ' ') Equal(reform("Hello world", 20), "Hello world") # Test without leading newline Equal(reform(hw, 1), "O\nhello\nworld") Equal(reform(hw, 6), "O\nhello\nworld") Equal(reform(hw, 7), "O hello\nworld") Equal(reform(hw, 12), "O hello\nworld") Equal(reform(hw, 13), "O hello world") # Test with leading newline hw = "\nO hello world" Equal(reform(hw, 1), "\nO\nhello\nworld") Equal(reform(hw, 6), "\nO\nhello\nworld") Equal(reform(hw, 7), "\nO hello\nworld") Equal(reform(hw, 12), "\nO hello\nworld") Equal(reform(hw, 13), "\nO hello world") class ReformatCommentTest(unittest.TestCase): """Test the reformat_comment function without the editor window.""" def test_reformat_comment(self): Equal = self.assertEqual # reformat_comment formats to a minimum of 20 characters test_string = ( " \"\"\"this is a test of a reformat for a triple quoted string" " will it reformat to less than 70 characters for me?\"\"\"") result = fp.reformat_comment(test_string, 70, " ") expected = ( " \"\"\"this is a test of a reformat for a triple quoted string will it\n" " reformat to less than 70 characters for me?\"\"\"") Equal(result, expected) test_comment = ( "# this is a test of a reformat for a triple quoted string will " "it reformat to less than 70 characters for me?") result = fp.reformat_comment(test_comment, 70, "#") expected = ( "# this is a test of a reformat for a triple quoted string will it\n" "# reformat to less than 70 characters for me?") Equal(result, expected) class FormatClassTest(unittest.TestCase): def test_init_close(self): instance = fp.FormatParagraph('editor') self.assertEqual(instance.editwin, 'editor') instance.close() self.assertEqual(instance.editwin, None) # For testing format_paragraph_event, Initialize FormatParagraph with # a mock Editor with .text and .get_selection_indices. The text must # be a Text wrapper that adds two methods # A real EditorWindow creates unneeded, time-consuming baggage and # sometimes emits shutdown warnings like this: # "warning: callback failed in WindowList <class '_tkinter.TclError'> # : invalid command name ".55131368.windows". # Calling EditorWindow._close in tearDownClass prevents this but causes # other problems (windows left open). class TextWrapper: def __init__(self, master): self.text = Text(master=master) def __getattr__(self, name): return getattr(self.text, name) def undo_block_start(self): pass def undo_block_stop(self): pass class Editor: def __init__(self, root): self.text = TextWrapper(root) get_selection_indices = EditorWindow. get_selection_indices class FormatEventTest(unittest.TestCase): """Test the formatting of text inside a Text widget. This is done with FormatParagraph.format.paragraph_event, which calls functions in the module as appropriate. """ test_string = ( " '''this is a test of a reformat for a triple " "quoted string will it reformat to less than 70 " "characters for me?'''\n") multiline_test_string = ( " '''The first line is under the max width.\n" " The second line's length is way over the max width. It goes " "on and on until it is over 100 characters long.\n" " Same thing with the third line. It is also way over the max " "width, but FormatParagraph will fix it.\n" " '''\n") multiline_test_comment = ( "# The first line is under the max width.\n" "# The second line's length is way over the max width. It goes on " "and on until it is over 100 characters long.\n" "# Same thing with the third line. It is also way over the max " "width, but FormatParagraph will fix it.\n" "# The fourth line is short like the first line.") @classmethod def setUpClass(cls): requires('gui') cls.root = Tk() editor = Editor(root=cls.root) cls.text = editor.text.text # Test code does not need the wrapper. cls.formatter = fp.FormatParagraph(editor).format_paragraph_event # Sets the insert mark just after the re-wrapped and inserted text. @classmethod def tearDownClass(cls): cls.root.destroy() del cls.root del cls.text del cls.formatter def test_short_line(self): self.text.insert('1.0', "Short line\n") self.formatter("Dummy") self.assertEqual(self.text.get('1.0', 'insert'), "Short line\n" ) self.text.delete('1.0', 'end') def test_long_line(self): text = self.text # Set cursor ('insert' mark) to '1.0', within text. text.insert('1.0', self.test_string) text.mark_set('insert', '1.0') self.formatter('ParameterDoesNothing', limit=70) result = text.get('1.0', 'insert') # find function includes \n expected = ( " '''this is a test of a reformat for a triple quoted string will it\n" " reformat to less than 70 characters for me?'''\n") # yes self.assertEqual(result, expected) text.delete('1.0', 'end') # Select from 1.11 to line end. text.insert('1.0', self.test_string) text.tag_add('sel', '1.11', '1.end') self.formatter('ParameterDoesNothing', limit=70) result = text.get('1.0', 'insert') # selection excludes \n expected = ( " '''this is a test of a reformat for a triple quoted string will it reformat\n" " to less than 70 characters for me?'''") # no self.assertEqual(result, expected) text.delete('1.0', 'end') def test_multiple_lines(self): text = self.text # Select 2 long lines. text.insert('1.0', self.multiline_test_string) text.tag_add('sel', '2.0', '4.0') self.formatter('ParameterDoesNothing', limit=70) result = text.get('2.0', 'insert') expected = ( " The second line's length is way over the max width. It goes on and\n" " on until it is over 100 characters long. Same thing with the third\n" " line. It is also way over the max width, but FormatParagraph will\n" " fix it.\n") self.assertEqual(result, expected) text.delete('1.0', 'end') def test_comment_block(self): text = self.text # Set cursor ('insert') to '1.0', within block. text.insert('1.0', self.multiline_test_comment) self.formatter('ParameterDoesNothing', limit=70) result = text.get('1.0', 'insert') expected = ( "# The first line is under the max width. The second line's length is\n" "# way over the max width. It goes on and on until it is over 100\n" "# characters long. Same thing with the third line. It is also way over\n" "# the max width, but FormatParagraph will fix it. The fourth line is\n" "# short like the first line.\n") self.assertEqual(result, expected) text.delete('1.0', 'end') # Select line 2, verify line 1 unaffected. text.insert('1.0', self.multiline_test_comment) text.tag_add('sel', '2.0', '3.0') self.formatter('ParameterDoesNothing', limit=70) result = text.get('1.0', 'insert') expected = ( "# The first line is under the max width.\n" "# The second line's length is way over the max width. It goes on and\n" "# on until it is over 100 characters long.\n") self.assertEqual(result, expected) text.delete('1.0', 'end') # The following block worked with EditorWindow but fails with the mock. # Lines 2 and 3 get pasted together even though the previous block left # the previous line alone. More investigation is needed. ## # Select lines 3 and 4 ## text.insert('1.0', self.multiline_test_comment) ## text.tag_add('sel', '3.0', '5.0') ## self.formatter('ParameterDoesNothing') ## result = text.get('3.0', 'insert') ## expected = ( ##"# Same thing with the third line. It is also way over the max width,\n" ##"# but FormatParagraph will fix it. The fourth line is short like the\n" ##"# first line.\n") ## self.assertEqual(result, expected) ## text.delete('1.0', 'end') if __name__ == '__main__': unittest.main(verbosity=2, exit=2)
lgpl-3.0
-7,986,859,299,697,650,000
37.066313
89
0.586161
false
vikatory/kbengine
kbe/src/lib/python/Lib/encodings/cp863.py
272
34252
""" Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP863.TXT' with gencodec.py. """#" 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_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_map)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp863', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084: 0x00c2, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0086: 0x00b6, # PILCROW SIGN 0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x008b: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x008c: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x008d: 0x2017, # DOUBLE LOW LINE 0x008e: 0x00c0, # LATIN CAPITAL LETTER A WITH GRAVE 0x008f: 0x00a7, # SECTION SIGN 0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0091: 0x00c8, # LATIN CAPITAL LETTER E WITH GRAVE 0x0092: 0x00ca, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x0094: 0x00cb, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x0095: 0x00cf, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x0097: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x0098: 0x00a4, # CURRENCY SIGN 0x0099: 0x00d4, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x009b: 0x00a2, # CENT SIGN 0x009c: 0x00a3, # POUND SIGN 0x009d: 0x00d9, # LATIN CAPITAL LETTER U WITH GRAVE 0x009e: 0x00db, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK 0x00a0: 0x00a6, # BROKEN BAR 0x00a1: 0x00b4, # ACUTE ACCENT 0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x00a4: 0x00a8, # DIAERESIS 0x00a5: 0x00b8, # CEDILLA 0x00a6: 0x00b3, # SUPERSCRIPT THREE 0x00a7: 0x00af, # MACRON 0x00a8: 0x00ce, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00a9: 0x2310, # REVERSED NOT SIGN 0x00aa: 0x00ac, # NOT SIGN 0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF 0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER 0x00ad: 0x00be, # VULGAR FRACTION THREE QUARTERS 0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 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: 0x03b1, # GREEK SMALL LETTER ALPHA 0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S 0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA 0x00e3: 0x03c0, # GREEK SMALL LETTER PI 0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA 0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA 0x00e6: 0x00b5, # MICRO SIGN 0x00e7: 0x03c4, # GREEK SMALL LETTER TAU 0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI 0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA 0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA 0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA 0x00ec: 0x221e, # INFINITY 0x00ed: 0x03c6, # GREEK SMALL LETTER PHI 0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON 0x00ef: 0x2229, # INTERSECTION 0x00f0: 0x2261, # IDENTICAL TO 0x00f1: 0x00b1, # PLUS-MINUS SIGN 0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO 0x00f3: 0x2264, # LESS-THAN OR EQUAL TO 0x00f4: 0x2320, # TOP HALF INTEGRAL 0x00f5: 0x2321, # BOTTOM HALF INTEGRAL 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 }) ### Decoding Table decoding_table = ( '\x00' # 0x0000 -> NULL '\x01' # 0x0001 -> START OF HEADING '\x02' # 0x0002 -> START OF TEXT '\x03' # 0x0003 -> END OF TEXT '\x04' # 0x0004 -> END OF TRANSMISSION '\x05' # 0x0005 -> ENQUIRY '\x06' # 0x0006 -> ACKNOWLEDGE '\x07' # 0x0007 -> BELL '\x08' # 0x0008 -> BACKSPACE '\t' # 0x0009 -> HORIZONTAL TABULATION '\n' # 0x000a -> LINE FEED '\x0b' # 0x000b -> VERTICAL TABULATION '\x0c' # 0x000c -> FORM FEED '\r' # 0x000d -> CARRIAGE RETURN '\x0e' # 0x000e -> SHIFT OUT '\x0f' # 0x000f -> SHIFT IN '\x10' # 0x0010 -> DATA LINK ESCAPE '\x11' # 0x0011 -> DEVICE CONTROL ONE '\x12' # 0x0012 -> DEVICE CONTROL TWO '\x13' # 0x0013 -> DEVICE CONTROL THREE '\x14' # 0x0014 -> DEVICE CONTROL FOUR '\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE '\x16' # 0x0016 -> SYNCHRONOUS IDLE '\x17' # 0x0017 -> END OF TRANSMISSION BLOCK '\x18' # 0x0018 -> CANCEL '\x19' # 0x0019 -> END OF MEDIUM '\x1a' # 0x001a -> SUBSTITUTE '\x1b' # 0x001b -> ESCAPE '\x1c' # 0x001c -> FILE SEPARATOR '\x1d' # 0x001d -> GROUP SEPARATOR '\x1e' # 0x001e -> RECORD SEPARATOR '\x1f' # 0x001f -> UNIT SEPARATOR ' ' # 0x0020 -> SPACE '!' # 0x0021 -> EXCLAMATION MARK '"' # 0x0022 -> QUOTATION MARK '#' # 0x0023 -> NUMBER SIGN '$' # 0x0024 -> DOLLAR SIGN '%' # 0x0025 -> PERCENT SIGN '&' # 0x0026 -> AMPERSAND "'" # 0x0027 -> APOSTROPHE '(' # 0x0028 -> LEFT PARENTHESIS ')' # 0x0029 -> RIGHT PARENTHESIS '*' # 0x002a -> ASTERISK '+' # 0x002b -> PLUS SIGN ',' # 0x002c -> COMMA '-' # 0x002d -> HYPHEN-MINUS '.' # 0x002e -> FULL STOP '/' # 0x002f -> SOLIDUS '0' # 0x0030 -> DIGIT ZERO '1' # 0x0031 -> DIGIT ONE '2' # 0x0032 -> DIGIT TWO '3' # 0x0033 -> DIGIT THREE '4' # 0x0034 -> DIGIT FOUR '5' # 0x0035 -> DIGIT FIVE '6' # 0x0036 -> DIGIT SIX '7' # 0x0037 -> DIGIT SEVEN '8' # 0x0038 -> DIGIT EIGHT '9' # 0x0039 -> DIGIT NINE ':' # 0x003a -> COLON ';' # 0x003b -> SEMICOLON '<' # 0x003c -> LESS-THAN SIGN '=' # 0x003d -> EQUALS SIGN '>' # 0x003e -> GREATER-THAN SIGN '?' # 0x003f -> QUESTION MARK '@' # 0x0040 -> COMMERCIAL AT 'A' # 0x0041 -> LATIN CAPITAL LETTER A 'B' # 0x0042 -> LATIN CAPITAL LETTER B 'C' # 0x0043 -> LATIN CAPITAL LETTER C 'D' # 0x0044 -> LATIN CAPITAL LETTER D 'E' # 0x0045 -> LATIN CAPITAL LETTER E 'F' # 0x0046 -> LATIN CAPITAL LETTER F 'G' # 0x0047 -> LATIN CAPITAL LETTER G 'H' # 0x0048 -> LATIN CAPITAL LETTER H 'I' # 0x0049 -> LATIN CAPITAL LETTER I 'J' # 0x004a -> LATIN CAPITAL LETTER J 'K' # 0x004b -> LATIN CAPITAL LETTER K 'L' # 0x004c -> LATIN CAPITAL LETTER L 'M' # 0x004d -> LATIN CAPITAL LETTER M 'N' # 0x004e -> LATIN CAPITAL LETTER N 'O' # 0x004f -> LATIN CAPITAL LETTER O 'P' # 0x0050 -> LATIN CAPITAL LETTER P 'Q' # 0x0051 -> LATIN CAPITAL LETTER Q 'R' # 0x0052 -> LATIN CAPITAL LETTER R 'S' # 0x0053 -> LATIN CAPITAL LETTER S 'T' # 0x0054 -> LATIN CAPITAL LETTER T 'U' # 0x0055 -> LATIN CAPITAL LETTER U 'V' # 0x0056 -> LATIN CAPITAL LETTER V 'W' # 0x0057 -> LATIN CAPITAL LETTER W 'X' # 0x0058 -> LATIN CAPITAL LETTER X 'Y' # 0x0059 -> LATIN CAPITAL LETTER Y 'Z' # 0x005a -> LATIN CAPITAL LETTER Z '[' # 0x005b -> LEFT SQUARE BRACKET '\\' # 0x005c -> REVERSE SOLIDUS ']' # 0x005d -> RIGHT SQUARE BRACKET '^' # 0x005e -> CIRCUMFLEX ACCENT '_' # 0x005f -> LOW LINE '`' # 0x0060 -> GRAVE ACCENT 'a' # 0x0061 -> LATIN SMALL LETTER A 'b' # 0x0062 -> LATIN SMALL LETTER B 'c' # 0x0063 -> LATIN SMALL LETTER C 'd' # 0x0064 -> LATIN SMALL LETTER D 'e' # 0x0065 -> LATIN SMALL LETTER E 'f' # 0x0066 -> LATIN SMALL LETTER F 'g' # 0x0067 -> LATIN SMALL LETTER G 'h' # 0x0068 -> LATIN SMALL LETTER H 'i' # 0x0069 -> LATIN SMALL LETTER I 'j' # 0x006a -> LATIN SMALL LETTER J 'k' # 0x006b -> LATIN SMALL LETTER K 'l' # 0x006c -> LATIN SMALL LETTER L 'm' # 0x006d -> LATIN SMALL LETTER M 'n' # 0x006e -> LATIN SMALL LETTER N 'o' # 0x006f -> LATIN SMALL LETTER O 'p' # 0x0070 -> LATIN SMALL LETTER P 'q' # 0x0071 -> LATIN SMALL LETTER Q 'r' # 0x0072 -> LATIN SMALL LETTER R 's' # 0x0073 -> LATIN SMALL LETTER S 't' # 0x0074 -> LATIN SMALL LETTER T 'u' # 0x0075 -> LATIN SMALL LETTER U 'v' # 0x0076 -> LATIN SMALL LETTER V 'w' # 0x0077 -> LATIN SMALL LETTER W 'x' # 0x0078 -> LATIN SMALL LETTER X 'y' # 0x0079 -> LATIN SMALL LETTER Y 'z' # 0x007a -> LATIN SMALL LETTER Z '{' # 0x007b -> LEFT CURLY BRACKET '|' # 0x007c -> VERTICAL LINE '}' # 0x007d -> RIGHT CURLY BRACKET '~' # 0x007e -> TILDE '\x7f' # 0x007f -> DELETE '\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA '\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS '\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE '\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX '\xc2' # 0x0084 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX '\xe0' # 0x0085 -> LATIN SMALL LETTER A WITH GRAVE '\xb6' # 0x0086 -> PILCROW SIGN '\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA '\xea' # 0x0088 -> LATIN SMALL LETTER E WITH CIRCUMFLEX '\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS '\xe8' # 0x008a -> LATIN SMALL LETTER E WITH GRAVE '\xef' # 0x008b -> LATIN SMALL LETTER I WITH DIAERESIS '\xee' # 0x008c -> LATIN SMALL LETTER I WITH CIRCUMFLEX '\u2017' # 0x008d -> DOUBLE LOW LINE '\xc0' # 0x008e -> LATIN CAPITAL LETTER A WITH GRAVE '\xa7' # 0x008f -> SECTION SIGN '\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE '\xc8' # 0x0091 -> LATIN CAPITAL LETTER E WITH GRAVE '\xca' # 0x0092 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX '\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX '\xcb' # 0x0094 -> LATIN CAPITAL LETTER E WITH DIAERESIS '\xcf' # 0x0095 -> LATIN CAPITAL LETTER I WITH DIAERESIS '\xfb' # 0x0096 -> LATIN SMALL LETTER U WITH CIRCUMFLEX '\xf9' # 0x0097 -> LATIN SMALL LETTER U WITH GRAVE '\xa4' # 0x0098 -> CURRENCY SIGN '\xd4' # 0x0099 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX '\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS '\xa2' # 0x009b -> CENT SIGN '\xa3' # 0x009c -> POUND SIGN '\xd9' # 0x009d -> LATIN CAPITAL LETTER U WITH GRAVE '\xdb' # 0x009e -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX '\u0192' # 0x009f -> LATIN SMALL LETTER F WITH HOOK '\xa6' # 0x00a0 -> BROKEN BAR '\xb4' # 0x00a1 -> ACUTE ACCENT '\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE '\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE '\xa8' # 0x00a4 -> DIAERESIS '\xb8' # 0x00a5 -> CEDILLA '\xb3' # 0x00a6 -> SUPERSCRIPT THREE '\xaf' # 0x00a7 -> MACRON '\xce' # 0x00a8 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX '\u2310' # 0x00a9 -> REVERSED NOT SIGN '\xac' # 0x00aa -> NOT SIGN '\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF '\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER '\xbe' # 0x00ad -> VULGAR FRACTION THREE QUARTERS '\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK '\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK '\u2591' # 0x00b0 -> LIGHT SHADE '\u2592' # 0x00b1 -> MEDIUM SHADE '\u2593' # 0x00b2 -> DARK SHADE '\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL '\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT '\u2561' # 0x00b5 -> BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE '\u2562' # 0x00b6 -> BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE '\u2556' # 0x00b7 -> BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE '\u2555' # 0x00b8 -> BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE '\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT '\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL '\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT '\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT '\u255c' # 0x00bd -> BOX DRAWINGS UP DOUBLE AND LEFT SINGLE '\u255b' # 0x00be -> BOX DRAWINGS UP SINGLE AND LEFT DOUBLE '\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT '\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT '\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL '\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL '\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT '\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL '\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL '\u255e' # 0x00c6 -> BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE '\u255f' # 0x00c7 -> BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE '\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT '\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT '\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL '\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL '\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT '\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL '\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL '\u2567' # 0x00cf -> BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE '\u2568' # 0x00d0 -> BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE '\u2564' # 0x00d1 -> BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE '\u2565' # 0x00d2 -> BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE '\u2559' # 0x00d3 -> BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE '\u2558' # 0x00d4 -> BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE '\u2552' # 0x00d5 -> BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE '\u2553' # 0x00d6 -> BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE '\u256b' # 0x00d7 -> BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE '\u256a' # 0x00d8 -> BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE '\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT '\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT '\u2588' # 0x00db -> FULL BLOCK '\u2584' # 0x00dc -> LOWER HALF BLOCK '\u258c' # 0x00dd -> LEFT HALF BLOCK '\u2590' # 0x00de -> RIGHT HALF BLOCK '\u2580' # 0x00df -> UPPER HALF BLOCK '\u03b1' # 0x00e0 -> GREEK SMALL LETTER ALPHA '\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S '\u0393' # 0x00e2 -> GREEK CAPITAL LETTER GAMMA '\u03c0' # 0x00e3 -> GREEK SMALL LETTER PI '\u03a3' # 0x00e4 -> GREEK CAPITAL LETTER SIGMA '\u03c3' # 0x00e5 -> GREEK SMALL LETTER SIGMA '\xb5' # 0x00e6 -> MICRO SIGN '\u03c4' # 0x00e7 -> GREEK SMALL LETTER TAU '\u03a6' # 0x00e8 -> GREEK CAPITAL LETTER PHI '\u0398' # 0x00e9 -> GREEK CAPITAL LETTER THETA '\u03a9' # 0x00ea -> GREEK CAPITAL LETTER OMEGA '\u03b4' # 0x00eb -> GREEK SMALL LETTER DELTA '\u221e' # 0x00ec -> INFINITY '\u03c6' # 0x00ed -> GREEK SMALL LETTER PHI '\u03b5' # 0x00ee -> GREEK SMALL LETTER EPSILON '\u2229' # 0x00ef -> INTERSECTION '\u2261' # 0x00f0 -> IDENTICAL TO '\xb1' # 0x00f1 -> PLUS-MINUS SIGN '\u2265' # 0x00f2 -> GREATER-THAN OR EQUAL TO '\u2264' # 0x00f3 -> LESS-THAN OR EQUAL TO '\u2320' # 0x00f4 -> TOP HALF INTEGRAL '\u2321' # 0x00f5 -> BOTTOM HALF INTEGRAL '\xf7' # 0x00f6 -> DIVISION SIGN '\u2248' # 0x00f7 -> ALMOST EQUAL TO '\xb0' # 0x00f8 -> DEGREE SIGN '\u2219' # 0x00f9 -> BULLET OPERATOR '\xb7' # 0x00fa -> MIDDLE DOT '\u221a' # 0x00fb -> SQUARE ROOT '\u207f' # 0x00fc -> SUPERSCRIPT LATIN SMALL LETTER N '\xb2' # 0x00fd -> SUPERSCRIPT TWO '\u25a0' # 0x00fe -> BLACK SQUARE '\xa0' # 0x00ff -> NO-BREAK SPACE ) ### Encoding Map encoding_map = { 0x0000: 0x0000, # NULL 0x0001: 0x0001, # START OF HEADING 0x0002: 0x0002, # START OF TEXT 0x0003: 0x0003, # END OF TEXT 0x0004: 0x0004, # END OF TRANSMISSION 0x0005: 0x0005, # ENQUIRY 0x0006: 0x0006, # ACKNOWLEDGE 0x0007: 0x0007, # BELL 0x0008: 0x0008, # BACKSPACE 0x0009: 0x0009, # HORIZONTAL TABULATION 0x000a: 0x000a, # LINE FEED 0x000b: 0x000b, # VERTICAL TABULATION 0x000c: 0x000c, # FORM FEED 0x000d: 0x000d, # CARRIAGE RETURN 0x000e: 0x000e, # SHIFT OUT 0x000f: 0x000f, # SHIFT IN 0x0010: 0x0010, # DATA LINK ESCAPE 0x0011: 0x0011, # DEVICE CONTROL ONE 0x0012: 0x0012, # DEVICE CONTROL TWO 0x0013: 0x0013, # DEVICE CONTROL THREE 0x0014: 0x0014, # DEVICE CONTROL FOUR 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE 0x0016: 0x0016, # SYNCHRONOUS IDLE 0x0017: 0x0017, # END OF TRANSMISSION BLOCK 0x0018: 0x0018, # CANCEL 0x0019: 0x0019, # END OF MEDIUM 0x001a: 0x001a, # SUBSTITUTE 0x001b: 0x001b, # ESCAPE 0x001c: 0x001c, # FILE SEPARATOR 0x001d: 0x001d, # GROUP SEPARATOR 0x001e: 0x001e, # RECORD SEPARATOR 0x001f: 0x001f, # UNIT SEPARATOR 0x0020: 0x0020, # SPACE 0x0021: 0x0021, # EXCLAMATION MARK 0x0022: 0x0022, # QUOTATION MARK 0x0023: 0x0023, # NUMBER SIGN 0x0024: 0x0024, # DOLLAR SIGN 0x0025: 0x0025, # PERCENT SIGN 0x0026: 0x0026, # AMPERSAND 0x0027: 0x0027, # APOSTROPHE 0x0028: 0x0028, # LEFT PARENTHESIS 0x0029: 0x0029, # RIGHT PARENTHESIS 0x002a: 0x002a, # ASTERISK 0x002b: 0x002b, # PLUS SIGN 0x002c: 0x002c, # COMMA 0x002d: 0x002d, # HYPHEN-MINUS 0x002e: 0x002e, # FULL STOP 0x002f: 0x002f, # SOLIDUS 0x0030: 0x0030, # DIGIT ZERO 0x0031: 0x0031, # DIGIT ONE 0x0032: 0x0032, # DIGIT TWO 0x0033: 0x0033, # DIGIT THREE 0x0034: 0x0034, # DIGIT FOUR 0x0035: 0x0035, # DIGIT FIVE 0x0036: 0x0036, # DIGIT SIX 0x0037: 0x0037, # DIGIT SEVEN 0x0038: 0x0038, # DIGIT EIGHT 0x0039: 0x0039, # DIGIT NINE 0x003a: 0x003a, # COLON 0x003b: 0x003b, # SEMICOLON 0x003c: 0x003c, # LESS-THAN SIGN 0x003d: 0x003d, # EQUALS SIGN 0x003e: 0x003e, # GREATER-THAN SIGN 0x003f: 0x003f, # QUESTION MARK 0x0040: 0x0040, # COMMERCIAL AT 0x0041: 0x0041, # LATIN CAPITAL LETTER A 0x0042: 0x0042, # LATIN CAPITAL LETTER B 0x0043: 0x0043, # LATIN CAPITAL LETTER C 0x0044: 0x0044, # LATIN CAPITAL LETTER D 0x0045: 0x0045, # LATIN CAPITAL LETTER E 0x0046: 0x0046, # LATIN CAPITAL LETTER F 0x0047: 0x0047, # LATIN CAPITAL LETTER G 0x0048: 0x0048, # LATIN CAPITAL LETTER H 0x0049: 0x0049, # LATIN CAPITAL LETTER I 0x004a: 0x004a, # LATIN CAPITAL LETTER J 0x004b: 0x004b, # LATIN CAPITAL LETTER K 0x004c: 0x004c, # LATIN CAPITAL LETTER L 0x004d: 0x004d, # LATIN CAPITAL LETTER M 0x004e: 0x004e, # LATIN CAPITAL LETTER N 0x004f: 0x004f, # LATIN CAPITAL LETTER O 0x0050: 0x0050, # LATIN CAPITAL LETTER P 0x0051: 0x0051, # LATIN CAPITAL LETTER Q 0x0052: 0x0052, # LATIN CAPITAL LETTER R 0x0053: 0x0053, # LATIN CAPITAL LETTER S 0x0054: 0x0054, # LATIN CAPITAL LETTER T 0x0055: 0x0055, # LATIN CAPITAL LETTER U 0x0056: 0x0056, # LATIN CAPITAL LETTER V 0x0057: 0x0057, # LATIN CAPITAL LETTER W 0x0058: 0x0058, # LATIN CAPITAL LETTER X 0x0059: 0x0059, # LATIN CAPITAL LETTER Y 0x005a: 0x005a, # LATIN CAPITAL LETTER Z 0x005b: 0x005b, # LEFT SQUARE BRACKET 0x005c: 0x005c, # REVERSE SOLIDUS 0x005d: 0x005d, # RIGHT SQUARE BRACKET 0x005e: 0x005e, # CIRCUMFLEX ACCENT 0x005f: 0x005f, # LOW LINE 0x0060: 0x0060, # GRAVE ACCENT 0x0061: 0x0061, # LATIN SMALL LETTER A 0x0062: 0x0062, # LATIN SMALL LETTER B 0x0063: 0x0063, # LATIN SMALL LETTER C 0x0064: 0x0064, # LATIN SMALL LETTER D 0x0065: 0x0065, # LATIN SMALL LETTER E 0x0066: 0x0066, # LATIN SMALL LETTER F 0x0067: 0x0067, # LATIN SMALL LETTER G 0x0068: 0x0068, # LATIN SMALL LETTER H 0x0069: 0x0069, # LATIN SMALL LETTER I 0x006a: 0x006a, # LATIN SMALL LETTER J 0x006b: 0x006b, # LATIN SMALL LETTER K 0x006c: 0x006c, # LATIN SMALL LETTER L 0x006d: 0x006d, # LATIN SMALL LETTER M 0x006e: 0x006e, # LATIN SMALL LETTER N 0x006f: 0x006f, # LATIN SMALL LETTER O 0x0070: 0x0070, # LATIN SMALL LETTER P 0x0071: 0x0071, # LATIN SMALL LETTER Q 0x0072: 0x0072, # LATIN SMALL LETTER R 0x0073: 0x0073, # LATIN SMALL LETTER S 0x0074: 0x0074, # LATIN SMALL LETTER T 0x0075: 0x0075, # LATIN SMALL LETTER U 0x0076: 0x0076, # LATIN SMALL LETTER V 0x0077: 0x0077, # LATIN SMALL LETTER W 0x0078: 0x0078, # LATIN SMALL LETTER X 0x0079: 0x0079, # LATIN SMALL LETTER Y 0x007a: 0x007a, # LATIN SMALL LETTER Z 0x007b: 0x007b, # LEFT CURLY BRACKET 0x007c: 0x007c, # VERTICAL LINE 0x007d: 0x007d, # RIGHT CURLY BRACKET 0x007e: 0x007e, # TILDE 0x007f: 0x007f, # DELETE 0x00a0: 0x00ff, # NO-BREAK SPACE 0x00a2: 0x009b, # CENT SIGN 0x00a3: 0x009c, # POUND SIGN 0x00a4: 0x0098, # CURRENCY SIGN 0x00a6: 0x00a0, # BROKEN BAR 0x00a7: 0x008f, # SECTION SIGN 0x00a8: 0x00a4, # DIAERESIS 0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00ac: 0x00aa, # NOT SIGN 0x00af: 0x00a7, # MACRON 0x00b0: 0x00f8, # DEGREE SIGN 0x00b1: 0x00f1, # PLUS-MINUS SIGN 0x00b2: 0x00fd, # SUPERSCRIPT TWO 0x00b3: 0x00a6, # SUPERSCRIPT THREE 0x00b4: 0x00a1, # ACUTE ACCENT 0x00b5: 0x00e6, # MICRO SIGN 0x00b6: 0x0086, # PILCROW SIGN 0x00b7: 0x00fa, # MIDDLE DOT 0x00b8: 0x00a5, # CEDILLA 0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER 0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF 0x00be: 0x00ad, # VULGAR FRACTION THREE QUARTERS 0x00c0: 0x008e, # LATIN CAPITAL LETTER A WITH GRAVE 0x00c2: 0x0084, # LATIN CAPITAL LETTER A WITH CIRCUMFLEX 0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA 0x00c8: 0x0091, # LATIN CAPITAL LETTER E WITH GRAVE 0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE 0x00ca: 0x0092, # LATIN CAPITAL LETTER E WITH CIRCUMFLEX 0x00cb: 0x0094, # LATIN CAPITAL LETTER E WITH DIAERESIS 0x00ce: 0x00a8, # LATIN CAPITAL LETTER I WITH CIRCUMFLEX 0x00cf: 0x0095, # LATIN CAPITAL LETTER I WITH DIAERESIS 0x00d4: 0x0099, # LATIN CAPITAL LETTER O WITH CIRCUMFLEX 0x00d9: 0x009d, # LATIN CAPITAL LETTER U WITH GRAVE 0x00db: 0x009e, # LATIN CAPITAL LETTER U WITH CIRCUMFLEX 0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S 0x00e0: 0x0085, # LATIN SMALL LETTER A WITH GRAVE 0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA 0x00e8: 0x008a, # LATIN SMALL LETTER E WITH GRAVE 0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE 0x00ea: 0x0088, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS 0x00ee: 0x008c, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x00ef: 0x008b, # LATIN SMALL LETTER I WITH DIAERESIS 0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE 0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00f7: 0x00f6, # DIVISION SIGN 0x00f9: 0x0097, # LATIN SMALL LETTER U WITH GRAVE 0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE 0x00fb: 0x0096, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS 0x0192: 0x009f, # LATIN SMALL LETTER F WITH HOOK 0x0393: 0x00e2, # GREEK CAPITAL LETTER GAMMA 0x0398: 0x00e9, # GREEK CAPITAL LETTER THETA 0x03a3: 0x00e4, # GREEK CAPITAL LETTER SIGMA 0x03a6: 0x00e8, # GREEK CAPITAL LETTER PHI 0x03a9: 0x00ea, # GREEK CAPITAL LETTER OMEGA 0x03b1: 0x00e0, # GREEK SMALL LETTER ALPHA 0x03b4: 0x00eb, # GREEK SMALL LETTER DELTA 0x03b5: 0x00ee, # GREEK SMALL LETTER EPSILON 0x03c0: 0x00e3, # GREEK SMALL LETTER PI 0x03c3: 0x00e5, # GREEK SMALL LETTER SIGMA 0x03c4: 0x00e7, # GREEK SMALL LETTER TAU 0x03c6: 0x00ed, # GREEK SMALL LETTER PHI 0x2017: 0x008d, # DOUBLE LOW LINE 0x207f: 0x00fc, # SUPERSCRIPT LATIN SMALL LETTER N 0x2219: 0x00f9, # BULLET OPERATOR 0x221a: 0x00fb, # SQUARE ROOT 0x221e: 0x00ec, # INFINITY 0x2229: 0x00ef, # INTERSECTION 0x2248: 0x00f7, # ALMOST EQUAL TO 0x2261: 0x00f0, # IDENTICAL TO 0x2264: 0x00f3, # LESS-THAN OR EQUAL TO 0x2265: 0x00f2, # GREATER-THAN OR EQUAL TO 0x2310: 0x00a9, # REVERSED NOT SIGN 0x2320: 0x00f4, # TOP HALF INTEGRAL 0x2321: 0x00f5, # BOTTOM HALF INTEGRAL 0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL 0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL 0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT 0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT 0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL 0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL 0x2552: 0x00d5, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x2553: 0x00d6, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2555: 0x00b8, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x2556: 0x00b7, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT 0x2558: 0x00d4, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x2559: 0x00d3, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT 0x255b: 0x00be, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x255c: 0x00bd, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT 0x255e: 0x00c6, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x255f: 0x00c7, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2561: 0x00b5, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x2562: 0x00b6, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2564: 0x00d1, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x2565: 0x00d2, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2567: 0x00cf, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x2568: 0x00d0, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x256a: 0x00d8, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x256b: 0x00d7, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x2580: 0x00df, # UPPER HALF BLOCK 0x2584: 0x00dc, # LOWER HALF BLOCK 0x2588: 0x00db, # FULL BLOCK 0x258c: 0x00dd, # LEFT HALF BLOCK 0x2590: 0x00de, # RIGHT HALF BLOCK 0x2591: 0x00b0, # LIGHT SHADE 0x2592: 0x00b1, # MEDIUM SHADE 0x2593: 0x00b2, # DARK SHADE 0x25a0: 0x00fe, # BLACK SQUARE }
lgpl-3.0
-6,916,906,441,276,573,000
48.071633
97
0.602739
false
vjmac15/Lyilis
lib/youtube_dl/extractor/baidu (VJ Washington's conflicted copy 2017-08-29).py
90
1980
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import unescapeHTML class BaiduVideoIE(InfoExtractor): IE_DESC = '百度视频' _VALID_URL = r'https?://v\.baidu\.com/(?P<type>[a-z]+)/(?P<id>\d+)\.htm' _TESTS = [{ 'url': 'http://v.baidu.com/comic/1069.htm?frp=bdbrand&q=%E4%B8%AD%E5%8D%8E%E5%B0%8F%E5%BD%93%E5%AE%B6', 'info_dict': { 'id': '1069', 'title': '中华小当家 TV版国语', 'description': 'md5:51be07afe461cf99fa61231421b5397c', }, 'playlist_count': 52, }, { 'url': 'http://v.baidu.com/show/11595.htm?frp=bdbrand', 'info_dict': { 'id': '11595', 'title': 're:^奔跑吧兄弟', 'description': 'md5:1bf88bad6d850930f542d51547c089b8', }, 'playlist_mincount': 12, }] def _call_api(self, path, category, playlist_id, note): return self._download_json('http://app.video.baidu.com/%s/?worktype=adnative%s&id=%s' % ( path, category, playlist_id), playlist_id, note) def _real_extract(self, url): category, playlist_id = re.match(self._VALID_URL, url).groups() if category == 'show': category = 'tvshow' if category == 'tv': category = 'tvplay' playlist_detail = self._call_api( 'xqinfo', category, playlist_id, 'Download playlist JSON metadata') playlist_title = playlist_detail['title'] playlist_description = unescapeHTML(playlist_detail.get('intro')) episodes_detail = self._call_api( 'xqsingle', category, playlist_id, 'Download episodes JSON metadata') entries = [self.url_result( episode['url'], video_title=episode['title'] ) for episode in episodes_detail['videos']] return self.playlist_result( entries, playlist_id, playlist_title, playlist_description)
gpl-3.0
8,918,850,448,971,882,000
33.75
111
0.58222
false
Solinea/horizon
openstack_dashboard/dashboards/admin/images/views.py
3
8396
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json import logging from oslo_utils import units from django import conf from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import tables from horizon.utils import memoized from openstack_dashboard import api from openstack_dashboard.dashboards.project.images.images import views from openstack_dashboard.dashboards.admin.images import forms as project_forms from openstack_dashboard.dashboards.admin.images \ import tables as project_tables LOG = logging.getLogger(__name__) class IndexView(tables.DataTableView): table_class = project_tables.AdminImagesTable template_name = 'admin/images/index.html' page_title = _("Images") def has_prev_data(self, table): return self._prev def has_more_data(self, table): return self._more def get_data(self): images = [] filters = self.get_filters() prev_marker = self.request.GET.get( project_tables.AdminImagesTable._meta.prev_pagination_param, None) if prev_marker is not None: sort_dir = 'asc' marker = prev_marker else: sort_dir = 'desc' marker = self.request.GET.get( project_tables.AdminImagesTable._meta.pagination_param, None) try: images, self._more, self._prev = api.glance.image_list_detailed( self.request, marker=marker, paginate=True, filters=filters, sort_dir=sort_dir) if prev_marker is not None: images = sorted(images, key=lambda image: getattr(image, 'created_at'), reverse=True) except Exception: self._prev = False self._more = False msg = _('Unable to retrieve image list.') exceptions.handle(self.request, msg) return images def get_filters(self): filters = {'is_public': None} filter_field = self.table.get_filter_field() filter_string = self.table.get_filter_string() filter_action = self.table._meta._filter_action if filter_field and filter_string and ( filter_action.is_api_filter(filter_field)): if filter_field in ['size_min', 'size_max']: invalid_msg = ('API query is not valid and is ignored: %s=%s' % (filter_field, filter_string)) try: filter_string = long(float(filter_string) * (units.Mi)) if filter_string >= 0: filters[filter_field] = filter_string else: LOG.warning(invalid_msg) except ValueError: LOG.warning(invalid_msg) elif (filter_field == 'disk_format' and filter_string.lower() == 'docker'): filters['disk_format'] = 'raw' filters['container_format'] = 'docker' else: filters[filter_field] = filter_string return filters class CreateView(views.CreateView): template_name = 'admin/images/create.html' form_class = project_forms.AdminCreateImageForm submit_url = reverse_lazy('horizon:admin:images:create') success_url = reverse_lazy('horizon:admin:images:index') page_title = _("Create An Image") class UpdateView(views.UpdateView): template_name = 'admin/images/update.html' form_class = project_forms.AdminUpdateImageForm submit_url = "horizon:admin:images:update" success_url = reverse_lazy('horizon:admin:images:index') page_title = _("Update Image") class DetailView(views.DetailView): def get_context_data(self, **kwargs): context = super(DetailView, self).get_context_data(**kwargs) table = project_tables.AdminImagesTable(self.request) context["url"] = reverse('horizon:admin:images:index') context["actions"] = table.render_row_actions(context["image"]) return context class UpdateMetadataView(forms.ModalFormView): template_name = "admin/images/update_metadata.html" modal_header = _("Update Image") form_id = "update_image_form" form_class = project_forms.UpdateMetadataForm submit_url = "horizon:admin:images:update_metadata" success_url = reverse_lazy('horizon:admin:images:index') page_title = _("Update Image Metadata") def get_initial(self): image = self.get_object() return {'id': self.kwargs["id"], 'metadata': image.properties} def get_context_data(self, **kwargs): context = super(UpdateMetadataView, self).get_context_data(**kwargs) image = self.get_object() reserved_props = getattr(conf.settings, 'IMAGE_RESERVED_CUSTOM_PROPERTIES', []) image.properties = dict((k, v) for (k, v) in image.properties.iteritems() if k not in reserved_props) context['existing_metadata'] = json.dumps(image.properties) args = (self.kwargs['id'],) context['submit_url'] = reverse(self.submit_url, args=args) resource_type = 'OS::Glance::Image' namespaces = [] try: # metadefs_namespace_list() returns a tuple with list as 1st elem available_namespaces = [x.namespace for x in api.glance.metadefs_namespace_list( self.request, filters={"resource_types": [resource_type]} )[0]] for namespace in available_namespaces: details = api.glance.metadefs_namespace_get(self.request, namespace, resource_type) # Filter out reserved custom properties from namespace if reserved_props: if hasattr(details, 'properties'): details.properties = dict( (k, v) for (k, v) in details.properties.iteritems() if k not in reserved_props ) if hasattr(details, 'objects'): for obj in details.objects: obj['properties'] = dict( (k, v) for (k, v) in obj['properties'].iteritems() if k not in reserved_props ) namespaces.append(details) except Exception: msg = _('Unable to retrieve available properties for image.') exceptions.handle(self.request, msg) context['available_metadata'] = json.dumps({'namespaces': namespaces}) context['id'] = self.kwargs['id'] return context @memoized.memoized_method def get_object(self): image_id = self.kwargs['id'] try: return api.glance.image_get(self.request, image_id) except Exception: msg = _('Unable to retrieve the image to be updated.') exceptions.handle(self.request, msg, redirect=reverse('horizon:admin:images:index'))
apache-2.0
3,675,810,975,928,954,000
38.051163
78
0.575989
false
luiseduardohdbackup/odoo
addons/account/wizard/account_move_line_reconcile_select.py
385
2362
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ class account_move_line_reconcile_select(osv.osv_memory): _name = "account.move.line.reconcile.select" _description = "Move line reconcile select" _columns = { 'account_id': fields.many2one('account.account', 'Account', \ domain = [('reconcile', '=', 1)], required=True), } def action_open_window(self, cr, uid, ids, context=None): """ This function Open account move line window for reconcile on given account id @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: account move line reconcile select’s ID or list of IDs @return: dictionary of Open account move line window for reconcile on given account id """ data = self.read(cr, uid, ids, context=context)[0] return { 'domain': "[('account_id','=',%d),('reconcile_id','=',False),('state','<>','draft')]" % data['account_id'], 'name': _('Reconciliation'), 'view_type': 'form', 'view_mode': 'tree,form', 'view_id': False, 'res_model': 'account.move.line', 'type': 'ir.actions.act_window' } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
-3,165,510,815,337,637,000
42.666667
119
0.59542
false
SDX2000/scons
engine/SCons/compat/__init__.py
21
8179
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __doc__ = """ SCons compatibility package for old Python versions This subpackage holds modules that provide backwards-compatible implementations of various things that we'd like to use in SCons but which only show up in later versions of Python than the early, old version(s) we still support. Other code will not generally reference things in this package through the SCons.compat namespace. The modules included here add things to the builtins namespace or the global module list so that the rest of our code can use the objects and names imported here regardless of Python version. Simply enough, things that go in the builtins name space come from our _scons_builtins module. The rest of the things here will be in individual compatibility modules that are either: 1) suitably modified copies of the future modules that we want to use; or 2) backwards compatible re-implementations of the specific portions of a future module's API that we want to use. GENERAL WARNINGS: Implementations of functions in the SCons.compat modules are *NOT* guaranteed to be fully compliant with these functions in later versions of Python. We are only concerned with adding functionality that we actually use in SCons, so be wary if you lift this code for other uses. (That said, making these more nearly the same as later, official versions is still a desirable goal, we just don't need to be obsessive about it.) We name the compatibility modules with an initial '_scons_' (for example, _scons_subprocess.py is our compatibility module for subprocess) so that we can still try to import the real module name and fall back to our compatibility module if we get an ImportError. The import_as() function defined below loads the module as the "real" name (without the '_scons'), after which all of the "import {module}" statements in the rest of our code will find our pre-loaded compatibility module. """ __revision__ = "src/engine/SCons/compat/__init__.py 5357 2011/09/09 21:31:03 bdeegan" import os import sys import imp # Use the "imp" module to protect imports from fixers. def import_as(module, name): """ Imports the specified module (from our local directory) as the specified name, returning the loaded module object. """ dir = os.path.split(__file__)[0] return imp.load_module(name, *imp.find_module(module, [dir])) def rename_module(new, old): """ Attempts to import the old module and load it under the new name. Used for purely cosmetic name changes in Python 3.x. """ try: sys.modules[new] = imp.load_module(old, *imp.find_module(old)) return True except ImportError: return False rename_module('builtins', '__builtin__') import _scons_builtins try: import hashlib except ImportError: # Pre-2.5 Python has no hashlib module. try: import_as('_scons_hashlib', 'hashlib') except ImportError: # If we failed importing our compatibility module, it probably # means this version of Python has no md5 module. Don't do # anything and let the higher layer discover this fact, so it # can fall back to using timestamp. pass try: set except NameError: # Pre-2.4 Python has no native set type import_as('_scons_sets', 'sets') import builtins, sets builtins.set = sets.Set try: import collections except ImportError: # Pre-2.4 Python has no collections module. import_as('_scons_collections', 'collections') else: try: collections.UserDict except AttributeError: exec('from UserDict import UserDict as _UserDict') collections.UserDict = _UserDict del _UserDict try: collections.UserList except AttributeError: exec('from UserList import UserList as _UserList') collections.UserList = _UserList del _UserList try: collections.UserString except AttributeError: exec('from UserString import UserString as _UserString') collections.UserString = _UserString del _UserString try: import io except ImportError: # Pre-2.6 Python has no io module. import_as('_scons_io', 'io') try: os.devnull except AttributeError: # Pre-2.4 Python has no os.devnull attribute _names = sys.builtin_module_names if 'posix' in _names: os.devnull = '/dev/null' elif 'nt' in _names: os.devnull = 'nul' os.path.devnull = os.devnull try: os.path.lexists except AttributeError: # Pre-2.4 Python has no os.path.lexists function def lexists(path): return os.path.exists(path) or os.path.islink(path) os.path.lexists = lexists # When we're using the '-3' option during regression tests, importing # cPickle gives a warning no matter how it's done, so always use the # real profile module, whether it's fast or not. if os.environ.get('SCONS_HORRIBLE_REGRESSION_TEST_HACK') is None: # Not a regression test with '-3', so try to use faster version. # In 3.x, 'pickle' automatically loads the fast version if available. rename_module('pickle', 'cPickle') # In 3.x, 'profile' automatically loads the fast version if available. rename_module('profile', 'cProfile') # Before Python 3.0, the 'queue' module was named 'Queue'. rename_module('queue', 'Queue') # Before Python 3.0, the 'winreg' module was named '_winreg' rename_module('winreg', '_winreg') try: import subprocess except ImportError: # Pre-2.4 Python has no subprocess module. import_as('_scons_subprocess', 'subprocess') try: sys.intern except AttributeError: # Pre-2.6 Python has no sys.intern() function. import builtins try: sys.intern = builtins.intern except AttributeError: # Pre-2.x Python has no builtin intern() function. def intern(x): return x sys.intern = intern del intern try: sys.maxsize except AttributeError: # Pre-2.6 Python has no sys.maxsize attribute # Wrapping sys in () is silly, but protects it from 2to3 renames fixer sys.maxsize = (sys).maxint if os.environ.get('SCONS_HORRIBLE_REGRESSION_TEST_HACK') is not None: # We can't apply the 'callable' fixer until the floor is 2.6, but the # '-3' option to Python 2.6 and 2.7 generates almost ten thousand # warnings. This hack allows us to run regression tests with the '-3' # option by replacing the callable() built-in function with a hack # that performs the same function but doesn't generate the warning. # Note that this hack is ONLY intended to be used for regression # testing, and should NEVER be used for real runs. from types import ClassType def callable(obj): if hasattr(obj, '__call__'): return True if isinstance(obj, (ClassType, type)): return True return False import builtins builtins.callable = callable del callable # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
mit
5,477,440,070,240,203,000
33.510549
101
0.712312
false
ruschelp/cortex-vfx
test/IECore/Shader.py
12
3204
########################################################################## # # Copyright (c) 2007-2011, Image Engine Design 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 Image Engine Design nor the names of any # other contributors to this software 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 unittest from IECore import * class TestShader( unittest.TestCase ) : def test( self ) : s = Shader() self.assertEqual( s.name, "defaultsurface" ) self.assertEqual( s.type, "surface" ) self.assertEqual( len( s.parameters ), 0 ) self.assertEqual( s.parameters.typeName(), "CompoundData" ) s = Shader( "marble", "surface" ) self.assertEqual( s.name, "marble" ) self.assertEqual( s.type, "surface" ) ss = s.copy() self.assertEqual( ss.name, s.name ) self.assertEqual( ss.type, s.type ) def testConstructWithParameters( self ) : s = Shader( "test", "surface", CompoundData( { "a" : StringData( "a" ) } ) ) self.assertEqual( s.name, "test" ) self.assertEqual( s.type, "surface" ) self.assertEqual( len( s.parameters ), 1 ) self.assertEqual( s.parameters.typeName(), CompoundData.staticTypeName() ) self.assertEqual( s.parameters["a"], StringData( "a" ) ) def testCopy( self ) : s = Shader( "test", "surface", CompoundData( { "a" : StringData( "a" ) } ) ) ss = s.copy() self.assertEqual( s, ss ) def testHash( self ) : s = Shader() h = s.hash() s.name = "somethingElse" self.assertNotEqual( s.hash(), h ) h = s.hash() s.type = "somethingElse" self.assertNotEqual( s.hash(), h ) h = s.hash() s.parameters["a"] = StringData( "a" ) self.assertNotEqual( s.hash(), h ) if __name__ == "__main__": unittest.main()
bsd-3-clause
8,937,002,234,067,745,000
34.208791
78
0.660737
false
gangadharkadam/smrterp
erpnext/stock/doctype/warehouse/warehouse.py
3
5175
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import cint, validate_email_add from frappe import throw, msgprint, _ from frappe.model.document import Document class Warehouse(Document): def autoname(self): suffix = " - " + frappe.db.get_value("Company", self.company, "abbr") if not self.warehouse_name.endswith(suffix): self.name = self.warehouse_name + suffix def validate(self): if self.email_id and not validate_email_add(self.email_id): throw(_("Please enter valid Email Id")) self.update_parent_account() def update_parent_account(self): if not getattr(self, "__islocal", None) \ and (self.create_account_under != frappe.db.get_value("Warehouse", self.name, "create_account_under")): self.validate_parent_account() warehouse_account = frappe.db.get_value("Account", {"account_type": "Warehouse", "company": self.company, "master_name": self.name}, ["name", "parent_account"]) if warehouse_account and warehouse_account[1] != self.create_account_under: acc_doc = frappe.get_doc("Account", warehouse_account[0]) acc_doc.parent_account = self.create_account_under acc_doc.save() def on_update(self): self.create_account_head() def create_account_head(self): if cint(frappe.defaults.get_global_default("auto_accounting_for_stock")): if not frappe.db.get_value("Account", {"account_type": "Warehouse", "master_name": self.name}): if self.get("__islocal") or not frappe.db.get_value( "Stock Ledger Entry", {"warehouse": self.name}): self.validate_parent_account() ac_doc = frappe.get_doc({ "doctype": "Account", 'account_name': self.warehouse_name, 'parent_account': self.create_account_under, 'group_or_ledger':'Ledger', 'company':self.company, "account_type": "Warehouse", "master_name": self.name, "freeze_account": "No" }) ac_doc.ignore_permissions = True ac_doc.insert() msgprint(_("Account head {0} created").format(ac_doc.name)) def validate_parent_account(self): if not self.company: frappe.throw(_("Warehouse {0}: Company is mandatory").format(self.name)) if not self.create_account_under: parent_account = frappe.db.get_value("Account", {"account_name": "Stock Assets", "company": self.company}) if parent_account: self.create_account_under = parent_account else: frappe.throw(_("Please enter parent account group for warehouse account")) elif frappe.db.get_value("Account", self.create_account_under, "company") != self.company: frappe.throw(_("Warehouse {0}: Parent account {1} does not bolong to the company {2}") .format(self.name, self.create_account_under, self.company)) def on_trash(self): # delete bin bins = frappe.db.sql("select * from `tabBin` where warehouse = %s", self.name, as_dict=1) for d in bins: if d['actual_qty'] or d['reserved_qty'] or d['ordered_qty'] or \ d['indented_qty'] or d['projected_qty'] or d['planned_qty']: throw(_("Warehouse {0} can not be deleted as quantity exists for Item {1}").format(self.name, d['item_code'])) else: frappe.db.sql("delete from `tabBin` where name = %s", d['name']) warehouse_account = frappe.db.get_value("Account", {"account_type": "Warehouse", "master_name": self.name}) if warehouse_account: frappe.delete_doc("Account", warehouse_account) if frappe.db.sql("""select name from `tabStock Ledger Entry` where warehouse = %s""", self.name): throw(_("Warehouse can not be deleted as stock ledger entry exists for this warehouse.")) def before_rename(self, olddn, newdn, merge=False): # Add company abbr if not provided from erpnext.setup.doctype.company.company import get_name_with_abbr new_warehouse = get_name_with_abbr(newdn, self.company) if merge: if not frappe.db.exists("Warehouse", new_warehouse): frappe.throw(_("Warehouse {0} does not exist").format(new_warehouse)) if self.company != frappe.db.get_value("Warehouse", new_warehouse, "company"): frappe.throw(_("Both Warehouse must belong to same Company")) frappe.db.sql("delete from `tabBin` where warehouse=%s", olddn) from erpnext.accounts.utils import rename_account_for rename_account_for("Warehouse", olddn, newdn, merge, self.company) return new_warehouse def after_rename(self, olddn, newdn, merge=False): if merge: self.recalculate_bin_qty(newdn) def recalculate_bin_qty(self, newdn): from erpnext.utilities.repost_stock import repost_stock frappe.db.auto_commit_on_many_writes = 1 frappe.db.set_default("allow_negative_stock", 1) for item in frappe.db.sql("""select distinct item_code from ( select name as item_code from `tabItem` where ifnull(is_stock_item, 'Yes')='Yes' union select distinct item_code from tabBin) a"""): repost_stock(item[0], newdn) frappe.db.set_default("allow_negative_stock", frappe.db.get_value("Stock Settings", None, "allow_negative_stock")) frappe.db.auto_commit_on_many_writes = 0
agpl-3.0
6,077,781,720,569,020,000
36.773723
114
0.687343
false
ajose01/rethinkdb
scripts/VirtuaBuild/builder.py
46
6345
#!/usr/bin/env python # Copyright 2010-2012 RethinkDB, all rights reserved. from vcoptparse import * import vm_build import sys from threading import Thread, Semaphore class Builder(Thread): def __init__(self, name, branch, target, semaphore): Thread.__init__(self) self.name = name self.branch = branch self.target = target self.semaphore = semaphore def run(self): self.success = False try: semaphore.acquire() self.target.run(self.branch, self.name) self.success = True except vm_build.RunError, err: self.exception = err finally: semaphore.release() target_names = ["suse", "redhat5_1", "ubuntu", "debian", "centos5_5", "centos6"] def help(): print >>sys.stderr, "Virtual builder:" print >>sys.stderr, " --help Print this help." print >>sys.stderr, " --target target1 [target2, target3]" print >>sys.stderr, " Build just one target, options are:" print >>sys.stderr, " ", target_names print >>sys.stderr, " defaults to all of them." print >>sys.stderr, " --branch branch_name" print >>sys.stderr, " Build from a branch mutually exclusive with --tag." print >>sys.stderr, " --tag tag-name" print >>sys.stderr, " Build from a tag mutually exclusive with --branch." print >>sys.stderr, " --threads number" print >>sys.stderr, " The number of parallel threads to run." print >>sys.stderr, " --debug" print >>sys.stderr, " Whether to build the packages with debugging enabled." print >>sys.stderr, " --interact" print >>sys.stderr, " This starts a target so that you can interact with it." print >>sys.stderr, " Requires a target." print >>sys.stderr, " --clean-up" print >>sys.stderr, " Shutdown all running vms" print >>sys.stderr, " --username" print >>sys.stderr, " Starts the Virtual Machine using VirtualBox from the specified username." print >>sys.stderr, " --hostname" print >>sys.stderr, " Starts the Virtual Machine using VirtualBox from the specified host machine." o = OptParser() o["help"] = BoolFlag("--help") o["target"] = StringFlag("--target", None) o["branch"] = StringFlag("--branch", None) o["tag"] = StringFlag("--tag", None) o["threads"] = IntFlag("--threads", 3) o["clean-up"] = BoolFlag("--clean-up") o["interact"] = BoolFlag("--interact") o["debug"] = BoolFlag("--debug"); o["username"] = StringFlag("--username", "rethinkdb") # For now, these default values should always be the ones you should use o["hostname"] = StringFlag("--hostname", "deadshot") # because the UUID values below are hard-coded to correspond with rethinkdb@deadshot try: opts = o.parse(sys.argv) except OptError: print >>sys.stderr, "Argument parsing error" help() exit(-1) if opts["help"]: help() sys.exit(0) if opts["branch"] and opts["tag"]: print >>sys.stderr, "Error cannot use --tag and --branch together." help() sys.exit(1) if opts["branch"]: rspec = vm_build.Branch(opts["branch"]) elif opts["tag"]: rspec = vm_build.Tag(opts["tag"]) else: rspec = vm_build.Branch("master") # Prepare the build flags flags = "" # this will be given to the makefile if opts["debug"]: flags += " DEBUG=1 UNIT_TESTS=0" else: flags += " DEBUG=0" suse = vm_build.target('765127b8-2007-43ff-8668-fe4c60176a2b', '192.168.0.173', 'rethinkdb', 'make LEGACY_LINUX=1 LEGACY_GCC=1 NO_EVENTFD=1 rpm-suse10 ' + flags, 'rpm', vm_build.rpm_install, vm_build.rpm_uninstall, vm_build.rpm_get_binary, opts["username"], opts["hostname"]) redhat5_1 = vm_build.target('32340f79-cea9-42ca-94d5-2da13d408d02', '192.168.0.159', 'rethinkdb', 'make rpm LEGACY_GCC=1 LEGACY_LINUX=1 NO_EVENTFD=1' + flags, 'rpm', vm_build.rpm_install, vm_build.rpm_uninstall, vm_build.rpm_get_binary, opts["username"], opts["hostname"]) ubuntu = vm_build.target('1f4521a0-6e74-4d20-b4b9-9ffd8e231423', '192.168.0.172', 'rethinkdb', 'make deb' + flags, 'deb', vm_build.deb_install, vm_build.deb_uninstall, vm_build.deb_get_binary, opts["username"], opts["hostname"]) debian = vm_build.target('cc76e2a5-92c0-4208-be08-5c02429c2c50', '192.168.0.176', 'root', 'make deb NO_EVENTFD=1 LEGACY_LINUX=1 ' + flags, 'deb', vm_build.deb_install, vm_build.deb_uninstall, vm_build.deb_get_binary, opts["username"], opts["hostname"]) centos5_5 = vm_build.target('25710682-666f-4449-bd28-68b25abd8bea', '192.168.0.153', 'root', 'make rpm LEGACY_GCC=1 LEGACY_LINUX=1 ' + flags, 'rpm', vm_build.rpm_install, vm_build.rpm_uninstall, vm_build.rpm_get_binary, opts["username"], opts["hostname"]) centos6 = vm_build.target('d9058650-a45a-44a5-953f-c2402253a614', '192.168.0.178', 'rethinkdb', 'make rpm LEGACY_GCC=1 LEGACY_LINUX=1 ' + flags, 'rpm', vm_build.rpm_install, vm_build.rpm_uninstall, vm_build.rpm_get_binary, opts["username"], opts["hostname"]) targets = {"suse": suse, "redhat5_1": redhat5_1, "ubuntu": ubuntu, "debian": debian, "centos5_5": centos5_5, "centos6": centos6} if (opts["target"]): targets = {opts["target"]: targets[opts["target"]]} if opts["clean-up"]: map(lambda x: x[1].clean_up(), targets.iteritems()) exit(0) if opts["interact"]: if not opts["target"]: print >>sys.stderr, "Error must specify a --target for --interact mode." exit(1) for name, target in targets.iteritems(): target.interact(name) else: success = {} exception = {} semaphore = Semaphore(opts["threads"]) builders = map(lambda x: Builder(x[0], rspec, x[1], semaphore), targets.iteritems()) map(lambda x: x.start(), builders) map(lambda x: x.join(), builders) for b in builders: success[b.name] = b.success if not b.success: exception[b.name] = b.exception print "Build summary:" from termcolor import colored for name, val in success.iteritems(): print name, "." * (20 - len(name)), colored("[Pass]", "green") if val else colored("[Fail]", "red") if (not val): print "Failed on: ", exception[name] raise exception[name] print "Done."
agpl-3.0
939,719,559,956,513,200
44.647482
275
0.626162
false
c1728p9/pyOCD
pyOCD/target/target_stm32f103rc.py
4
1457
""" mbed CMSIS-DAP debugger Copyright (c) 2006-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from cortex_m import CortexM, DHCSR, DBGKEY, C_DEBUGEN, C_MASKINTS, C_STEP, DEMCR, VC_CORERESET, NVIC_AIRCR, NVIC_AIRCR_VECTKEY, NVIC_AIRCR_SYSRESETREQ from .memory_map import (FlashRegion, RamRegion, MemoryMap) from pyOCD.target.target import TARGET_RUNNING, TARGET_HALTED import logging DBGMCU_CR = 0xE0042004 #0111 1110 0011 1111 1111 1111 0000 0000 DBGMCU_VAL = 0x7E3FFF00 class STM32F103RC(CortexM): memoryMap = MemoryMap( FlashRegion( start=0x08000000, length=0x80000, blocksize=0x800, isBootMemory=True), RamRegion( start=0x20000000, length=0x10000) ) def __init__(self, transport): super(STM32F103RC, self).__init__(transport, self.memoryMap) def init(self): logging.debug('stm32f103rc init') CortexM.init(self) self.writeMemory(DBGMCU_CR, DBGMCU_VAL);
apache-2.0
-6,004,540,841,488,146,000
32.883721
151
0.728895
false
technologiescollege/s2a_fr
s2a/Python/Lib/test/lock_tests.py
110
15126
""" Various tests for synchronization primitives. """ import sys import time from thread import start_new_thread, get_ident import threading import unittest from test import test_support as support def _wait(): # A crude wait/yield function not relying on synchronization primitives. time.sleep(0.01) class Bunch(object): """ A bunch of threads. """ def __init__(self, f, n, wait_before_exit=False): """ Construct a bunch of `n` threads running the same function `f`. If `wait_before_exit` is True, the threads won't terminate until do_finish() is called. """ self.f = f self.n = n self.started = [] self.finished = [] self._can_exit = not wait_before_exit def task(): tid = get_ident() self.started.append(tid) try: f() finally: self.finished.append(tid) while not self._can_exit: _wait() for i in range(n): start_new_thread(task, ()) def wait_for_started(self): while len(self.started) < self.n: _wait() def wait_for_finished(self): while len(self.finished) < self.n: _wait() def do_finish(self): self._can_exit = True class BaseTestCase(unittest.TestCase): def setUp(self): self._threads = support.threading_setup() def tearDown(self): support.threading_cleanup(*self._threads) support.reap_children() class BaseLockTests(BaseTestCase): """ Tests for both recursive and non-recursive locks. """ def test_constructor(self): lock = self.locktype() del lock def test_acquire_destroy(self): lock = self.locktype() lock.acquire() del lock def test_acquire_release(self): lock = self.locktype() lock.acquire() lock.release() del lock def test_try_acquire(self): lock = self.locktype() self.assertTrue(lock.acquire(False)) lock.release() def test_try_acquire_contended(self): lock = self.locktype() lock.acquire() result = [] def f(): result.append(lock.acquire(False)) Bunch(f, 1).wait_for_finished() self.assertFalse(result[0]) lock.release() def test_acquire_contended(self): lock = self.locktype() lock.acquire() N = 5 def f(): lock.acquire() lock.release() b = Bunch(f, N) b.wait_for_started() _wait() self.assertEqual(len(b.finished), 0) lock.release() b.wait_for_finished() self.assertEqual(len(b.finished), N) def test_with(self): lock = self.locktype() def f(): lock.acquire() lock.release() def _with(err=None): with lock: if err is not None: raise err _with() # Check the lock is unacquired Bunch(f, 1).wait_for_finished() self.assertRaises(TypeError, _with, TypeError) # Check the lock is unacquired Bunch(f, 1).wait_for_finished() def test_thread_leak(self): # The lock shouldn't leak a Thread instance when used from a foreign # (non-threading) thread. lock = self.locktype() def f(): lock.acquire() lock.release() n = len(threading.enumerate()) # We run many threads in the hope that existing threads ids won't # be recycled. Bunch(f, 15).wait_for_finished() self.assertEqual(n, len(threading.enumerate())) class LockTests(BaseLockTests): """ Tests for non-recursive, weak locks (which can be acquired and released from different threads). """ def test_reacquire(self): # Lock needs to be released before re-acquiring. lock = self.locktype() phase = [] def f(): lock.acquire() phase.append(None) lock.acquire() phase.append(None) start_new_thread(f, ()) while len(phase) == 0: _wait() _wait() self.assertEqual(len(phase), 1) lock.release() while len(phase) == 1: _wait() self.assertEqual(len(phase), 2) def test_different_thread(self): # Lock can be released from a different thread. lock = self.locktype() lock.acquire() def f(): lock.release() b = Bunch(f, 1) b.wait_for_finished() lock.acquire() lock.release() class RLockTests(BaseLockTests): """ Tests for recursive locks. """ def test_reacquire(self): lock = self.locktype() lock.acquire() lock.acquire() lock.release() lock.acquire() lock.release() lock.release() def test_release_unacquired(self): # Cannot release an unacquired lock lock = self.locktype() self.assertRaises(RuntimeError, lock.release) lock.acquire() lock.acquire() lock.release() lock.acquire() lock.release() lock.release() self.assertRaises(RuntimeError, lock.release) def test_different_thread(self): # Cannot release from a different thread lock = self.locktype() def f(): lock.acquire() b = Bunch(f, 1, True) try: self.assertRaises(RuntimeError, lock.release) finally: b.do_finish() def test__is_owned(self): lock = self.locktype() self.assertFalse(lock._is_owned()) lock.acquire() self.assertTrue(lock._is_owned()) lock.acquire() self.assertTrue(lock._is_owned()) result = [] def f(): result.append(lock._is_owned()) Bunch(f, 1).wait_for_finished() self.assertFalse(result[0]) lock.release() self.assertTrue(lock._is_owned()) lock.release() self.assertFalse(lock._is_owned()) class EventTests(BaseTestCase): """ Tests for Event objects. """ def test_is_set(self): evt = self.eventtype() self.assertFalse(evt.is_set()) evt.set() self.assertTrue(evt.is_set()) evt.set() self.assertTrue(evt.is_set()) evt.clear() self.assertFalse(evt.is_set()) evt.clear() self.assertFalse(evt.is_set()) def _check_notify(self, evt): # All threads get notified N = 5 results1 = [] results2 = [] def f(): results1.append(evt.wait()) results2.append(evt.wait()) b = Bunch(f, N) b.wait_for_started() _wait() self.assertEqual(len(results1), 0) evt.set() b.wait_for_finished() self.assertEqual(results1, [True] * N) self.assertEqual(results2, [True] * N) def test_notify(self): evt = self.eventtype() self._check_notify(evt) # Another time, after an explicit clear() evt.set() evt.clear() self._check_notify(evt) def test_timeout(self): evt = self.eventtype() results1 = [] results2 = [] N = 5 def f(): results1.append(evt.wait(0.0)) t1 = time.time() r = evt.wait(0.2) t2 = time.time() results2.append((r, t2 - t1)) Bunch(f, N).wait_for_finished() self.assertEqual(results1, [False] * N) for r, dt in results2: self.assertFalse(r) self.assertTrue(dt >= 0.2, dt) # The event is set results1 = [] results2 = [] evt.set() Bunch(f, N).wait_for_finished() self.assertEqual(results1, [True] * N) for r, dt in results2: self.assertTrue(r) class ConditionTests(BaseTestCase): """ Tests for condition variables. """ def test_acquire(self): cond = self.condtype() # Be default we have an RLock: the condition can be acquired multiple # times. cond.acquire() cond.acquire() cond.release() cond.release() lock = threading.Lock() cond = self.condtype(lock) cond.acquire() self.assertFalse(lock.acquire(False)) cond.release() self.assertTrue(lock.acquire(False)) self.assertFalse(cond.acquire(False)) lock.release() with cond: self.assertFalse(lock.acquire(False)) def test_unacquired_wait(self): cond = self.condtype() self.assertRaises(RuntimeError, cond.wait) def test_unacquired_notify(self): cond = self.condtype() self.assertRaises(RuntimeError, cond.notify) def _check_notify(self, cond): N = 5 results1 = [] results2 = [] phase_num = 0 def f(): cond.acquire() cond.wait() cond.release() results1.append(phase_num) cond.acquire() cond.wait() cond.release() results2.append(phase_num) b = Bunch(f, N) b.wait_for_started() _wait() self.assertEqual(results1, []) # Notify 3 threads at first cond.acquire() cond.notify(3) _wait() phase_num = 1 cond.release() while len(results1) < 3: _wait() self.assertEqual(results1, [1] * 3) self.assertEqual(results2, []) # Notify 5 threads: they might be in their first or second wait cond.acquire() cond.notify(5) _wait() phase_num = 2 cond.release() while len(results1) + len(results2) < 8: _wait() self.assertEqual(results1, [1] * 3 + [2] * 2) self.assertEqual(results2, [2] * 3) # Notify all threads: they are all in their second wait cond.acquire() cond.notify_all() _wait() phase_num = 3 cond.release() while len(results2) < 5: _wait() self.assertEqual(results1, [1] * 3 + [2] * 2) self.assertEqual(results2, [2] * 3 + [3] * 2) b.wait_for_finished() def test_notify(self): cond = self.condtype() self._check_notify(cond) # A second time, to check internal state is still ok. self._check_notify(cond) def test_timeout(self): cond = self.condtype() results = [] N = 5 def f(): cond.acquire() t1 = time.time() cond.wait(0.2) t2 = time.time() cond.release() results.append(t2 - t1) Bunch(f, N).wait_for_finished() self.assertEqual(len(results), 5) for dt in results: self.assertTrue(dt >= 0.2, dt) class BaseSemaphoreTests(BaseTestCase): """ Common tests for {bounded, unbounded} semaphore objects. """ def test_constructor(self): self.assertRaises(ValueError, self.semtype, value = -1) self.assertRaises(ValueError, self.semtype, value = -sys.maxint) def test_acquire(self): sem = self.semtype(1) sem.acquire() sem.release() sem = self.semtype(2) sem.acquire() sem.acquire() sem.release() sem.release() def test_acquire_destroy(self): sem = self.semtype() sem.acquire() del sem def test_acquire_contended(self): sem = self.semtype(7) sem.acquire() N = 10 results1 = [] results2 = [] phase_num = 0 def f(): sem.acquire() results1.append(phase_num) sem.acquire() results2.append(phase_num) b = Bunch(f, 10) b.wait_for_started() while len(results1) + len(results2) < 6: _wait() self.assertEqual(results1 + results2, [0] * 6) phase_num = 1 for i in range(7): sem.release() while len(results1) + len(results2) < 13: _wait() self.assertEqual(sorted(results1 + results2), [0] * 6 + [1] * 7) phase_num = 2 for i in range(6): sem.release() while len(results1) + len(results2) < 19: _wait() self.assertEqual(sorted(results1 + results2), [0] * 6 + [1] * 7 + [2] * 6) # The semaphore is still locked self.assertFalse(sem.acquire(False)) # Final release, to let the last thread finish sem.release() b.wait_for_finished() def test_try_acquire(self): sem = self.semtype(2) self.assertTrue(sem.acquire(False)) self.assertTrue(sem.acquire(False)) self.assertFalse(sem.acquire(False)) sem.release() self.assertTrue(sem.acquire(False)) def test_try_acquire_contended(self): sem = self.semtype(4) sem.acquire() results = [] def f(): results.append(sem.acquire(False)) results.append(sem.acquire(False)) Bunch(f, 5).wait_for_finished() # There can be a thread switch between acquiring the semaphore and # appending the result, therefore results will not necessarily be # ordered. self.assertEqual(sorted(results), [False] * 7 + [True] * 3 ) def test_default_value(self): # The default initial value is 1. sem = self.semtype() sem.acquire() def f(): sem.acquire() sem.release() b = Bunch(f, 1) b.wait_for_started() _wait() self.assertFalse(b.finished) sem.release() b.wait_for_finished() def test_with(self): sem = self.semtype(2) def _with(err=None): with sem: self.assertTrue(sem.acquire(False)) sem.release() with sem: self.assertFalse(sem.acquire(False)) if err: raise err _with() self.assertTrue(sem.acquire(False)) sem.release() self.assertRaises(TypeError, _with, TypeError) self.assertTrue(sem.acquire(False)) sem.release() class SemaphoreTests(BaseSemaphoreTests): """ Tests for unbounded semaphores. """ def test_release_unacquired(self): # Unbounded releases are allowed and increment the semaphore's value sem = self.semtype(1) sem.release() sem.acquire() sem.acquire() sem.release() class BoundedSemaphoreTests(BaseSemaphoreTests): """ Tests for bounded semaphores. """ def test_release_unacquired(self): # Cannot go past the initial value sem = self.semtype() self.assertRaises(ValueError, sem.release) sem.acquire() sem.release() self.assertRaises(ValueError, sem.release)
gpl-3.0
1,044,183,361,976,538,100
26.703297
82
0.536229
false
krishna-pandey-git/django
tests/template_tests/filter_tests/test_timesince.py
207
5422
from __future__ import unicode_literals from datetime import datetime, timedelta from django.template.defaultfilters import timesince_filter from django.test import SimpleTestCase from django.test.utils import requires_tz_support from ..utils import setup from .timezone_utils import TimezoneTestCase class TimesinceTests(TimezoneTestCase): """ #20246 - \xa0 in output avoids line-breaks between value and unit """ # Default compare with datetime.now() @setup({'timesince01': '{{ a|timesince }}'}) def test_timesince01(self): output = self.engine.render_to_string('timesince01', {'a': datetime.now() + timedelta(minutes=-1, seconds=-10)}) self.assertEqual(output, '1\xa0minute') @setup({'timesince02': '{{ a|timesince }}'}) def test_timesince02(self): output = self.engine.render_to_string('timesince02', {'a': datetime.now() - timedelta(days=1, minutes=1)}) self.assertEqual(output, '1\xa0day') @setup({'timesince03': '{{ a|timesince }}'}) def test_timesince03(self): output = self.engine.render_to_string('timesince03', {'a': datetime.now() - timedelta(hours=1, minutes=25, seconds=10)}) self.assertEqual(output, '1\xa0hour, 25\xa0minutes') # Compare to a given parameter @setup({'timesince04': '{{ a|timesince:b }}'}) def test_timesince04(self): output = self.engine.render_to_string( 'timesince04', {'a': self.now - timedelta(days=2), 'b': self.now - timedelta(days=1)}, ) self.assertEqual(output, '1\xa0day') @setup({'timesince05': '{{ a|timesince:b }}'}) def test_timesince05(self): output = self.engine.render_to_string( 'timesince05', {'a': self.now - timedelta(days=2, minutes=1), 'b': self.now - timedelta(days=2)}, ) self.assertEqual(output, '1\xa0minute') # Check that timezone is respected @setup({'timesince06': '{{ a|timesince:b }}'}) def test_timesince06(self): output = self.engine.render_to_string('timesince06', {'a': self.now_tz - timedelta(hours=8), 'b': self.now_tz}) self.assertEqual(output, '8\xa0hours') # Tests for #7443 @setup({'timesince07': '{{ earlier|timesince }}'}) def test_timesince07(self): output = self.engine.render_to_string('timesince07', {'earlier': self.now - timedelta(days=7)}) self.assertEqual(output, '1\xa0week') @setup({'timesince08': '{{ earlier|timesince:now }}'}) def test_timesince08(self): output = self.engine.render_to_string('timesince08', {'now': self.now, 'earlier': self.now - timedelta(days=7)}) self.assertEqual(output, '1\xa0week') @setup({'timesince09': '{{ later|timesince }}'}) def test_timesince09(self): output = self.engine.render_to_string('timesince09', {'later': self.now + timedelta(days=7)}) self.assertEqual(output, '0\xa0minutes') @setup({'timesince10': '{{ later|timesince:now }}'}) def test_timesince10(self): output = self.engine.render_to_string('timesince10', {'now': self.now, 'later': self.now + timedelta(days=7)}) self.assertEqual(output, '0\xa0minutes') # Ensures that differing timezones are calculated correctly. @setup({'timesince11': '{{ a|timesince }}'}) def test_timesince11(self): output = self.engine.render_to_string('timesince11', {'a': self.now}) self.assertEqual(output, '0\xa0minutes') @requires_tz_support @setup({'timesince12': '{{ a|timesince }}'}) def test_timesince12(self): output = self.engine.render_to_string('timesince12', {'a': self.now_tz}) self.assertEqual(output, '0\xa0minutes') @requires_tz_support @setup({'timesince13': '{{ a|timesince }}'}) def test_timesince13(self): output = self.engine.render_to_string('timesince13', {'a': self.now_tz_i}) self.assertEqual(output, '0\xa0minutes') @setup({'timesince14': '{{ a|timesince:b }}'}) def test_timesince14(self): output = self.engine.render_to_string('timesince14', {'a': self.now_tz, 'b': self.now_tz_i}) self.assertEqual(output, '0\xa0minutes') @setup({'timesince15': '{{ a|timesince:b }}'}) def test_timesince15(self): output = self.engine.render_to_string('timesince15', {'a': self.now, 'b': self.now_tz_i}) self.assertEqual(output, '') @setup({'timesince16': '{{ a|timesince:b }}'}) def test_timesince16(self): output = self.engine.render_to_string('timesince16', {'a': self.now_tz_i, 'b': self.now}) self.assertEqual(output, '') # Tests for #9065 (two date objects). @setup({'timesince17': '{{ a|timesince:b }}'}) def test_timesince17(self): output = self.engine.render_to_string('timesince17', {'a': self.today, 'b': self.today}) self.assertEqual(output, '0\xa0minutes') @setup({'timesince18': '{{ a|timesince:b }}'}) def test_timesince18(self): output = self.engine.render_to_string('timesince18', {'a': self.today, 'b': self.today + timedelta(hours=24)}) self.assertEqual(output, '1\xa0day') class FunctionTests(SimpleTestCase): def test_since_now(self): self.assertEqual(timesince_filter(datetime.now() - timedelta(1)), '1\xa0day') def test_explicit_date(self): self.assertEqual(timesince_filter(datetime(2005, 12, 29), datetime(2005, 12, 30)), '1\xa0day')
bsd-3-clause
-8,209,475,703,017,608,000
41.031008
128
0.634821
false
mne-tools/mne-tools.github.io
0.20/_downloads/76822bb92a8465181ec2a7ee96ca8cf4/plot_decoding_csp_timefreq.py
1
6457
""" ============================================================================ Decoding in time-frequency space data using the Common Spatial Pattern (CSP) ============================================================================ The time-frequency decomposition is estimated by iterating over raw data that has been band-passed at different frequencies. This is used to compute a covariance matrix over each epoch or a rolling time-window and extract the CSP filtered signals. A linear discriminant classifier is then applied to these signals. """ # Authors: Laura Gwilliams <laura.gwilliams@nyu.edu> # Jean-Remi King <jeanremi.king@gmail.com> # Alex Barachant <alexandre.barachant@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from mne import Epochs, create_info, events_from_annotations from mne.io import concatenate_raws, read_raw_edf from mne.datasets import eegbci from mne.decoding import CSP from mne.time_frequency import AverageTFR from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.model_selection import StratifiedKFold, cross_val_score from sklearn.pipeline import make_pipeline from sklearn.preprocessing import LabelEncoder ############################################################################### # Set parameters and read data event_id = dict(hands=2, feet=3) # motor imagery: hands vs feet subject = 1 runs = [6, 10, 14] raw_fnames = eegbci.load_data(subject, runs) raw = concatenate_raws([read_raw_edf(f, preload=True) for f in raw_fnames]) # Extract information from the raw file sfreq = raw.info['sfreq'] events, _ = events_from_annotations(raw, event_id=dict(T1=2, T2=3)) raw.pick_types(meg=False, eeg=True, stim=False, eog=False, exclude='bads') # Assemble the classifier using scikit-learn pipeline clf = make_pipeline(CSP(n_components=4, reg=None, log=True, norm_trace=False), LinearDiscriminantAnalysis()) n_splits = 5 # how many folds to use for cross-validation cv = StratifiedKFold(n_splits=n_splits, shuffle=True) # Classification & Time-frequency parameters tmin, tmax = -.200, 2.000 n_cycles = 10. # how many complete cycles: used to define window size min_freq = 5. max_freq = 25. n_freqs = 8 # how many frequency bins to use # Assemble list of frequency range tuples freqs = np.linspace(min_freq, max_freq, n_freqs) # assemble frequencies freq_ranges = list(zip(freqs[:-1], freqs[1:])) # make freqs list of tuples # Infer window spacing from the max freq and number of cycles to avoid gaps window_spacing = (n_cycles / np.max(freqs) / 2.) centered_w_times = np.arange(tmin, tmax, window_spacing)[1:] n_windows = len(centered_w_times) # Instantiate label encoder le = LabelEncoder() ############################################################################### # Loop through frequencies, apply classifier and save scores # init scores freq_scores = np.zeros((n_freqs - 1,)) # Loop through each frequency range of interest for freq, (fmin, fmax) in enumerate(freq_ranges): # Infer window size based on the frequency being used w_size = n_cycles / ((fmax + fmin) / 2.) # in seconds # Apply band-pass filter to isolate the specified frequencies raw_filter = raw.copy().filter(fmin, fmax, n_jobs=1, fir_design='firwin', skip_by_annotation='edge') # Extract epochs from filtered data, padded by window size epochs = Epochs(raw_filter, events, event_id, tmin - w_size, tmax + w_size, proj=False, baseline=None, preload=True) epochs.drop_bad() y = le.fit_transform(epochs.events[:, 2]) X = epochs.get_data() # Save mean scores over folds for each frequency and time window freq_scores[freq] = np.mean(cross_val_score(estimator=clf, X=X, y=y, scoring='roc_auc', cv=cv, n_jobs=1), axis=0) ############################################################################### # Plot frequency results plt.bar(freqs[:-1], freq_scores, width=np.diff(freqs)[0], align='edge', edgecolor='black') plt.xticks(freqs) plt.ylim([0, 1]) plt.axhline(len(epochs['feet']) / len(epochs), color='k', linestyle='--', label='chance level') plt.legend() plt.xlabel('Frequency (Hz)') plt.ylabel('Decoding Scores') plt.title('Frequency Decoding Scores') ############################################################################### # Loop through frequencies and time, apply classifier and save scores # init scores tf_scores = np.zeros((n_freqs - 1, n_windows)) # Loop through each frequency range of interest for freq, (fmin, fmax) in enumerate(freq_ranges): # Infer window size based on the frequency being used w_size = n_cycles / ((fmax + fmin) / 2.) # in seconds # Apply band-pass filter to isolate the specified frequencies raw_filter = raw.copy().filter(fmin, fmax, n_jobs=1, fir_design='firwin', skip_by_annotation='edge') # Extract epochs from filtered data, padded by window size epochs = Epochs(raw_filter, events, event_id, tmin - w_size, tmax + w_size, proj=False, baseline=None, preload=True) epochs.drop_bad() y = le.fit_transform(epochs.events[:, 2]) # Roll covariance, csp and lda over time for t, w_time in enumerate(centered_w_times): # Center the min and max of the window w_tmin = w_time - w_size / 2. w_tmax = w_time + w_size / 2. # Crop data into time-window of interest X = epochs.copy().crop(w_tmin, w_tmax).get_data() # Save mean scores over folds for each frequency and time window tf_scores[freq, t] = np.mean(cross_val_score(estimator=clf, X=X, y=y, scoring='roc_auc', cv=cv, n_jobs=1), axis=0) ############################################################################### # Plot time-frequency results # Set up time frequency object av_tfr = AverageTFR(create_info(['freq'], sfreq), tf_scores[np.newaxis, :], centered_w_times, freqs[1:], 1) chance = np.mean(y) # set chance level to white in the plot av_tfr.plot([0], vmin=chance, title="Time-Frequency Decoding Scores", cmap=plt.cm.Reds)
bsd-3-clause
240,441,842,313,748,830
39.10559
79
0.611275
false
pennersr/django-allauth
allauth/socialaccount/providers/orcid/provider.py
2
1564
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class Scope(object): USERINFO_PROFILE = "/authenticate" class OrcidAccount(ProviderAccount): def get_profile_url(self): return extract_from_dict(self.account.extra_data, ["orcid-identifier", "uri"]) def to_str(self): return self.account.uid class OrcidProvider(OAuth2Provider): id = "orcid" name = "Orcid.org" account_class = OrcidAccount def get_default_scope(self): return [Scope.USERINFO_PROFILE] def extract_uid(self, data): return extract_from_dict(data, ["orcid-identifier", "path"]) def extract_common_fields(self, data): common_fields = dict( email=extract_from_dict(data, ["person", "emails", "email", 0, "email"]), last_name=extract_from_dict( data, ["person", "name", "family-name", "value"] ), first_name=extract_from_dict( data, ["person", "name", "given-names", "value"] ), ) return dict((key, value) for (key, value) in common_fields.items() if value) provider_classes = [OrcidProvider] def extract_from_dict(data, path): """ Navigate `data`, a multidimensional array (list or dictionary), and returns the object at `path`. """ value = data try: for key in path: value = value[key] return value except (KeyError, IndexError, TypeError): return ""
mit
6,449,739,463,738,600,000
27.436364
86
0.618926
false
binarydud/verse
verse/views.py
1
7356
import json import re import yaml import base64 import velruse import datetime from pygithub3 import Github from pyramid.httpexceptions import HTTPFound from pyramid.view import view_config from verse.utils import set_content #from pyramid.i18n import TranslationString as _ from .models import ( DBSession, User, ) flat_url = velruse.utils.flat_url SALT = 'supersecretsalt' def tree(items, root=None): if root: items = filter(lambda x: x['path'].startswith(root), items) trees = filter(lambda x: x['type'] == 'tree', items) blobs = filter(lambda x: x['type'] == 'blob', items) return trees, blobs fm_pattern = re.compile(r'^---\n([\s\S]*?)---\n([\s\S]*)') def fm(content): matches = fm_pattern.match(content) if matches: return matches.group(1), matches.group(2) return None, None _repo_name = 'testbest' def _get_credentials(request): return request.session.get('token'), request.session.get('github_user'), request.session.get('github_repo') def content_to_json(content_obj): content = content_obj.get_content() front_matter, post = fm(content or '') if front_matter: meta = yaml.safe_load(front_matter) else: meta = {} d = { 'content': post, 'front_matter': front_matter, 'raw': content, 'name': content_obj.name, 'path': content_obj.path, 'sha': content_obj.sha, 'url': content_obj.url, } for key, value in meta.items(): d['meta_%s' % key] = value if 'meta_published' not in d: d['meta_published'] = '' return d slug_re = re.compile(r"[^A-Za-z0-9.]+") def slugify(value): return slug_re.sub("-", value).lower() def normalize_front_matter(raw_front_matter): pass def dashboard(request): return {} class PostsView(object): def __init__(self, request): self.request = request @view_config(route_name='post.list', renderer='json', accept='application/json',) @view_config(route_name='post.list', renderer='posts.html', accept='text/html') def list(self): access_token, user, repo = _get_credentials(self.request) github = Github(token=access_token, user=user, repo=repo) items = github.repos.contents.get('_posts/') full_items = [] for item in items: if item.name != 'README': full_items.append(github.repos.contents.get(item.path)) return {'items': map(content_to_json, full_items)} @view_config(route_name='post.item', renderer='json', request_method="GET", accept='application/json',) def item(self): access_token, user, repo = _get_credentials(self.request) github = Github(token=access_token, user=user, repo=repo) name = self.request.matchdict['id'] f = github.repos.contents.get('_posts/%s' % name) post = content_to_json(f) return post @view_config(route_name='post.new', renderer='post_new.html') @view_config(route_name='post.new', renderer='json', accept='application/json') def new(self): access_token, user, repo = _get_credentials(self.request) github = Github(token=access_token, user=user, repo=repo) date = datetime.datetime.now().date() post = self.request.json_body front_matter = { 'layout': 'post', 'published': False, 'comments': 'true', 'date': date.strftime('%Y-%m-%d'), } front_matter['title'] = post['meta_title'] front_matter_raw = yaml.safe_dump(front_matter, default_flow_style=False) name = slugify(post['meta_title']) raw = '---\n%s---\n%s' % (front_matter_raw, post['content']) date_string = date.strftime('%Y-%m-%d-{}.md') name = date_string.format(name) path = '_posts/{}'.format(name) commit_data = { 'path': path, 'message': 'creating new post', 'content': base64.b64encode(raw) } resp = github.repos.contents.create(path, commit_data) sha = resp.content['sha'] d = { 'front_matter': front_matter_raw, 'content': post['content'], 'raw': raw, 'name': date_string.format(name), 'path': path, 'sha': sha, } for key, value in front_matter.items(): d['meta_%s' % key] = value return d @view_config(route_name='post.item', request_method='PUT', renderer='json') def update(self): """ if sha is in the model, then update else create """ access_token, user, repo = _get_credentials(self.request) github = Github(token=access_token, user=user, repo=repo) post = self.request.json_body #saving meta information fm = yaml.safe_load(post['front_matter']) fm['title'] = post['meta_title'] fm['date'] = post['meta_date'] fm['published'] = post['meta_published'] fm_raw = yaml.safe_dump(fm, default_flow_style=False) path = post['path'] raw = '---\n%s---\n%s' % (fm_raw, post['content']) commit_data = { 'path': path, 'message': 'updating post', 'content': base64.b64encode(raw), 'sha': post['sha'] } resp = github.repos.contents.update(path, commit_data) post['sha'] = resp.content['sha'] return post @view_config(route_name='post.item', request_method='DELETE', renderer='json') def delete(self): return {} from cornice.resource import resource, view @resource(collection_path='/pages', path='/pages/{id}') class PageView(object): def __init__(self, request): self.request = request access_token, user, repo = _get_credentials(self.request) self.github = Github(token=access_token, user=user, repo=repo) def _filter_pages(self, x): starts = ('_layouts', '_posts', '_drafts') ends = ('html', 'htm') #type is blob #endswith htm or html return x['type'] == 'blob' and x['path'].endswith(ends) and not x['path'].startswith(starts) def _map_pages(self, x): y = x.copy() y['id'] = base64.b64encode(y['path']) return y def collection_get(self): #access_token, user, repo = _get_credentials(self.request) #github = Github(token=access_token, user=user, repo=repo) tree = self.github.git_data.trees.get(sha='master', recursive=1) items = map(self._map_pages, filter(self._filter_pages, tree.tree)) return {'items': items} def collection_post(self): #this creates a new page content = set_content(self.github, self.request.POST['']) return {} def get(self): id = self.request.matchdict['id'] id = base64.b64decode(id) access_token, user, repo = _get_credentials(self.request) github = Github(token=access_token, user=user, repo=repo) content = github.repos.contents.get(id) return content._attrs def put(self): #updates a page print 'PUT' id = int(self.request.matchdict['id']) return {} def delete(self): #delete a page print 'DELETE' id = int(self.request.matchdict['id']) return {}
apache-2.0
-5,712,206,696,094,507,000
31.548673
111
0.584557
false
d40223223/2015cdbg6team0622
static/Brython3.1.1-20150328-091302/Lib/importlib/basehook.py
608
1396
from javascript import JSObject from browser import window import urllib.request class TempMod: def __init__(self, name): self.name=name #define my custom import hook (just to see if it get called etc). class BaseHook: def __init__(self, fullname=None, path=None): self._fullname=fullname self._path=path # we don't are about this... self._modpath='' self._module='' def find_module(self, name=None, path=None): if name is None: name=self._fullname for _i in ('libs/%s.js' % name, 'Lib/%s.py' % name, 'Lib/%s/__init__.py' % name): _path="%s%s" % (__BRYTHON__.brython_path, _i) try: _fp,_,_headers=urllib.request.urlopen(_path) if _headers['status'] != 200: continue self._module=_fp.read() self._modpath=_path return self except urllib.error.HTTPError as e: print(str(e)) self._modpath='' self._module='' raise ImportError def is_package(self): return '.' in self._fullname def load_module(self, name): if name is None: name=self._fullname window.eval('__BRYTHON__.imported["%s"]={}' % name) return JSObject(__BRYTHON__.run_py)(TempMod(name), self._modpath, self._module)
gpl-3.0
834,423,359,024,821,900
29.347826
70
0.537966
false
fx2003/tensorflow-study
TensorFlow实战/models/syntaxnet/dragnn/python/composite_optimizer.py
12
2604
# Copyright 2017 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. # ============================================================================== """An optimizer that switches between several methods.""" import tensorflow as tf from tensorflow.python.training import optimizer class CompositeOptimizer(optimizer.Optimizer): """Optimizer that switches between several methods. """ def __init__(self, optimizer1, optimizer2, switch, use_locking=False, name='Composite'): """Construct a new Composite optimizer. Args: optimizer1: A tf.python.training.optimizer.Optimizer object. optimizer2: A tf.python.training.optimizer.Optimizer object. switch: A tf.bool Tensor, selecting whether to use the first or the second optimizer. use_locking: Bool. If True apply use locks to prevent concurrent updates to variables. name: Optional name prefix for the operations created when applying gradients. Defaults to "Composite". """ super(CompositeOptimizer, self).__init__(use_locking, name) self._optimizer1 = optimizer1 self._optimizer2 = optimizer2 self._switch = switch def apply_gradients(self, grads_and_vars, global_step=None, name=None): return tf.cond( self._switch, lambda: self._optimizer1.apply_gradients(grads_and_vars, global_step, name), lambda: self._optimizer2.apply_gradients(grads_and_vars, global_step, name) ) def get_slot(self, var, name): slot1 = self._optimizer1.get_slot(var, name) slot2 = self._optimizer2.get_slot(var, name) if slot1 and slot2: raise LookupError('Slot named %s for variable %s populated for both ' 'optimizers' % (name, var.name)) return slot1 or slot2 def get_slot_names(self): return sorted(self._optimizer1.get_slot_names() + self._optimizer2.get_slot_names())
mit
4,514,945,215,384,570,000
36.2
80
0.635177
false
dalegregory/odoo
addons/hr_timesheet_invoice/__openerp__.py
260
2403
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Invoice on Timesheets', 'version': '1.0', 'category': 'Sales Management', 'description': """ Generate your Invoices from Expenses, Timesheet Entries. ======================================================== Module to generate invoices based on costs (human resources, expenses, ...). You can define price lists in analytic account, make some theoretical revenue reports.""", 'author': 'OpenERP SA', 'website': 'https://www.odoo.com/page/employees', 'depends': ['account', 'hr_timesheet', 'report'], 'data': [ 'security/ir.model.access.csv', 'hr_timesheet_invoice_data.xml', 'hr_timesheet_invoice_view.xml', 'hr_timesheet_invoice_wizard.xml', 'hr_timesheet_invoice_report.xml', 'report/report_analytic_view.xml', 'report/hr_timesheet_invoice_report_view.xml', 'wizard/hr_timesheet_analytic_profit_view.xml', 'wizard/hr_timesheet_invoice_create_view.xml', 'wizard/hr_timesheet_invoice_create_final_view.xml', 'views/report_analyticprofit.xml', ], 'demo': ['hr_timesheet_invoice_demo.xml'], 'test': ['test/test_hr_timesheet_invoice.yml', 'test/test_hr_timesheet_invoice_no_prod_tax.yml', 'test/hr_timesheet_invoice_report.yml', ], 'installable': True, 'auto_install': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
-881,569,634,572,412,800
39.728814
78
0.610487
false
stephane-martin/salt-debian-packaging
salt-2016.3.2/tests/unit/templates/jinja_test.py
1
28124
# -*- coding: utf-8 -*- # Import python libs from __future__ import absolute_import import os import copy import tempfile import json import datetime import pprint # Import Salt Testing libs from salttesting.unit import skipIf, TestCase from salttesting.case import ModuleCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs import salt.loader import salt.utils from salt.exceptions import SaltRenderError from salt.ext.six.moves import builtins from salt.utils import get_context from salt.utils.jinja import ( SaltCacheLoader, SerializerExtension, ensure_sequence_filter ) from salt.utils.templates import JINJA, render_jinja_tmpl from salt.utils.odict import OrderedDict from integration import TMP_CONF_DIR # Import 3rd party libs import yaml from jinja2 import Environment, DictLoader, exceptions try: import timelib # pylint: disable=W0611 HAS_TIMELIB = True except ImportError: HAS_TIMELIB = False TEMPLATES_DIR = os.path.dirname(os.path.abspath(__file__)) class MockFileClient(object): ''' Does not download files but records any file request for testing ''' def __init__(self, loader=None): if loader: loader._file_client = self self.requests = [] def get_file(self, template, dest='', makedirs=False, saltenv='base'): self.requests.append({ 'path': template, 'dest': dest, 'makedirs': makedirs, 'saltenv': saltenv }) class TestSaltCacheLoader(TestCase): def __init__(self, *args, **kws): TestCase.__init__(self, *args, **kws) self.opts = { 'cachedir': TEMPLATES_DIR, 'file_roots': { 'test': [os.path.join(TEMPLATES_DIR, 'files', 'test')] }, 'pillar_roots': { 'test': [os.path.join(TEMPLATES_DIR, 'files', 'test')] } } def test_searchpath(self): ''' The searchpath is based on the cachedir option and the saltenv parameter ''' tmp = tempfile.gettempdir() opts = copy.deepcopy(self.opts) opts.update({'cachedir': tmp}) loader = SaltCacheLoader(opts, saltenv='test') assert loader.searchpath == [os.path.join(tmp, 'files', 'test')] def test_mockclient(self): ''' A MockFileClient is used that records all file requests normally sent to the master. ''' loader = SaltCacheLoader(self.opts, 'test') fc = MockFileClient(loader) res = loader.get_source(None, 'hello_simple') assert len(res) == 3 # res[0] on Windows is unicode and use os.linesep so it works cross OS self.assertEqual(str(res[0]), 'world' + os.linesep) tmpl_dir = os.path.join(TEMPLATES_DIR, 'files', 'test', 'hello_simple') self.assertEqual(res[1], tmpl_dir) assert res[2](), 'Template up to date?' assert len(fc.requests) self.assertEqual(fc.requests[0]['path'], 'salt://hello_simple') def get_test_saltenv(self): ''' Setup a simple jinja test environment ''' loader = SaltCacheLoader(self.opts, 'test') fc = MockFileClient(loader) jinja = Environment(loader=loader) return fc, jinja def test_import(self): ''' You can import and use macros from other files ''' fc, jinja = self.get_test_saltenv() result = jinja.get_template('hello_import').render() self.assertEqual(result, 'Hey world !a b !') assert len(fc.requests) == 2 self.assertEqual(fc.requests[0]['path'], 'salt://hello_import') self.assertEqual(fc.requests[1]['path'], 'salt://macro') def test_include(self): ''' You can also include a template that imports and uses macros ''' fc, jinja = self.get_test_saltenv() result = jinja.get_template('hello_include').render() self.assertEqual(result, 'Hey world !a b !') assert len(fc.requests) == 3 self.assertEqual(fc.requests[0]['path'], 'salt://hello_include') self.assertEqual(fc.requests[1]['path'], 'salt://hello_import') self.assertEqual(fc.requests[2]['path'], 'salt://macro') def test_include_context(self): ''' Context variables are passes to the included template by default. ''' _, jinja = self.get_test_saltenv() result = jinja.get_template('hello_include').render(a='Hi', b='Salt') self.assertEqual(result, 'Hey world !Hi Salt !') class TestGetTemplate(TestCase): def __init__(self, *args, **kws): TestCase.__init__(self, *args, **kws) self.local_opts = { 'cachedir': TEMPLATES_DIR, 'file_client': 'local', 'file_ignore_regex': None, 'file_ignore_glob': None, 'file_roots': { 'test': [os.path.join(TEMPLATES_DIR, 'files', 'test')] }, 'pillar_roots': { 'test': [os.path.join(TEMPLATES_DIR, 'files', 'test')] }, 'fileserver_backend': ['roots'], 'hash_type': 'md5', 'extension_modules': os.path.join( os.path.dirname(os.path.abspath(__file__)), 'extmods'), } def test_fallback(self): ''' A Template with a filesystem loader is returned as fallback if the file is not contained in the searchpath ''' fn_ = os.path.join(TEMPLATES_DIR, 'files', 'test', 'hello_simple') with salt.utils.fopen(fn_) as fp_: out = render_jinja_tmpl( fp_.read(), dict(opts=self.local_opts, saltenv='test')) self.assertEqual(out, 'world\n') def test_fallback_noloader(self): ''' A Template with a filesystem loader is returned as fallback if the file is not contained in the searchpath ''' filename = os.path.join(TEMPLATES_DIR, 'files', 'test', 'hello_import') out = render_jinja_tmpl( salt.utils.fopen(filename).read(), dict(opts=self.local_opts, saltenv='test')) self.assertEqual(out, 'Hey world !a b !\n') def test_saltenv(self): ''' If the template is within the searchpath it can import, include and extend other templates. The initial template is expected to be already cached get_template does not request it from the master again. ''' fc = MockFileClient() # monkey patch file client _fc = SaltCacheLoader.file_client SaltCacheLoader.file_client = lambda loader: fc filename = os.path.join(TEMPLATES_DIR, 'files', 'test', 'hello_import') out = render_jinja_tmpl( salt.utils.fopen(filename).read(), dict(opts={'cachedir': TEMPLATES_DIR, 'file_client': 'remote', 'file_roots': self.local_opts['file_roots'], 'pillar_roots': self.local_opts['pillar_roots']}, a='Hi', b='Salt', saltenv='test')) self.assertEqual(out, 'Hey world !Hi Salt !\n') self.assertEqual(fc.requests[0]['path'], 'salt://macro') SaltCacheLoader.file_client = _fc def test_macro_additional_log_for_generalexc(self): ''' If we failed in a macro because of e.g. a TypeError, get more output from trace. ''' expected = r'''Jinja error:.*division.* .*/macrogeneral\(2\): --- \{% macro mymacro\(\) -%\} \{\{ 1/0 \}\} <====================== \{%- endmacro %\} ---.*''' filename = os.path.join(TEMPLATES_DIR, 'files', 'test', 'hello_import_generalerror') fc = MockFileClient() _fc = SaltCacheLoader.file_client SaltCacheLoader.file_client = lambda loader: fc self.assertRaisesRegexp( SaltRenderError, expected, render_jinja_tmpl, salt.utils.fopen(filename).read(), dict(opts=self.local_opts, saltenv='test')) SaltCacheLoader.file_client = _fc def test_macro_additional_log_for_undefined(self): ''' If we failed in a macro because of undefined variables, get more output from trace. ''' expected = r'''Jinja variable 'b' is undefined .*/macroundefined\(2\): --- \{% macro mymacro\(\) -%\} \{\{b.greetee\}\} <-- error is here <====================== \{%- endmacro %\} ---''' filename = os.path.join(TEMPLATES_DIR, 'files', 'test', 'hello_import_undefined') fc = MockFileClient() _fc = SaltCacheLoader.file_client SaltCacheLoader.file_client = lambda loader: fc self.assertRaisesRegexp( SaltRenderError, expected, render_jinja_tmpl, salt.utils.fopen(filename).read(), dict(opts=self.local_opts, saltenv='test')) SaltCacheLoader.file_client = _fc def test_macro_additional_log_syntaxerror(self): ''' If we failed in a macro, get more output from trace. ''' expected = r'''Jinja syntax error: expected token .*end.*got '-'.* .*/macroerror\(2\): --- # macro \{% macro mymacro\(greeting, greetee='world'\) -\} <-- error is here <====================== \{\{ greeting ~ ' ' ~ greetee \}\} ! \{%- endmacro %\} ---.*''' filename = os.path.join(TEMPLATES_DIR, 'files', 'test', 'hello_import_error') fc = MockFileClient() _fc = SaltCacheLoader.file_client SaltCacheLoader.file_client = lambda loader: fc self.assertRaisesRegexp( SaltRenderError, expected, render_jinja_tmpl, salt.utils.fopen(filename).read(), dict(opts=self.local_opts, saltenv='test')) SaltCacheLoader.file_client = _fc def test_non_ascii_encoding(self): fc = MockFileClient() # monkey patch file client _fc = SaltCacheLoader.file_client SaltCacheLoader.file_client = lambda loader: fc filename = os.path.join(TEMPLATES_DIR, 'files', 'test', 'hello_import') out = render_jinja_tmpl( salt.utils.fopen(filename).read(), dict(opts={'cachedir': TEMPLATES_DIR, 'file_client': 'remote', 'file_roots': self.local_opts['file_roots'], 'pillar_roots': self.local_opts['pillar_roots']}, a='Hi', b='Sàlt', saltenv='test')) self.assertEqual(out, u'Hey world !Hi Sàlt !\n') self.assertEqual(fc.requests[0]['path'], 'salt://macro') SaltCacheLoader.file_client = _fc _fc = SaltCacheLoader.file_client SaltCacheLoader.file_client = lambda loader: fc filename = os.path.join(TEMPLATES_DIR, 'files', 'test', 'non_ascii') out = render_jinja_tmpl( salt.utils.fopen(filename).read(), dict(opts={'cachedir': TEMPLATES_DIR, 'file_client': 'remote', 'file_roots': self.local_opts['file_roots'], 'pillar_roots': self.local_opts['pillar_roots']}, a='Hi', b='Sàlt', saltenv='test')) self.assertEqual(u'Assunção\n', out) self.assertEqual(fc.requests[0]['path'], 'salt://macro') SaltCacheLoader.file_client = _fc @skipIf(HAS_TIMELIB is False, 'The `timelib` library is not installed.') def test_strftime(self): response = render_jinja_tmpl('{{ "2002/12/25"|strftime }}', dict(opts=self.local_opts, saltenv='test')) self.assertEqual(response, '2002-12-25') objects = ( datetime.datetime(2002, 12, 25, 12, 00, 00, 00), '2002/12/25', 1040814000, '1040814000' ) for object in objects: response = render_jinja_tmpl('{{ object|strftime }}', dict(object=object, opts=self.local_opts, saltenv='test')) self.assertEqual(response, '2002-12-25') response = render_jinja_tmpl('{{ object|strftime("%b %d, %Y") }}', dict(object=object, opts=self.local_opts, saltenv='test')) self.assertEqual(response, 'Dec 25, 2002') response = render_jinja_tmpl('{{ object|strftime("%y") }}', dict(object=object, opts=self.local_opts, saltenv='test')) self.assertEqual(response, '02') def test_non_ascii(self): fn = os.path.join(TEMPLATES_DIR, 'files', 'test', 'non_ascii') out = JINJA(fn, opts=self.local_opts, saltenv='test') with salt.utils.fopen(out['data']) as fp: result = fp.read().decode('utf-8') self.assertEqual(u'Assunção\n', result) def test_get_context_has_enough_context(self): template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf' context = get_context(template, 8) expected = '---\n[...]\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\n[...]\n---' self.assertEqual(expected, context) def test_get_context_at_top_of_file(self): template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf' context = get_context(template, 1) expected = '---\n1\n2\n3\n4\n5\n6\n[...]\n---' self.assertEqual(expected, context) def test_get_context_at_bottom_of_file(self): template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf' context = get_context(template, 15) expected = '---\n[...]\na\nb\nc\nd\ne\nf\n---' self.assertEqual(expected, context) def test_get_context_2_context_lines(self): template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf' context = get_context(template, 8, num_lines=2) expected = '---\n[...]\n6\n7\n8\n9\na\n[...]\n---' self.assertEqual(expected, context) def test_get_context_with_marker(self): template = '1\n2\n3\n4\n5\n6\n7\n8\n9\na\nb\nc\nd\ne\nf' context = get_context(template, 8, num_lines=2, marker=' <---') expected = '---\n[...]\n6\n7\n8 <---\n9\na\n[...]\n---' self.assertEqual(expected, context) def test_render_with_syntax_error(self): template = 'hello\n\n{{ bad\n\nfoo' expected = r'.*---\nhello\n\n{{ bad\n\nfoo <======================\n---' self.assertRaisesRegexp( SaltRenderError, expected, render_jinja_tmpl, template, dict(opts=self.local_opts, saltenv='test') ) def test_render_with_unicode_syntax_error(self): encoding = builtins.__salt_system_encoding__ builtins.__salt_system_encoding__ = 'utf-8' template = u'hello\n\n{{ bad\n\nfoo\ud55c' expected = r'.*---\nhello\n\n{{ bad\n\nfoo\xed\x95\x9c <======================\n---' self.assertRaisesRegexp( SaltRenderError, expected, render_jinja_tmpl, template, dict(opts=self.local_opts, saltenv='test') ) builtins.__salt_system_encoding__ = encoding def test_render_with_utf8_syntax_error(self): encoding = builtins.__salt_system_encoding__ builtins.__salt_system_encoding__ = 'utf-8' template = 'hello\n\n{{ bad\n\nfoo\xed\x95\x9c' expected = r'.*---\nhello\n\n{{ bad\n\nfoo\xed\x95\x9c <======================\n---' self.assertRaisesRegexp( SaltRenderError, expected, render_jinja_tmpl, template, dict(opts=self.local_opts, saltenv='test') ) builtins.__salt_system_encoding__ = encoding def test_render_with_undefined_variable(self): template = "hello\n\n{{ foo }}\n\nfoo" expected = r'Jinja variable \'foo\' is undefined' self.assertRaisesRegexp( SaltRenderError, expected, render_jinja_tmpl, template, dict(opts=self.local_opts, saltenv='test') ) def test_render_with_undefined_variable_utf8(self): template = "hello\xed\x95\x9c\n\n{{ foo }}\n\nfoo" expected = r'Jinja variable \'foo\' is undefined' self.assertRaisesRegexp( SaltRenderError, expected, render_jinja_tmpl, template, dict(opts=self.local_opts, saltenv='test') ) def test_render_with_undefined_variable_unicode(self): template = u"hello\ud55c\n\n{{ foo }}\n\nfoo" expected = r'Jinja variable \'foo\' is undefined' self.assertRaisesRegexp( SaltRenderError, expected, render_jinja_tmpl, template, dict(opts=self.local_opts, saltenv='test') ) class TestCustomExtensions(TestCase): def test_serialize_json(self): dataset = { "foo": True, "bar": 42, "baz": [1, 2, 3], "qux": 2.0 } env = Environment(extensions=[SerializerExtension]) rendered = env.from_string('{{ dataset|json }}').render(dataset=dataset) self.assertEqual(dataset, json.loads(rendered)) def test_serialize_yaml(self): dataset = { "foo": True, "bar": 42, "baz": [1, 2, 3], "qux": 2.0 } env = Environment(extensions=[SerializerExtension]) rendered = env.from_string('{{ dataset|yaml }}').render(dataset=dataset) self.assertEqual(dataset, yaml.load(rendered)) def test_serialize_python(self): dataset = { "foo": True, "bar": 42, "baz": [1, 2, 3], "qux": 2.0 } env = Environment(extensions=[SerializerExtension]) rendered = env.from_string('{{ dataset|python }}').render(dataset=dataset) self.assertEqual(rendered, pprint.pformat(dataset)) def test_load_yaml(self): env = Environment(extensions=[SerializerExtension]) rendered = env.from_string('{% set document = "{foo: it works}"|load_yaml %}{{ document.foo }}').render() self.assertEqual(rendered, u"it works") rendered = env.from_string('{% set document = document|load_yaml %}' '{{ document.foo }}').render(document="{foo: it works}") self.assertEqual(rendered, u"it works") with self.assertRaises(exceptions.TemplateRuntimeError): env.from_string('{% set document = document|load_yaml %}' '{{ document.foo }}').render(document={"foo": "it works"}) def test_load_tag(self): env = Environment(extensions=[SerializerExtension]) source = '{{ bar }}, ' + \ '{% load_yaml as docu %}{foo: it works, {{ bar }}: baz}{% endload %}' + \ '{{ docu.foo }}' rendered = env.from_string(source).render(bar="barred") self.assertEqual(rendered, u"barred, it works") source = '{{ bar }}, {% load_json as docu %}{"foo": "it works", "{{ bar }}": "baz"}{% endload %}' + \ '{{ docu.foo }}' rendered = env.from_string(source).render(bar="barred") self.assertEqual(rendered, u"barred, it works") with self.assertRaises(exceptions.TemplateSyntaxError): env.from_string('{% load_yamle as document %}{foo, bar: it works}{% endload %}').render() with self.assertRaises(exceptions.TemplateRuntimeError): env.from_string('{% load_json as document %}{foo, bar: it works}{% endload %}').render() def test_load_json(self): env = Environment(extensions=[SerializerExtension]) rendered = env.from_string('{% set document = \'{"foo": "it works"}\'|load_json %}' '{{ document.foo }}').render() self.assertEqual(rendered, u"it works") rendered = env.from_string('{% set document = document|load_json %}' '{{ document.foo }}').render(document='{"foo": "it works"}') self.assertEqual(rendered, u"it works") # bad quotes with self.assertRaises(exceptions.TemplateRuntimeError): env.from_string("{{ document|load_json }}").render(document="{'foo': 'it works'}") # not a string with self.assertRaises(exceptions.TemplateRuntimeError): env.from_string('{{ document|load_json }}').render(document={"foo": "it works"}) def test_load_yaml_template(self): loader = DictLoader({'foo': '{bar: "my god is blue", foo: [1, 2, 3]}'}) env = Environment(extensions=[SerializerExtension], loader=loader) rendered = env.from_string('{% import_yaml "foo" as doc %}{{ doc.bar }}').render() self.assertEqual(rendered, u"my god is blue") with self.assertRaises(exceptions.TemplateNotFound): env.from_string('{% import_yaml "does not exists" as doc %}').render() def test_load_json_template(self): loader = DictLoader({'foo': '{"bar": "my god is blue", "foo": [1, 2, 3]}'}) env = Environment(extensions=[SerializerExtension], loader=loader) rendered = env.from_string('{% import_json "foo" as doc %}{{ doc.bar }}').render() self.assertEqual(rendered, u"my god is blue") with self.assertRaises(exceptions.TemplateNotFound): env.from_string('{% import_json "does not exists" as doc %}').render() def test_load_text_template(self): loader = DictLoader({'foo': 'Foo!'}) env = Environment(extensions=[SerializerExtension], loader=loader) rendered = env.from_string('{% import_text "foo" as doc %}{{ doc }}').render() self.assertEqual(rendered, u"Foo!") with self.assertRaises(exceptions.TemplateNotFound): env.from_string('{% import_text "does not exists" as doc %}').render() def test_catalog(self): loader = DictLoader({ 'doc1': '{bar: "my god is blue"}', 'doc2': '{% import_yaml "doc1" as local2 %} never exported', 'doc3': '{% load_yaml as local3 %}{"foo": "it works"}{% endload %} me neither', 'main1': '{% from "doc2" import local2 %}{{ local2.bar }}', 'main2': '{% from "doc3" import local3 %}{{ local3.foo }}', 'main3': ''' {% import "doc2" as imported2 %} {% import "doc3" as imported3 %} {{ imported2.local2.bar }} ''', 'main4': ''' {% import "doc2" as imported2 %} {% import "doc3" as imported3 %} {{ imported3.local3.foo }} ''', 'main5': ''' {% from "doc2" import local2 as imported2 %} {% from "doc3" import local3 as imported3 %} {{ imported2.bar }} ''', 'main6': ''' {% from "doc2" import local2 as imported2 %} {% from "doc3" import local3 as imported3 %} {{ imported3.foo }} ''' }) env = Environment(extensions=[SerializerExtension], loader=loader) rendered = env.get_template('main1').render() self.assertEqual(rendered, u"my god is blue") rendered = env.get_template('main2').render() self.assertEqual(rendered, u"it works") rendered = env.get_template('main3').render().strip() self.assertEqual(rendered, u"my god is blue") rendered = env.get_template('main4').render().strip() self.assertEqual(rendered, u"it works") rendered = env.get_template('main5').render().strip() self.assertEqual(rendered, u"my god is blue") rendered = env.get_template('main6').render().strip() self.assertEqual(rendered, u"it works") def test_nested_structures(self): env = Environment(extensions=[SerializerExtension]) rendered = env.from_string('{{ data }}').render(data="foo") self.assertEqual(rendered, u"foo") data = OrderedDict([ ('foo', OrderedDict([ ('bar', 'baz'), ('qux', 42) ]) ) ]) rendered = env.from_string('{{ data }}').render(data=data) self.assertEqual(rendered, u"{'foo': {'bar': 'baz', 'qux': 42}}") rendered = env.from_string('{{ data }}').render(data=[ OrderedDict( foo='bar', ), OrderedDict( baz=42, ) ]) self.assertEqual(rendered, u"[{'foo': 'bar'}, {'baz': 42}]") def test_sequence(self): env = Environment() env.filters['sequence'] = ensure_sequence_filter rendered = env.from_string('{{ data | sequence | length }}') \ .render(data='foo') self.assertEqual(rendered, '1') rendered = env.from_string('{{ data | sequence | length }}') \ .render(data=['foo', 'bar']) self.assertEqual(rendered, '2') rendered = env.from_string('{{ data | sequence | length }}') \ .render(data=('foo', 'bar')) self.assertEqual(rendered, '2') rendered = env.from_string('{{ data | sequence | length }}') \ .render(data=set(['foo', 'bar'])) self.assertEqual(rendered, '2') rendered = env.from_string('{{ data | sequence | length }}') \ .render(data={'foo': 'bar'}) self.assertEqual(rendered, '1') # def test_print(self): # env = Environment(extensions=[SerializerExtension]) # source = '{% import_yaml "toto.foo" as docu %}' # name, filename = None, '<filename>' # parsed = env._parse(source, name, filename) # print parsed # print # compiled = env._generate(parsed, name, filename) # print compiled # return class TestDotNotationLookup(ModuleCase): ''' Tests to call Salt functions via Jinja with various lookup syntaxes ''' def setUp(self, *args, **kwargs): functions = { 'mocktest.ping': lambda: True, 'mockgrains.get': lambda x: 'jerry', } minion_opts = salt.config.minion_config(os.path.join(TMP_CONF_DIR, 'minion')) render = salt.loader.render(minion_opts, functions) self.jinja = render.get('jinja') def render(self, tmpl_str, context=None): return self.jinja(tmpl_str, context=context or {}, from_str=True).read() def test_normlookup(self): ''' Sanity-check the normal dictionary-lookup syntax for our stub function ''' tmpl_str = '''Hello, {{ salt['mocktest.ping']() }}.''' ret = self.render(tmpl_str) self.assertEqual(ret, 'Hello, True.') def test_dotlookup(self): ''' Check calling a stub function using awesome dot-notation ''' tmpl_str = '''Hello, {{ salt.mocktest.ping() }}.''' ret = self.render(tmpl_str) self.assertEqual(ret, 'Hello, True.') def test_shadowed_dict_method(self): ''' Check calling a stub function with a name that shadows a ``dict`` method name ''' tmpl_str = '''Hello, {{ salt.mockgrains.get('id') }}.''' ret = self.render(tmpl_str) self.assertEqual(ret, 'Hello, jerry.') if __name__ == '__main__': from integration import run_tests run_tests(TestSaltCacheLoader, TestGetTemplate, TestCustomExtensions, TestDotNotationLookup, needs_daemon=False)
apache-2.0
-7,130,847,342,912,362,000
37.835635
113
0.548316
false
goksie/newfies-dialer
newfies/survey/urls.py
4
1597
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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) 2011-2014 Star2Billing S.L. # # The Initial Developer of the Original Code is # Arezqui Belaid <info@star2billing.com> # from django.conf.urls import patterns urlpatterns = patterns('survey.views', # Survey urls (r'^module/survey/$', 'survey_list'), (r'^module/survey/add/$', 'survey_add'), (r'^module/sealed_survey_view/(.+)/$', 'sealed_survey_view'), (r'^module/survey/del/(.+)/$', 'survey_del'), (r'^module/survey/(.+)/$', 'survey_change'), (r'^module/export_survey/(.+)/$', 'export_survey'), (r'^module/import_survey/$', 'import_survey'), (r'^module/sealed_survey/$', 'sealed_survey_list'), (r'^module/seal_survey/(.+)/$', 'seal_survey'), # Section urls (r'^section/add/$', 'section_add'), (r'^section/branch/add/$', 'section_branch_add'), (r'^section/delete/(?P<id>\w+)/$', 'section_delete'), (r'^section/(?P<id>\w+)/$', 'section_change'), (r'^section/script/(?P<id>\w+)/$', 'section_script_change'), (r'^section/script_play/(?P<id>\w+)/$', 'section_script_play'), (r'^section/branch/(?P<id>\w+)/$', 'section_branch_change'), # Survey Report urls (r'^survey_report/$', 'survey_report'), (r'^export_surveycall_report/$', 'export_surveycall_report'), (r'^survey_campaign_result/(?P<id>\w+)/$', 'survey_campaign_result'), )
mpl-2.0
1,297,583,328,540,066,600
36.139535
75
0.61866
false
GyrosOfWar/servo
tests/wpt/css-tests/tools/webdriver/webdriver/exceptions.py
263
6460
"""Definition of WebDriverException classes.""" def create_webdriver_exception_strict(status_code, message): """Create the appropriate WebDriverException given the status_code.""" if status_code in _exceptions_strict: return _exceptions_strict[status_code](message) return UnknownStatusCodeException("[%s] %s" % (status_code, message)) def create_webdriver_exception_compatibility(status_code, message): """Create the appropriate WebDriverException given the status_code.""" if status_code in _exceptions_compatibility: return _exceptions_compatibility[status_code](message) return UnknownStatusCodeException("[%s] %s" % (status_code, message)) class WebDriverException(Exception): """Base class for all WebDriverExceptions.""" class UnableToSetCookieException(WebDriverException): """A request to set a cookie's value could not be satisfied.""" class InvalidElementStateException(WebDriverException): """An element command could not be completed because the element is in an invalid state (e.g. attempting to click an element that is no longer attached to the DOM). """ class NoSuchElementException(WebDriverException): """An element could not be located on the page using the given search parameters. """ class TimeoutException(WebDriverException): """An operation did not complete before its timeout expired.""" class ElementNotSelectableException(InvalidElementStateException): """An attempt was made to select an element that cannot be selected.""" class ElementNotVisibleException(InvalidElementStateException): """An element command could not be completed because the element is not visible on the page. """ class ImeEngineActivationFailedException(WebDriverException): """An IME engine could not be started.""" class ImeNotAvailableException(ImeEngineActivationFailedException): """IME was not available.""" class InvalidCookieDomainException(UnableToSetCookieException): """An illegal attempt was made to set a cookie under a different domain than the current page. """ class InvalidElementCoordinatesException(WebDriverException): """The coordinates provided to an interactions operation are invalid.""" class InvalidSelectorException(NoSuchElementException): """Argument was an invalid selector (e.g. XPath/CSS).""" class JavascriptErrorException(WebDriverException): """An error occurred while executing user supplied JavaScript.""" class MoveTargetOutOfBoundsException(InvalidElementStateException): """The target for mouse interaction is not in the browser's viewport and cannot be brought into that viewport. """ class NoSuchAlertException(WebDriverException): """An attempt was made to operate on a modal dialog when one was not open.""" class NoSuchFrameException(WebDriverException): """A request to switch to a frame could not be satisfied because the frame could not be found.""" class NoSuchWindowException(WebDriverException): """A request to switch to a different window could not be satisfied because the window could not be found. """ class ScriptTimeoutException(TimeoutException): """A script did not complete before its timeout expired.""" class SessionNotCreatedException(WebDriverException): """A new session could not be created.""" class StaleElementReferenceException(InvalidElementStateException): """An element command failed because the referenced element is no longer attached to the DOM. """ class UnexpectedAlertOpenException(WebDriverException): """A modal dialog was open, blocking this operation.""" class UnknownCommandException(WebDriverException): """A command could not be executed because the remote end is not aware of it. """ class UnknownErrorException(WebDriverException): """An unknown error occurred in the remote end while processing the command. """ class UnsupportedOperationException(WebDriverException): """Indicates that a command that should have executed properly cannot be supported for some reason. """ class UnknownStatusCodeException(WebDriverException): """Exception for all other status codes.""" _exceptions_strict = { "element not selectable": ElementNotSelectableException, "element not visible": ElementNotVisibleException, "ime engine activation failed": ImeEngineActivationFailedException, "ime not available": ImeNotAvailableException, "invalid cookie domain": InvalidCookieDomainException, "invalid element coordinates": InvalidElementCoordinatesException, "invalid element state": InvalidElementStateException, "invalid selector": InvalidSelectorException, "javascript error": JavascriptErrorException, "move target out of bounds": MoveTargetOutOfBoundsException, "no such alert": NoSuchAlertException, "no such element": NoSuchElementException, "no such frame": NoSuchFrameException, "no such window": NoSuchWindowException, "script timeout": ScriptTimeoutException, "session not created": SessionNotCreatedException, "stale element reference": StaleElementReferenceException, "success": None, "timeout": TimeoutException, "unable to set cookie": UnableToSetCookieException, "unexpected alert open": UnexpectedAlertOpenException, "unknown command": UnknownCommandException, "unknown error": UnknownErrorException, "unsupported operation": UnsupportedOperationException, } _exceptions_compatibility = { 15: ElementNotSelectableException, 11: ElementNotVisibleException, 31: ImeEngineActivationFailedException, 30: ImeNotAvailableException, 24: InvalidCookieDomainException, 29: InvalidElementCoordinatesException, 12: InvalidElementStateException, 19: InvalidSelectorException, 32: InvalidSelectorException, 17: JavascriptErrorException, 34: MoveTargetOutOfBoundsException, 27: NoSuchAlertException, 7: NoSuchElementException, 8: NoSuchFrameException, 23: NoSuchWindowException, 28: ScriptTimeoutException, 6: SessionNotCreatedException, 33: SessionNotCreatedException, 10: StaleElementReferenceException, 0: None, # success 21: TimeoutException, 25: UnableToSetCookieException, 26: UnexpectedAlertOpenException, 9: UnknownCommandException, 13: UnknownErrorException, # "unsupported operation": UnsupportedOperationException }
mpl-2.0
-6,763,187,260,070,101,000
37.915663
81
0.762539
false
mshafiq9/django
django/views/generic/detail.py
306
6922
from __future__ import unicode_literals from django.core.exceptions import ImproperlyConfigured from django.db import models from django.http import Http404 from django.utils.translation import ugettext as _ from django.views.generic.base import ContextMixin, TemplateResponseMixin, View class SingleObjectMixin(ContextMixin): """ Provides the ability to retrieve a single object for further manipulation. """ model = None queryset = None slug_field = 'slug' context_object_name = None slug_url_kwarg = 'slug' pk_url_kwarg = 'pk' query_pk_and_slug = False def get_object(self, queryset=None): """ Returns the object the view is displaying. By default this requires `self.queryset` and a `pk` or `slug` argument in the URLconf, but subclasses can override this to return any object. """ # Use a custom queryset if provided; this is required for subclasses # like DateDetailView if queryset is None: queryset = self.get_queryset() # Next, try looking up by primary key. pk = self.kwargs.get(self.pk_url_kwarg) slug = self.kwargs.get(self.slug_url_kwarg) if pk is not None: queryset = queryset.filter(pk=pk) # Next, try looking up by slug. if slug is not None and (pk is None or self.query_pk_and_slug): slug_field = self.get_slug_field() queryset = queryset.filter(**{slug_field: slug}) # If none of those are defined, it's an error. if pk is None and slug is None: raise AttributeError("Generic detail view %s must be called with " "either an object pk or a slug." % self.__class__.__name__) try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: raise Http404(_("No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name}) return obj def get_queryset(self): """ Return the `QuerySet` that will be used to look up the object. Note that this method is called by the default implementation of `get_object` and may not be called if `get_object` is overridden. """ if self.queryset is None: if self.model: return self.model._default_manager.all() else: raise ImproperlyConfigured( "%(cls)s is missing a QuerySet. Define " "%(cls)s.model, %(cls)s.queryset, or override " "%(cls)s.get_queryset()." % { 'cls': self.__class__.__name__ } ) return self.queryset.all() def get_slug_field(self): """ Get the name of a slug field to be used to look up by slug. """ return self.slug_field def get_context_object_name(self, obj): """ Get the name to use for the object. """ if self.context_object_name: return self.context_object_name elif isinstance(obj, models.Model): if self.object._deferred: obj = obj._meta.proxy_for_model return obj._meta.model_name else: return None def get_context_data(self, **kwargs): """ Insert the single object into the context dict. """ context = {} if self.object: context['object'] = self.object context_object_name = self.get_context_object_name(self.object) if context_object_name: context[context_object_name] = self.object context.update(kwargs) return super(SingleObjectMixin, self).get_context_data(**context) class BaseDetailView(SingleObjectMixin, View): """ A base view for displaying a single object """ def get(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) class SingleObjectTemplateResponseMixin(TemplateResponseMixin): template_name_field = None template_name_suffix = '_detail' def get_template_names(self): """ Return a list of template names to be used for the request. May not be called if render_to_response is overridden. Returns the following list: * the value of ``template_name`` on the view (if provided) * the contents of the ``template_name_field`` field on the object instance that the view is operating upon (if available) * ``<app_label>/<model_name><template_name_suffix>.html`` """ try: names = super(SingleObjectTemplateResponseMixin, self).get_template_names() except ImproperlyConfigured: # If template_name isn't specified, it's not a problem -- # we just start with an empty list. names = [] # If self.template_name_field is set, grab the value of the field # of that name from the object; this is the most specific template # name, if given. if self.object and self.template_name_field: name = getattr(self.object, self.template_name_field, None) if name: names.insert(0, name) # The least-specific option is the default <app>/<model>_detail.html; # only use this if the object in question is a model. if isinstance(self.object, models.Model): object_meta = self.object._meta if self.object._deferred: object_meta = self.object._meta.proxy_for_model._meta names.append("%s/%s%s.html" % ( object_meta.app_label, object_meta.model_name, self.template_name_suffix )) elif hasattr(self, 'model') and self.model is not None and issubclass(self.model, models.Model): names.append("%s/%s%s.html" % ( self.model._meta.app_label, self.model._meta.model_name, self.template_name_suffix )) # If we still haven't managed to find any template names, we should # re-raise the ImproperlyConfigured to alert the user. if not names: raise return names class DetailView(SingleObjectTemplateResponseMixin, BaseDetailView): """ Render a "detail" view of an object. By default this is a model instance looked up from `self.queryset`, but the view will support display of *any* object by overriding `self.get_object()`. """
bsd-3-clause
-6,310,951,046,772,378,000
36.825137
108
0.582202
false
takeflight/wagtailmodelchooser
wagtailmodelchooser/__init__.py
1
2011
from .utils import kwarg_decorator, last_arg_decorator from .version import version as __version__ from .version import version_info __all__ = [ '__version__', 'version_info', 'registry', 'register_model_chooser', 'register_simple_model_chooser', 'register_filter', ] class Registry(object): def __init__(self): self.choosers = {} self.filters = {} def register_chooser(self, chooser, **kwargs): """Adds a model chooser definition to the registry.""" if not issubclass(chooser, Chooser): return self.register_simple_chooser(chooser, **kwargs) self.choosers[chooser.model] = chooser(**kwargs) return chooser def register_simple_chooser(self, model, **kwargs): """ Generates a model chooser definition from a model, and adds it to the registry. """ name = '{}Chooser'.format(model._meta.object_name) attrs = {'model': model} attrs.update(kwargs) chooser = type(name, (Chooser,), attrs) self.register_chooser(chooser) return model def register_filter(self, model, name, filter): assert model in self.choosers self.filters[(model, name)] = filter return filter class Chooser(object): model = None icon = 'placeholder' # Customize the chooser content for just this model modal_template = None modal_results_template = None def get_queryset(self, request): return self.model._default_manager.all() def get_modal_template(self, request): return self.modal_template or 'wagtailmodelchooser/modal.html' def get_modal_results_template(self, request): return self.modal_results_template or 'wagtailmodelchooser/results.html' registry = Registry() register_model_chooser = kwarg_decorator(registry.register_chooser) register_simple_model_chooser = kwarg_decorator(registry.register_simple_chooser) register_filter = last_arg_decorator(registry.register_filter)
bsd-2-clause
-339,373,218,791,220,300
29.469697
81
0.665341
false
hsuchie4/TACTIC
src/pyasm/deprecated/flash/flash_file_naming.py
6
1678
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permission. # # # __all__ = ['FlashFileNaming'] import os, re from pyasm.biz import FileNaming, Project, Snapshot, File from pyasm.common import TacticException class FlashFileNaming(FileNaming): def add_ending(my, parts, auto_version=False): context = my.snapshot.get_value("context") version = my.snapshot.get_value("version") version = "v%0.3d" % version ext = my.get_ext() # it is only unique if we use both context and version parts.append(context) parts.append(version) filename = "_".join(parts) filename = "%s%s" % (filename, ext) # should I check if this filename is unique again? return filename # custom filename processing per sobject begins def _get_unique_filename(my): filename = my.file_object.get_full_file_name() # find if this filename has been used for this project file = File.get_by_filename(filename, skip_id=my.file_object.get_id()) if file: root, ext = os.path.splitext(filename) parts = [root] filename = my.add_ending(parts, auto_version=True) return filename else: return None def flash_nat_pause(my): return my._get_unique_filename() def flash_final_wave(my): return my._get_unique_filename()
epl-1.0
7,258,592,367,855,573,000
26.966667
78
0.607867
false
dparlevliet/zelenka-report-storage
server-local/twisted/internet/unix.py
41
17920
# -*- test-case-name: twisted.test.test_unix,twisted.internet.test.test_unix,twisted.internet.test.test_posixbase -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Various asynchronous TCP/IP classes. End users shouldn't use this module directly - use the reactor APIs instead. Maintainer: Itamar Shtull-Trauring """ # System imports import os, sys, stat, socket, struct from errno import EINTR, EMSGSIZE, EAGAIN, EWOULDBLOCK, ECONNREFUSED, ENOBUFS from zope.interface import implements, implementsOnly, implementedBy if not hasattr(socket, 'AF_UNIX'): raise ImportError("UNIX sockets not supported on this platform") # Twisted imports from twisted.internet import main, base, tcp, udp, error, interfaces, protocol, address from twisted.internet.error import CannotListenError from twisted.python.util import untilConcludes from twisted.python import lockfile, log, reflect, failure try: from twisted.python import sendmsg except ImportError: sendmsg = None def _ancillaryDescriptor(fd): """ Pack an integer into an ancillary data structure suitable for use with L{sendmsg.send1msg}. """ packed = struct.pack("i", fd) return [(socket.SOL_SOCKET, sendmsg.SCM_RIGHTS, packed)] class _SendmsgMixin(object): """ Mixin for stream-oriented UNIX transports which uses sendmsg and recvmsg to offer additional functionality, such as copying file descriptors into other processes. @ivar _writeSomeDataBase: The class which provides the basic implementation of C{writeSomeData}. Ultimately this should be a subclass of L{twisted.internet.abstract.FileDescriptor}. Subclasses which mix in L{_SendmsgMixin} must define this. @ivar _sendmsgQueue: A C{list} of C{int} holding file descriptors which are currently buffered before being sent. @ivar _fileDescriptorBufferSize: An C{int} giving the maximum number of file descriptors to accept and queue for sending before pausing the registered producer, if there is one. """ implements(interfaces.IUNIXTransport) _writeSomeDataBase = None _fileDescriptorBufferSize = 64 def __init__(self): self._sendmsgQueue = [] def _isSendBufferFull(self): """ Determine whether the user-space send buffer for this transport is full or not. This extends the base determination by adding consideration of how many file descriptors need to be sent using L{sendmsg.send1msg}. When there are more than C{self._fileDescriptorBufferSize}, the buffer is considered full. @return: C{True} if it is full, C{False} otherwise. """ # There must be some bytes in the normal send buffer, checked by # _writeSomeDataBase._isSendBufferFull, in order to send file # descriptors from _sendmsgQueue. That means that the buffer will # eventually be considered full even without this additional logic. # However, since we send only one byte per file descriptor, having lots # of elements in _sendmsgQueue incurs more overhead and perhaps slows # things down. Anyway, try this for now, maybe rethink it later. return ( len(self._sendmsgQueue) > self._fileDescriptorBufferSize or self._writeSomeDataBase._isSendBufferFull(self)) def sendFileDescriptor(self, fileno): """ Queue the given file descriptor to be sent and start trying to send it. """ self._sendmsgQueue.append(fileno) self._maybePauseProducer() self.startWriting() def writeSomeData(self, data): """ Send as much of C{data} as possible. Also send any pending file descriptors. """ # Make it a programming error to send more file descriptors than you # send regular bytes. Otherwise, due to the limitation mentioned below, # we could end up with file descriptors left, but no bytes to send with # them, therefore no way to send those file descriptors. if len(self._sendmsgQueue) > len(data): return error.FileDescriptorOverrun() # If there are file descriptors to send, try sending them first, using a # little bit of data from the stream-oriented write buffer too. It is # not possible to send a file descriptor without sending some regular # data. index = 0 try: while index < len(self._sendmsgQueue): fd = self._sendmsgQueue[index] try: untilConcludes( sendmsg.send1msg, self.socket.fileno(), data[index], 0, _ancillaryDescriptor(fd)) except socket.error, se: if se.args[0] in (EWOULDBLOCK, ENOBUFS): return index else: return main.CONNECTION_LOST else: index += 1 finally: del self._sendmsgQueue[:index] # Hand the remaining data to the base implementation. Avoid slicing in # favor of a buffer, in case that happens to be any faster. limitedData = buffer(data, index) result = self._writeSomeDataBase.writeSomeData(self, limitedData) try: return index + result except TypeError: return result def doRead(self): """ Calls L{IFileDescriptorReceiver.fileDescriptorReceived} and L{IProtocol.dataReceived} with all available data. This reads up to C{self.bufferSize} bytes of data from its socket, then dispatches the data to protocol callbacks to be handled. If the connection is not lost through an error in the underlying recvmsg(), this function will return the result of the dataReceived call. """ try: data, flags, ancillary = untilConcludes( sendmsg.recv1msg, self.socket.fileno(), 0, self.bufferSize) except socket.error, se: if se.args[0] == EWOULDBLOCK: return else: return main.CONNECTION_LOST if ancillary: fd = struct.unpack('i', ancillary[0][2])[0] if interfaces.IFileDescriptorReceiver.providedBy(self.protocol): self.protocol.fileDescriptorReceived(fd) else: log.msg( format=( "%(protocolName)s (on %(hostAddress)r) does not " "provide IFileDescriptorReceiver; closing file " "descriptor received (from %(peerAddress)r)."), hostAddress=self.getHost(), peerAddress=self.getPeer(), protocolName=self._getLogPrefix(self.protocol), ) os.close(fd) return self._dataReceived(data) if sendmsg is None: class _SendmsgMixin(object): """ Behaviorless placeholder used when L{twisted.python.sendmsg} is not available, preventing L{IUNIXTransport} from being supported. """ class Server(_SendmsgMixin, tcp.Server): _writeSomeDataBase = tcp.Server def __init__(self, sock, protocol, client, server, sessionno, reactor): _SendmsgMixin.__init__(self) tcp.Server.__init__(self, sock, protocol, (client, None), server, sessionno, reactor) def getHost(self): return address.UNIXAddress(self.socket.getsockname()) def getPeer(self): return address.UNIXAddress(self.hostname or None) def _inFilesystemNamespace(path): """ Determine whether the given unix socket path is in a filesystem namespace. While most PF_UNIX sockets are entries in the filesystem, Linux 2.2 and above support PF_UNIX sockets in an "abstract namespace" that does not correspond to any path. This function returns C{True} if the given socket path is stored in the filesystem and C{False} if the path is in this abstract namespace. """ return path[:1] != "\0" class _UNIXPort(object): def getHost(self): """Returns a UNIXAddress. This indicates the server's address. """ if sys.version_info > (2, 5) or _inFilesystemNamespace(self.port): path = self.socket.getsockname() else: # Abstract namespace sockets aren't well supported on Python 2.4. # getsockname() always returns ''. path = self.port return address.UNIXAddress(path) class Port(_UNIXPort, tcp.Port): addressFamily = socket.AF_UNIX socketType = socket.SOCK_STREAM transport = Server lockFile = None def __init__(self, fileName, factory, backlog=50, mode=0666, reactor=None, wantPID = 0): tcp.Port.__init__(self, fileName, factory, backlog, reactor=reactor) self.mode = mode self.wantPID = wantPID def __repr__(self): factoryName = reflect.qual(self.factory.__class__) if hasattr(self, 'socket'): return '<%s on %r>' % (factoryName, self.port) else: return '<%s (not listening)>' % (factoryName,) def _buildAddr(self, name): return address.UNIXAddress(name) def startListening(self): """ Create and bind my socket, and begin listening on it. This is called on unserialization, and must be called after creating a server to begin listening on the specified port. """ log.msg("%s starting on %r" % ( self._getLogPrefix(self.factory), self.port)) if self.wantPID: self.lockFile = lockfile.FilesystemLock(self.port + ".lock") if not self.lockFile.lock(): raise CannotListenError, (None, self.port, "Cannot acquire lock") else: if not self.lockFile.clean: try: # This is a best-attempt at cleaning up # left-over unix sockets on the filesystem. # If it fails, there's not much else we can # do. The bind() below will fail with an # exception that actually propagates. if stat.S_ISSOCK(os.stat(self.port).st_mode): os.remove(self.port) except: pass self.factory.doStart() try: skt = self.createInternetSocket() skt.bind(self.port) except socket.error, le: raise CannotListenError, (None, self.port, le) else: if _inFilesystemNamespace(self.port): # Make the socket readable and writable to the world. os.chmod(self.port, self.mode) skt.listen(self.backlog) self.connected = True self.socket = skt self.fileno = self.socket.fileno self.numberAccepts = 100 self.startReading() def _logConnectionLostMsg(self): """ Log message for closing socket """ log.msg('(UNIX Port %s Closed)' % (repr(self.port),)) def connectionLost(self, reason): if _inFilesystemNamespace(self.port): os.unlink(self.port) if self.lockFile is not None: self.lockFile.unlock() tcp.Port.connectionLost(self, reason) class Client(_SendmsgMixin, tcp.BaseClient): """A client for Unix sockets.""" addressFamily = socket.AF_UNIX socketType = socket.SOCK_STREAM _writeSomeDataBase = tcp.BaseClient def __init__(self, filename, connector, reactor=None, checkPID = 0): _SendmsgMixin.__init__(self) self.connector = connector self.realAddress = self.addr = filename if checkPID and not lockfile.isLocked(filename + ".lock"): self._finishInit(None, None, error.BadFileError(filename), reactor) self._finishInit(self.doConnect, self.createInternetSocket(), None, reactor) def getPeer(self): return address.UNIXAddress(self.addr) def getHost(self): return address.UNIXAddress(None) class Connector(base.BaseConnector): def __init__(self, address, factory, timeout, reactor, checkPID): base.BaseConnector.__init__(self, factory, timeout, reactor) self.address = address self.checkPID = checkPID def _makeTransport(self): return Client(self.address, self, self.reactor, self.checkPID) def getDestination(self): return address.UNIXAddress(self.address) class DatagramPort(_UNIXPort, udp.Port): """Datagram UNIX port, listening for packets.""" implements(interfaces.IUNIXDatagramTransport) addressFamily = socket.AF_UNIX def __init__(self, addr, proto, maxPacketSize=8192, mode=0666, reactor=None): """Initialize with address to listen on. """ udp.Port.__init__(self, addr, proto, maxPacketSize=maxPacketSize, reactor=reactor) self.mode = mode def __repr__(self): protocolName = reflect.qual(self.protocol.__class__,) if hasattr(self, 'socket'): return '<%s on %r>' % (protocolName, self.port) else: return '<%s (not listening)>' % (protocolName,) def _bindSocket(self): log.msg("%s starting on %s"%(self.protocol.__class__, repr(self.port))) try: skt = self.createInternetSocket() # XXX: haha misnamed method if self.port: skt.bind(self.port) except socket.error, le: raise error.CannotListenError, (None, self.port, le) if self.port and _inFilesystemNamespace(self.port): # Make the socket readable and writable to the world. os.chmod(self.port, self.mode) self.connected = 1 self.socket = skt self.fileno = self.socket.fileno def write(self, datagram, address): """Write a datagram.""" try: return self.socket.sendto(datagram, address) except socket.error, se: no = se.args[0] if no == EINTR: return self.write(datagram, address) elif no == EMSGSIZE: raise error.MessageLengthError, "message too long" elif no == EAGAIN: # oh, well, drop the data. The only difference from UDP # is that UDP won't ever notice. # TODO: add TCP-like buffering pass else: raise def connectionLost(self, reason=None): """Cleans up my socket. """ log.msg('(Port %s Closed)' % repr(self.port)) base.BasePort.connectionLost(self, reason) if hasattr(self, "protocol"): # we won't have attribute in ConnectedPort, in cases # where there was an error in connection process self.protocol.doStop() self.connected = 0 self.socket.close() del self.socket del self.fileno if hasattr(self, "d"): self.d.callback(None) del self.d def setLogStr(self): self.logstr = reflect.qual(self.protocol.__class__) + " (UDP)" class ConnectedDatagramPort(DatagramPort): """ A connected datagram UNIX socket. """ implementsOnly(interfaces.IUNIXDatagramConnectedTransport, *(implementedBy(base.BasePort))) def __init__(self, addr, proto, maxPacketSize=8192, mode=0666, bindAddress=None, reactor=None): assert isinstance(proto, protocol.ConnectedDatagramProtocol) DatagramPort.__init__(self, bindAddress, proto, maxPacketSize, mode, reactor) self.remoteaddr = addr def startListening(self): try: self._bindSocket() self.socket.connect(self.remoteaddr) self._connectToProtocol() except: self.connectionFailed(failure.Failure()) def connectionFailed(self, reason): """ Called when a connection fails. Stop listening on the socket. @type reason: L{Failure} @param reason: Why the connection failed. """ self.stopListening() self.protocol.connectionFailed(reason) del self.protocol def doRead(self): """ Called when my socket is ready for reading. """ read = 0 while read < self.maxThroughput: try: data, addr = self.socket.recvfrom(self.maxPacketSize) read += len(data) self.protocol.datagramReceived(data) except socket.error, se: no = se.args[0] if no in (EAGAIN, EINTR, EWOULDBLOCK): return if no == ECONNREFUSED: self.protocol.connectionRefused() else: raise except: log.deferr() def write(self, data): """ Write a datagram. """ try: return self.socket.send(data) except socket.error, se: no = se.args[0] if no == EINTR: return self.write(data) elif no == EMSGSIZE: raise error.MessageLengthError, "message too long" elif no == ECONNREFUSED: self.protocol.connectionRefused() elif no == EAGAIN: # oh, well, drop the data. The only difference from UDP # is that UDP won't ever notice. # TODO: add TCP-like buffering pass else: raise def getPeer(self): return address.UNIXAddress(self.remoteaddr)
lgpl-3.0
4,383,641,988,542,789,000
33.594595
117
0.599275
false
yongshengwang/hue
desktop/core/ext-py/pycrypto-2.6.1/build/lib.linux-x86_64-2.7/Crypto/PublicKey/DSA.py
123
13695
# -*- coding: utf-8 -*- # # PublicKey/DSA.py : DSA signature primitive # # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net> # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # 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. # =================================================================== """DSA public-key signature algorithm. DSA_ is a widespread public-key signature algorithm. Its security is based on the discrete logarithm problem (DLP_). Given a cyclic group, a generator *g*, and an element *h*, it is hard to find an integer *x* such that *g^x = h*. The problem is believed to be difficult, and it has been proved such (and therefore secure) for more than 30 years. The group is actually a sub-group over the integers modulo *p*, with *p* prime. The sub-group order is *q*, which is prime too; it always holds that *(p-1)* is a multiple of *q*. The cryptographic strength is linked to the magnitude of *p* and *q*. The signer holds a value *x* (*0<x<q-1*) as private key, and its public key (*y* where *y=g^x mod p*) is distributed. In 2012, a sufficient size is deemed to be 2048 bits for *p* and 256 bits for *q*. For more information, see the most recent ECRYPT_ report. DSA is reasonably secure for new designs. The algorithm can only be used for authentication (digital signature). DSA cannot be used for confidentiality (encryption). The values *(p,q,g)* are called *domain parameters*; they are not sensitive but must be shared by both parties (the signer and the verifier). Different signers can share the same domain parameters with no security concerns. The DSA signature is twice as big as the size of *q* (64 bytes if *q* is 256 bit long). This module provides facilities for generating new DSA keys and for constructing them from known components. DSA keys allows you to perform basic signing and verification. >>> from Crypto.Random import random >>> from Crypto.PublicKey import DSA >>> from Crypto.Hash import SHA >>> >>> message = "Hello" >>> key = DSA.generate(1024) >>> h = SHA.new(message).digest() >>> k = random.StrongRandom().randint(1,key.q-1) >>> sig = key.sign(h,k) >>> ... >>> if key.verify(h,sig): >>> print "OK" >>> else: >>> print "Incorrect signature" .. _DSA: http://en.wikipedia.org/wiki/Digital_Signature_Algorithm .. _DLP: http://www.cosic.esat.kuleuven.be/publications/talk-78.pdf .. _ECRYPT: http://www.ecrypt.eu.org/documents/D.SPA.17.pdf """ __revision__ = "$Id$" __all__ = ['generate', 'construct', 'error', 'DSAImplementation', '_DSAobj'] import sys if sys.version_info[0] == 2 and sys.version_info[1] == 1: from Crypto.Util.py21compat import * from Crypto.PublicKey import _DSA, _slowmath, pubkey from Crypto import Random try: from Crypto.PublicKey import _fastmath except ImportError: _fastmath = None class _DSAobj(pubkey.pubkey): """Class defining an actual DSA key. :undocumented: __getstate__, __setstate__, __repr__, __getattr__ """ #: Dictionary of DSA parameters. #: #: A public key will only have the following entries: #: #: - **y**, the public key. #: - **g**, the generator. #: - **p**, the modulus. #: - **q**, the order of the sub-group. #: #: A private key will also have: #: #: - **x**, the private key. keydata = ['y', 'g', 'p', 'q', 'x'] def __init__(self, implementation, key): self.implementation = implementation self.key = key def __getattr__(self, attrname): if attrname in self.keydata: # For backward compatibility, allow the user to get (not set) the # DSA key parameters directly from this object. return getattr(self.key, attrname) else: raise AttributeError("%s object has no %r attribute" % (self.__class__.__name__, attrname,)) def sign(self, M, K): """Sign a piece of data with DSA. :Parameter M: The piece of data to sign with DSA. It may not be longer in bit size than the sub-group order (*q*). :Type M: byte string or long :Parameter K: A secret number, chosen randomly in the closed range *[1,q-1]*. :Type K: long (recommended) or byte string (not recommended) :attention: selection of *K* is crucial for security. Generating a random number larger than *q* and taking the modulus by *q* is **not** secure, since smaller values will occur more frequently. Generating a random number systematically smaller than *q-1* (e.g. *floor((q-1)/8)* random bytes) is also **not** secure. In general, it shall not be possible for an attacker to know the value of `any bit of K`__. :attention: The number *K* shall not be reused for any other operation and shall be discarded immediately. :attention: M must be a digest cryptographic hash, otherwise an attacker may mount an existential forgery attack. :Return: A tuple with 2 longs. .. __: http://www.di.ens.fr/~pnguyen/pub_NgSh00.htm """ return pubkey.pubkey.sign(self, M, K) def verify(self, M, signature): """Verify the validity of a DSA signature. :Parameter M: The expected message. :Type M: byte string or long :Parameter signature: The DSA signature to verify. :Type signature: A tuple with 2 longs as return by `sign` :Return: True if the signature is correct, False otherwise. """ return pubkey.pubkey.verify(self, M, signature) def _encrypt(self, c, K): raise TypeError("DSA cannot encrypt") def _decrypt(self, c): raise TypeError("DSA cannot decrypt") def _blind(self, m, r): raise TypeError("DSA cannot blind") def _unblind(self, m, r): raise TypeError("DSA cannot unblind") def _sign(self, m, k): return self.key._sign(m, k) def _verify(self, m, sig): (r, s) = sig return self.key._verify(m, r, s) def has_private(self): return self.key.has_private() def size(self): return self.key.size() def can_blind(self): return False def can_encrypt(self): return False def can_sign(self): return True def publickey(self): return self.implementation.construct((self.key.y, self.key.g, self.key.p, self.key.q)) def __getstate__(self): d = {} for k in self.keydata: try: d[k] = getattr(self.key, k) except AttributeError: pass return d def __setstate__(self, d): if not hasattr(self, 'implementation'): self.implementation = DSAImplementation() t = [] for k in self.keydata: if not d.has_key(k): break t.append(d[k]) self.key = self.implementation._math.dsa_construct(*tuple(t)) def __repr__(self): attrs = [] for k in self.keydata: if k == 'p': attrs.append("p(%d)" % (self.size()+1,)) elif hasattr(self.key, k): attrs.append(k) if self.has_private(): attrs.append("private") # PY3K: This is meant to be text, do not change to bytes (data) return "<%s @0x%x %s>" % (self.__class__.__name__, id(self), ",".join(attrs)) class DSAImplementation(object): """ A DSA key factory. This class is only internally used to implement the methods of the `Crypto.PublicKey.DSA` module. """ def __init__(self, **kwargs): """Create a new DSA key factory. :Keywords: use_fast_math : bool Specify which mathematic library to use: - *None* (default). Use fastest math available. - *True* . Use fast math. - *False* . Use slow math. default_randfunc : callable Specify how to collect random data: - *None* (default). Use Random.new().read(). - not *None* . Use the specified function directly. :Raise RuntimeError: When **use_fast_math** =True but fast math is not available. """ use_fast_math = kwargs.get('use_fast_math', None) if use_fast_math is None: # Automatic if _fastmath is not None: self._math = _fastmath else: self._math = _slowmath elif use_fast_math: # Explicitly select fast math if _fastmath is not None: self._math = _fastmath else: raise RuntimeError("fast math module not available") else: # Explicitly select slow math self._math = _slowmath self.error = self._math.error # 'default_randfunc' parameter: # None (default) - use Random.new().read # not None - use the specified function self._default_randfunc = kwargs.get('default_randfunc', None) self._current_randfunc = None def _get_randfunc(self, randfunc): if randfunc is not None: return randfunc elif self._current_randfunc is None: self._current_randfunc = Random.new().read return self._current_randfunc def generate(self, bits, randfunc=None, progress_func=None): """Randomly generate a fresh, new DSA key. :Parameters: bits : int Key length, or size (in bits) of the DSA modulus *p*. It must be a multiple of 64, in the closed interval [512,1024]. randfunc : callable Random number generation function; it should accept a single integer N and return a string of random data N bytes long. If not specified, a new one will be instantiated from ``Crypto.Random``. progress_func : callable Optional function that will be called with a short string containing the key parameter currently being generated; it's useful for interactive applications where a user is waiting for a key to be generated. :attention: You should always use a cryptographically secure random number generator, such as the one defined in the ``Crypto.Random`` module; **don't** just use the current time and the ``random`` module. :Return: A DSA key object (`_DSAobj`). :Raise ValueError: When **bits** is too little, too big, or not a multiple of 64. """ # Check against FIPS 186-2, which says that the size of the prime p # must be a multiple of 64 bits between 512 and 1024 for i in (0, 1, 2, 3, 4, 5, 6, 7, 8): if bits == 512 + 64*i: return self._generate(bits, randfunc, progress_func) # The March 2006 draft of FIPS 186-3 also allows 2048 and 3072-bit # primes, but only with longer q values. Since the current DSA # implementation only supports a 160-bit q, we don't support larger # values. raise ValueError("Number of bits in p must be a multiple of 64 between 512 and 1024, not %d bits" % (bits,)) def _generate(self, bits, randfunc=None, progress_func=None): rf = self._get_randfunc(randfunc) obj = _DSA.generate_py(bits, rf, progress_func) # TODO: Don't use legacy _DSA module key = self._math.dsa_construct(obj.y, obj.g, obj.p, obj.q, obj.x) return _DSAobj(self, key) def construct(self, tup): """Construct a DSA key from a tuple of valid DSA components. The modulus *p* must be a prime. The following equations must apply: - p-1 = 0 mod q - g^x = y mod p - 0 < x < q - 1 < g < p :Parameters: tup : tuple A tuple of long integers, with 4 or 5 items in the following order: 1. Public key (*y*). 2. Sub-group generator (*g*). 3. Modulus, finite field order (*p*). 4. Sub-group order (*q*). 5. Private key (*x*). Optional. :Return: A DSA key object (`_DSAobj`). """ key = self._math.dsa_construct(*tup) return _DSAobj(self, key) _impl = DSAImplementation() generate = _impl.generate construct = _impl.construct error = _impl.error # vim:set ts=4 sw=4 sts=4 expandtab:
apache-2.0
7,233,003,489,526,411,000
35.134565
116
0.584958
false
afandria/sky_engine
build/android/pylib/host_driven/setup.py
55
6378
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Setup for instrumentation host-driven tests.""" import logging import os import sys import types from pylib.host_driven import test_case from pylib.host_driven import test_info_collection from pylib.host_driven import test_runner def _GetPythonFiles(root, files): """Returns all files from |files| that end in 'Test.py'. Args: root: A directory name with python files. files: A list of file names. Returns: A list with all python files that match the testing naming scheme. """ return [os.path.join(root, f) for f in files if f.endswith('Test.py')] def _InferImportNameFromFile(python_file): """Given a file, infer the import name for that file. Example: /usr/foo/bar/baz.py -> baz. Args: python_file: Path to the Python file, ostensibly to import later. Returns: The module name for the given file. """ return os.path.splitext(os.path.basename(python_file))[0] def _GetTestModules(host_driven_test_root, is_official_build): """Retrieve a list of python modules that match the testing naming scheme. Walks the location of host-driven tests, imports them, and provides the list of imported modules to the caller. Args: host_driven_test_root: The path to walk, looking for the pythonDrivenTests or host_driven_tests directory is_official_build: Whether to run only those tests marked 'official' Returns: A list of python modules under |host_driven_test_root| which match the testing naming scheme. Each module should define one or more classes that derive from HostDrivenTestCase. """ # By default run all host-driven tests under pythonDrivenTests or # host_driven_tests. host_driven_test_file_list = [] for root, _, files in os.walk(host_driven_test_root): if (root.endswith('host_driven_tests') or root.endswith('pythonDrivenTests') or (is_official_build and (root.endswith('pythonDrivenTests/official') or root.endswith('host_driven_tests/official')))): host_driven_test_file_list += _GetPythonFiles(root, files) host_driven_test_file_list.sort() test_module_list = [_GetModuleFromFile(test_file) for test_file in host_driven_test_file_list] return test_module_list def _GetModuleFromFile(python_file): """Gets the python module associated with a file by importing it. Args: python_file: File to import. Returns: The module object. """ sys.path.append(os.path.dirname(python_file)) import_name = _InferImportNameFromFile(python_file) return __import__(import_name) def _GetTestsFromClass(test_case_class, **kwargs): """Returns one test object for each test method in |test_case_class|. Test methods are methods on the class which begin with 'test'. Args: test_case_class: Class derived from HostDrivenTestCase which contains zero or more test methods. kwargs: Keyword args to pass into the constructor of test cases. Returns: A list of test case objects, each initialized for a particular test method. """ test_names = [m for m in dir(test_case_class) if _IsTestMethod(m, test_case_class)] return [test_case_class(name, **kwargs) for name in test_names] def _GetTestsFromModule(test_module, **kwargs): """Gets a list of test objects from |test_module|. Args: test_module: Module from which to get the set of test methods. kwargs: Keyword args to pass into the constructor of test cases. Returns: A list of test case objects each initialized for a particular test method defined in |test_module|. """ tests = [] for name in dir(test_module): attr = getattr(test_module, name) if _IsTestCaseClass(attr): tests.extend(_GetTestsFromClass(attr, **kwargs)) return tests def _IsTestCaseClass(test_class): return (type(test_class) is types.TypeType and issubclass(test_class, test_case.HostDrivenTestCase) and test_class is not test_case.HostDrivenTestCase) def _IsTestMethod(attrname, test_case_class): """Checks whether this is a valid test method. Args: attrname: The method name. test_case_class: The test case class. Returns: True if test_case_class.'attrname' is callable and it starts with 'test'; False otherwise. """ attr = getattr(test_case_class, attrname) return callable(attr) and attrname.startswith('test') def _GetAllTests(test_root, is_official_build, **kwargs): """Retrieve a list of host-driven tests defined under |test_root|. Args: test_root: Path which contains host-driven test files. is_official_build: Whether this is an official build. kwargs: Keyword args to pass into the constructor of test cases. Returns: List of test case objects, one for each available test method. """ if not test_root: return [] all_tests = [] test_module_list = _GetTestModules(test_root, is_official_build) for module in test_module_list: all_tests.extend(_GetTestsFromModule(module, **kwargs)) return all_tests def InstrumentationSetup(host_driven_test_root, official_build, instrumentation_options): """Creates a list of host-driven instrumentation tests and a runner factory. Args: host_driven_test_root: Directory where the host-driven tests are. official_build: True if this is an official build. instrumentation_options: An InstrumentationOptions object. Returns: A tuple of (TestRunnerFactory, tests). """ test_collection = test_info_collection.TestInfoCollection() all_tests = _GetAllTests( host_driven_test_root, official_build, instrumentation_options=instrumentation_options) test_collection.AddTests(all_tests) available_tests = test_collection.GetAvailableTests( instrumentation_options.annotations, instrumentation_options.exclude_annotations, instrumentation_options.test_filter) logging.debug('All available tests: ' + str( [t.tagged_name for t in available_tests])) def TestRunnerFactory(device, shard_index): return test_runner.HostDrivenTestRunner( device, shard_index, instrumentation_options.tool) return (TestRunnerFactory, available_tests)
bsd-3-clause
6,065,192,468,811,680,000
30.89
79
0.711979
false
CGATOxford/CGATPipelines
CGATPipelines/pipeline_bamstats.py
1
25344
""" =========================== Pipeline bamstats =========================== :Author: Adam Cribbs :Release: $Id$ :Date: |today| :Tags: Python The intention of this pipeline is to perform QC statistics on `.bam` files that are produced following mapping of fastq files. The pipeline requires a `.bam` file as an input. Overview ======== The pipeline perform the following stats in each folder: * IdxStats -Samtools idxstats is ran and this calculates the number of mapped and unmapped reads per contig. * BamStats -This is a CGAT script (bam2stats) that performs stats on a bam file and outputs alignment statistics. * PicardStats -this runs to CollectRnaSeqMetrics picard tools. * StrandSpec -Gives a measure of the proportion of reads that map to each strand. Is used to work out strandness of library if unknown. * nreads -Calculates the number of reads in the bam file. * Paired_QC -This contains metrics that are only required for paired end. Most of the statistics collate metrics regarding splicing. Transcript profile is across the upstream,exons and downstream because this is usually specific to rna seq analysis. ### May need to remove this to make it single ended........... This pipeline computes the word frequencies in the configuration files :file:``pipeline.ini` and :file:`conf.py`. Usage ===== See :ref:`PipelineSettingUp` and :ref:`PipelineRunning` on general information how to use CGAT pipelines. Configuration ------------- This pipeline requires the user to run pipeline_gtf_subset.py. The location of the database then needs to be set in the pipeline.ini file. The pipeline requires a configured :file:`pipeline.ini` file. CGATReport report requires a :file:`conf.py` and optionally a :file:`cgatreport.ini` file (see :ref:`PipelineReporting`). Default configuration files can be generated by executing: python <srcdir>/pipeline_bamstats.py config Input files ----------- The pipeline configuration files need to be generated by running: python <srcdir>/pipeline_bamstats.py config Once the config file (pipeline.ini) is generated this should be modified before running the pipeline. The pipeline requires `.bam` files to be loacted within the same directory that the piepline is ran. Requirements ------------ The pipeline requires the gtf file produced from :doc:`pipeline_gtf_subset`. Set the configuration variable :py:data:`gtf_database`. On top of the default CGAT setup, the pipeline requires the following software to be in the path: +--------------+----------+------------------------------------+ |*Program* |*Version* |*Purpose* | +--------------+----------+------------------------------------+ |samtools |>=0.1.16 |bam/sam files | +--------------+----------+------------------------------------+ |cgat tools | |bam2stats script | +--------------+----------+------------------------------------+ |picard |>=1.42 |bam/sam files. The .jar files need | | | |to be in your CLASSPATH environment | | | |variable. | +--------------+----------+------------------------------------+ |bamstats_ |>=1.22 |from CGR, Liverpool | +--------------+----------+------------------------------------+ Pipeline output =============== The major output of the pipeline is the database file :file:`csvdb`. SQL query of this database forms the basis of the final reports. The following reports are generated as part of running: python <srcdir>/pipeline_bamstats.py make build_report * Jupyter notebook - a python implimentation. The output files are located in Jupyter_report.dir. To view the report open the _site/CGAT_FULL_BAM_STATS_REPORT.html. You can navigate throught the various report pages through here. * Rmarkdown - an R markdown report implimentation.The output report os located in the R_report.dir/_site directory and can be accessed by opening any of the html files. * multiQC - this builds a basic report using the multiqc - http://multiqc.info/ external tool. There is the potential for customising multiQC so it can be used to generate reports from CGAT tools, however at presnt this is not possible because of development stage of multiQC. Example ======= Example data is available at: ..........Add data............... python <srcdir>/pipeline_bamstats.py config python <srcdir>/pipeline_bamstats.py make full Glossary ======== .. glossary:: .. _bamstats: http://www.agf.liv.ac.uk/454/sabkea/samStats_13-01-2011 Code ==== """ # load modules for use in the pipeline import sys import os import sqlite3 import CGAT.IOTools as IOTools from ruffus import * import CGATPipelines.Pipeline as P import CGATPipelines.PipelineBamStats as PipelineBamStats # load options from the config file P.getParameters( ["%s/pipeline.ini" % os.path.splitext(__file__)[0], "../pipeline.ini", "pipeline.ini"]) PARAMS = P.PARAMS # Add parameters from the gtf_subset pipeline, but # only the interface section. All PARAMS options # will have the prefix `annotations_` PARAMS.update(P.peekParameters( PARAMS["gtf_dir"], "pipeline_genesets.py", prefix="annotations_", update_interface=True, restrict_interface=True)) # ----------------------------------------------- # Utility functions def connect(): '''utility function to connect to database. Use this method to connect to the pipeline database. Additional databases can be attached here as well. Returns an sqlite3 database handle. ''' dbh = sqlite3.connect(PARAMS["database_name"]) if not os.path.exists(PARAMS["gtf_database"]): raise ValueError( "can't find database '%s'" % PARAMS["gtf_database"]) statement = '''ATTACH DATABASE '%s' as annotations''' % \ (PARAMS["gtf_database"]) cc = dbh.cursor() cc.execute(statement) cc.close() return dbh # Determine whether the gemone is paired SPLICED_MAPPING = PARAMS["bam_paired_end"] ######################################################################### # Count reads as some QC targets require it ######################################################################### @follows(mkdir("nreads.dir")) @transform("*.bam", suffix(".bam"), r"nreads.dir/\1.nreads") def countReads(infile, outfile): '''Count number of reads in input files.''' statement = '''printf "nreads \\t" >> %(outfile)s''' P.run() statement = '''samtools view %(infile)s | wc -l | xargs printf >> %(outfile)s''' P.run() ######################################################################### # QC tasks start here ######################################################################### @follows(mkdir("StrandSpec.dir")) @transform("*.bam", suffix(".bam"), r"StrandSpec.dir/\1.strand") def strandSpecificity(infile, outfile): '''This function will determine the strand specificity of your library from the bam file''' iterations = "1000000" PipelineBamStats.getStrandSpecificity(infile, outfile, iterations) @follows(mkdir("BamFiles.dir")) @transform("*.bam", regex("(.*).bam$"), r"BamFiles.dir/\1.bam") def intBam(infile, outfile): '''make an intermediate bam file if there is no sequence infomation. If there is no sequence quality then make a softlink. Picard tools has an issue when quality score infomation is missing''' if PARAMS["bam_sequence_stripped"] is True: PipelineBamStats.addPseudoSequenceQuality(infile, outfile) else: PipelineBamStats.copyBamFile(infile, outfile) @follows(mkdir("Picard_stats.dir")) @P.add_doc(PipelineBamStats.buildPicardAlignmentStats) @transform(intBam, regex("BamFiles.dir/(.*).bam$"), add_inputs(os.path.join(PARAMS["genome_dir"], PARAMS["genome"] + ".fa")), r"Picard_stats.dir/\1.picard_stats") def buildPicardStats(infiles, outfile): ''' build Picard alignment stats ''' infile, reffile = infiles # patch for mapping against transcriptome - switch genomic reference # to transcriptomic sequences if "transcriptome.dir" in infile: reffile = "refcoding.fa" PipelineBamStats.buildPicardAlignmentStats(infile, outfile, reffile) @P.add_doc(PipelineBamStats.buildPicardDuplicationStats) @transform(intBam, regex("BamFiles.dir/(.*).bam$"), r"Picard_stats.dir/\1.picard_duplication_metrics") def buildPicardDuplicationStats(infile, outfile): '''Get duplicate stats from picard MarkDuplicates ''' PipelineBamStats.buildPicardDuplicationStats(infile, outfile) @follows(mkdir("BamStats.dir")) @follows(countReads) @transform(intBam, regex("BamFiles.dir/(.*).bam$"), add_inputs(r"nreads.dir/\1.nreads"), r"BamStats.dir/\1.readstats") def buildBAMStats(infiles, outfile): '''count number of reads mapped, duplicates, etc. Excludes regions overlapping repetitive RNA sequences Parameters ---------- infiles : list infiles[0] : str Input filename in :term:`bam` format infiles[1] : str Input filename with number of reads per sample outfile : str Output filename with read stats annotations_interface_rna_gtf : str :term:`PARMS`. :term:`gtf` format file with repetitive rna ''' rna_file = PARAMS["annotations_interface_rna_gff"] job_memory = "32G" bamfile, readsfile = infiles nreads = PipelineBamStats.getNumReadsFromReadsFile(readsfile) track = P.snip(os.path.basename(readsfile), ".nreads") # if a fastq file exists, submit for counting if os.path.exists(track + ".fastq.gz"): fastqfile = track + ".fastq.gz" elif os.path.exists(track + ".fastq.1.gz"): fastqfile = track + ".fastq.1.gz" else: fastqfile = None if fastqfile is not None: fastq_option = "--fastq-file=%s" % fastqfile else: fastq_option = "" statement = ''' cgat bam2stats %(fastq_option)s --force-output --mask-bed-file=%(rna_file)s --ignore-masked-reads --num-reads=%(nreads)i --output-filename-pattern=%(outfile)s.%%s < %(bamfile)s > %(outfile)s ''' P.run() @follows(intBam) @transform(PARAMS["annotations_interface_genomic_context_bed"], regex("^\/(.+\/)*(.+).bed.gz"), r"BamStats.dir/\2.bed.gz") def processGenomicContext(infile, outfile): ''' This module process genomic context file. It assigns each and every features of context file to a specific catagory. It helps us to understand heiarchical classification of features. ''' PipelineBamStats.defineBedFeatures(infile, outfile) @follows(processGenomicContext) @P.add_doc(PipelineBamStats.summarizeTagsWithinContext) @transform(intBam, regex("BamFiles.dir/(.*).bam$"), add_inputs(processGenomicContext), r"BamStats.dir/\1.contextstats.tsv.gz") def buildContextStats(infiles, outfile): ''' build mapping context stats ''' PipelineBamStats.summarizeTagsWithinContext( infiles[0], infiles[1], outfile) @follows(mkdir("IdxStats.dir")) @transform(intBam, regex("BamFiles.dir/(.*).bam$"), r"IdxStats.dir/\1.idxstats") def buildIdxStats(infile, outfile): '''gets idxstats for bam file so number of reads per chromosome can be plotted later''' statement = '''samtools idxstats %(infile)s > %(outfile)s''' P.run() # ------------------------------------------------------------------ # QC specific to spliced mapping # ------------------------------------------------------------------ @follows(mkdir("Paired_QC.dir")) @active_if(SPLICED_MAPPING) @transform(intBam, regex("BamFiles.dir/(.*).bam$"), add_inputs(PARAMS["annotations_interface_geneset_coding_exons_gtf"]), r"Paired_QC.dir/\1.exon.validation.tsv.gz") def buildExonValidation(infiles, outfile): '''Compare the alignments to the exon models to quantify exon overrun/underrun Expectation is that reads should not extend beyond known exons. Parameters ---------- infiles : list infiles[0] : str Input filename in :term:`bam` format infiles[1] : str Input filename in :term:`gtf` format outfile : str Output filename in :term:`gtf` format with exon validation stats ''' infile, exons = infiles statement = '''cat %(infile)s | cgat bam_vs_gtf --exons-file=%(exons)s --force-output --log=%(outfile)s.log --output-filename-pattern="%(outfile)s.%%s.gz" | gzip > %(outfile)s ''' P.run() @active_if(SPLICED_MAPPING) @transform(intBam, regex("BamFiles.dir/(.*).bam$"), add_inputs(PARAMS["annotations_interface_geneset_coding_exons_gtf"]), r"Paired_QC.dir/\1.transcript_counts.tsv.gz") def buildTranscriptLevelReadCounts(infiles, outfile): '''count reads in gene models Count the reads from a :term:`bam` file which overlap the positions of protein coding transcripts in a :term:`gtf` format transcripts file. Parameters ---------- infiles : list of str infiles[0] : str Input filename in :term:`bam` format infiles[1] : str Input filename in :term:`gtf` format outfile : str Output filename in :term:`tsv` format .. note:: In paired-end data sets each mate will be counted. Thus the actual read counts are approximately twice the fragment counts. ''' infile, geneset = infiles job_memory = "8G" statement = ''' zcat %(geneset)s | cgat gtf2table --reporter=transcripts --bam-file=%(infile)s --counter=length --column-prefix="exons_" --counter=read-counts --column-prefix="" --counter=read-coverage --column-prefix=coverage_ -v 0 | gzip > %(outfile)s ''' % locals() P.run() @active_if(SPLICED_MAPPING) @transform(intBam, regex("BamFiles.dir/(.*).bam$"), add_inputs(PARAMS["annotations_interface_geneset_intron_gtf"]), r"Paired_QC.dir/\1.intron_counts.tsv.gz") def buildIntronLevelReadCounts(infiles, outfile): '''count reads in gene models Count the reads from a :term:`bam` file which overlap the positions of introns in a :term:`gtf` format transcripts file. Parameters ---------- infiles : list of str infile :term:`str` Input filename in :term:`bam` format geneset :term:`str` Input filename in :term:`gtf` format outfile : str Output filename in :term:`tsv` format .. note:: In paired-end data sets each mate will be counted. Thus the actual read counts are approximately twice the fragment counts. ''' infile, exons = infiles job_memory = "4G" if "transcriptome.dir" in infile: P.touch(outfile) return statement = ''' zcat %(exons)s | awk -v OFS="\\t" -v FS="\\t" '{$3="exon"; print}' | cgat gtf2table --reporter=genes --bam-file=%(infile)s --counter=length --column-prefix="introns_" --counter=read-counts --column-prefix="" --counter=read-coverage --column-prefix=coverage_ | gzip > %(outfile)s ''' P.run() @active_if(SPLICED_MAPPING) @transform(intBam, regex("BamFiles.dir/(\S+).bam$"), add_inputs(PARAMS["annotations_interface_geneset_coding_exons_gtf"]), r"Paired_QC.dir/\1.transcriptprofile.gz") def buildTranscriptProfiles(infiles, outfile): '''build gene coverage profiles PolyA-RNA-Seq is expected to show a bias towards the 3' end of transcripts. Here we generate a meta-profile for each sample for the read depth from the :term:`bam` file across the gene models defined in the :term:`gtf` gene set In addition to the outfile specified by the task, plots will be saved with full and focus views of the meta-profile Parameters ---------- infiles : list of str infiles[0] : str Input filename in :term:`bam` format infiles[1] : str` Input filename in :term:`gtf` format outfile : str Output filename in :term:`tsv` format ''' bamfile, gtffile = infiles job_memory = "8G" statement = '''cgat bam2geneprofile --output-filename-pattern="%(outfile)s.%%s" --force-output --reporter=transcript --use-base-accuracy --method=geneprofileabsolutedistancefromthreeprimeend --normalize-profile=all %(bamfile)s %(gtffile)s | gzip > %(outfile)s ''' P.run() @active_if(SPLICED_MAPPING) @P.add_doc(PipelineBamStats.buildPicardRnaSeqMetrics) @transform(intBam, regex("BamFiles.dir/(.*).bam$"), add_inputs(PARAMS["annotations_interface_ref_flat"]), r"Picard_stats.dir/\1.picard_rna_metrics") def buildPicardRnaSeqMetrics(infiles, outfile): '''Get duplicate stats from picard RNASeqMetrics ''' # convert strandness to tophat-style library type if PARAMS["strandness"] == ("RF" or "R"): strand = "SECOND_READ_TRANSCRIPTION_STRAND" elif PARAMS["strandness"] == ("FR" or "F"): strand = "FIRST_READ_TRANSCRIPTION_STRAND" else: strand = "NONE" PipelineBamStats.buildPicardRnaSeqMetrics(infiles, strand, outfile) ########################################################################## # Database loading statements ########################################################################## @P.add_doc(PipelineBamStats.loadPicardAlignmentStats) @jobs_limit(PARAMS.get("jobs_limit_db", 1), "db") @merge(buildPicardStats, "Picard_stats.dir/picard_stats.load") def loadPicardStats(infiles, outfile): '''merge alignment stats into single tables.''' PipelineBamStats.loadPicardAlignmentStats(infiles, outfile) @P.add_doc(PipelineBamStats.loadPicardDuplicationStats) @jobs_limit(PARAMS.get("jobs_limit_db", 1), "db") @merge(buildPicardDuplicationStats, ["picard_duplication_stats.load", "picard_duplication_histogram.load"]) def loadPicardDuplicationStats(infiles, outfiles): '''merge alignment stats into single tables.''' PipelineBamStats.loadPicardDuplicationStats(infiles, outfiles) @P.add_doc(PipelineBamStats.loadBAMStats) @jobs_limit(PARAMS.get("jobs_limit_db", 1), "db") @merge(buildBAMStats, "bam_stats.load") def loadBAMStats(infiles, outfile): ''' load bam statistics into bam_stats table ''' PipelineBamStats.loadBAMStats(infiles, outfile) @P.add_doc(PipelineBamStats.loadSummarizedContextStats) @jobs_limit(PARAMS.get("jobs_limit_db", 1), "db") @follows(loadBAMStats) @merge(buildContextStats, "context_stats.load") def loadContextStats(infiles, outfile): ''' load context mapping statistics into context_stats table ''' PipelineBamStats.loadSummarizedContextStats(infiles, outfile) @jobs_limit(PARAMS.get("jobs_limit_db", 1), "db") @merge(buildIdxStats, "idxstats_reads_per_chromosome.load") def loadIdxStats(infiles, outfile): '''merge idxstats files into single dataframe and load to database Loads tables into the database * mapped_reads_per_chromosome Arguments --------- infiles : list list where each element is a string of the filename containing samtools idxstats output. Filename format is expected to be 'sample.idxstats' outfile : string Logfile. The table name will be derived from `outfile`.''' PipelineBamStats.loadIdxstats(infiles, outfile) @jobs_limit(PARAMS.get("jobs_limit_db", 1), "db") @active_if(SPLICED_MAPPING) @merge(buildExonValidation, "exon_validation.load") def loadExonValidation(infiles, outfile): ''' load individual and merged exon validation stats For each sample, the exon validation stats are loaded into a table named by sample and mapper [sample]_[mapper]_overrun The merge alignment stats for all samples are merged and loaded into single table called exon_validation Parameters ---------- infiles : list Input filenames with exon validation stats outfile : str Output filename ''' suffix = ".exon.validation.tsv.gz" P.mergeAndLoad(infiles, outfile, suffix=suffix) for infile in infiles: track = P.snip(infile, suffix) o = "%s_overrun.load" % track P.load(infile + ".overrun.gz", o) @P.add_doc(PipelineBamStats.loadPicardRnaSeqMetrics) @jobs_limit(PARAMS.get("jobs_limit_db", 1), "db") @merge(buildPicardRnaSeqMetrics, ["picard_rna_metrics.load", "picard_rna_histogram.load"]) def loadPicardRnaSeqMetrics(infiles, outfiles): '''merge alignment stats into single tables.''' PipelineBamStats.loadPicardRnaSeqMetrics(infiles, outfiles) @P.add_doc(PipelineBamStats.loadCountReads) @jobs_limit(PARAMS.get("jobs_limit_db", 1), "db") @follows(loadPicardRnaSeqMetrics) @merge(countReads, "count_reads.load") def loadCountReads(infiles, outfile): ''' load read counts count_reads table ''' PipelineBamStats.loadCountReads(infiles, outfile) @active_if(SPLICED_MAPPING) @P.add_doc(PipelineBamStats.loadTranscriptProfile) @jobs_limit(PARAMS.get("jobs_limit_db", 1), "db") @follows(loadCountReads) @merge(buildTranscriptProfiles, "transcript_profile.load") def loadTranscriptProfile(infiles, outfile): ''' merge transcript profiles into a single table''' PipelineBamStats.loadTranscriptProfile(infiles, outfile) @P.add_doc(PipelineBamStats.loadStrandSpecificity) @jobs_limit(PARAMS.get("jobs_limit_db", 1), "db") @follows(loadTranscriptProfile) @merge(strandSpecificity, "strand_spec.load") def loadStrandSpecificity(infiles, outfile): ''' merge strand specificity data into a single table''' PipelineBamStats.loadStrandSpecificity(infiles, outfile) # --------------------------------------------------- # Generic pipeline tasks # These tasks allow ruffus to pipeline tasks together @follows(buildTranscriptProfiles, loadPicardStats, loadPicardDuplicationStats, loadBAMStats, loadContextStats, buildIntronLevelReadCounts, loadIdxStats, loadExonValidation, loadPicardRnaSeqMetrics, loadTranscriptProfile, loadStrandSpecificity) def full(): '''a dummy task to run all tasks in the pipeline''' pass # -------------------------------------------------- # Reporting tasks # -------------------------------------------------- @follows(mkdir("R_report.dir")) def renderRreport(): '''build R markdown report ''' report_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'pipeline_docs', 'pipeline_bamstats', 'R_report')) statement = '''cp %(report_path)s/* R_report.dir ; cd R_report.dir ; R -e "rmarkdown::render_site()"''' P.run() @follows(mkdir("Jupyter_report.dir")) def renderJupyterReport(): '''build Jupyter notebook report''' report_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'pipeline_docs', 'pipeline_bamstats', 'Jupyter_report')) statement = ''' cp %(report_path)s/* Jupyter_report.dir/ ; cd Jupyter_report.dir/; jupyter nbconvert --ExecutePreprocessor.timeout=None --to html --execute *.ipynb --allow-errors; mkdir _site; mv -t _site *.html cgat_logo.jpeg oxford.png''' P.run() @follows(mkdir("MultiQC_report.dir")) @originate("MultiQC_report.dir/multiqc_report.html") def renderMultiqc(infile): '''build mulitqc report''' statement = '''LANG=en_GB.UTF-8 multiqc . -f; mv multiqc_report.html MultiQC_report.dir/''' P.run() @follows(renderRreport, renderJupyterReport, renderMultiqc) def build_report(): '''report dummy task to build reports''' pass def main(argv=None): if argv is None: argv = sys.argv P.main(argv) if __name__ == "__main__": sys.exit(P.main(sys.argv))
mit
-7,511,280,054,306,433,000
29.42497
116
0.606021
false
FlaPer87/qpid-proton
proton-c/mllib/dom.py
41
6497
# # 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. # """ Simple DOM for both SGML and XML documents. """ from __future__ import division from __future__ import generators from __future__ import nested_scopes import transforms class Container: def __init__(self): self.children = [] def add(self, child): child.parent = self self.children.append(child) def extend(self, children): for child in children: child.parent = self self.children.append(child) class Component: def __init__(self): self.parent = None def index(self): if self.parent: return self.parent.children.index(self) else: return 0 def _line(self, file, line, column): self.file = file self.line = line self.column = column class DispatchError(Exception): def __init__(self, scope, f): msg = "no such attribtue" class Dispatcher: def is_type(self, type): cls = self while cls != None: if cls.type == type: return True cls = cls.base return False def dispatch(self, f, attrs = ""): cls = self while cls != None: if hasattr(f, cls.type): return getattr(f, cls.type)(self) else: cls = cls.base cls = self while cls != None: if attrs: sep = ", " if cls.base == None: sep += "or " else: sep = "" attrs += "%s'%s'" % (sep, cls.type) cls = cls.base raise AttributeError("'%s' object has no attribute %s" % (f.__class__.__name__, attrs)) class Node(Container, Component, Dispatcher): type = "node" base = None def __init__(self): Container.__init__(self) Component.__init__(self) self.query = Query([self]) def __getitem__(self, name): for nd in self.query[name]: return nd def text(self): return self.dispatch(transforms.Text()) def tag(self, name, *attrs, **kwargs): t = Tag(name, *attrs, **kwargs) self.add(t) return t def data(self, s): d = Data(s) self.add(d) return d def entity(self, s): e = Entity(s) self.add(e) return e class Tree(Node): type = "tree" base = Node class Tag(Node): type = "tag" base = Node def __init__(self, _name, *attrs, **kwargs): Node.__init__(self) self.name = _name self.attrs = list(attrs) self.attrs.extend(kwargs.items()) self.singleton = False def get_attr(self, name): for k, v in self.attrs: if name == k: return v def _idx(self, attr): idx = 0 for k, v in self.attrs: if k == attr: return idx idx += 1 return None def set_attr(self, name, value): idx = self._idx(name) if idx is None: self.attrs.append((name, value)) else: self.attrs[idx] = (name, value) def dispatch(self, f): try: attr = "do_" + self.name method = getattr(f, attr) except AttributeError: return Dispatcher.dispatch(self, f, "'%s'" % attr) return method(self) class Leaf(Component, Dispatcher): type = "leaf" base = None def __init__(self, data): assert isinstance(data, basestring) self.data = data class Data(Leaf): type = "data" base = Leaf class Entity(Leaf): type = "entity" base = Leaf class Character(Leaf): type = "character" base = Leaf class Comment(Leaf): type = "comment" base = Leaf ################### ## Query Classes ## ########################################################################### class Adder: def __add__(self, other): return Sum(self, other) class Sum(Adder): def __init__(self, left, right): self.left = left self.right = right def __iter__(self): for x in self.left: yield x for x in self.right: yield x class View(Adder): def __init__(self, source): self.source = source class Filter(View): def __init__(self, predicate, source): View.__init__(self, source) self.predicate = predicate def __iter__(self): for nd in self.source: if self.predicate(nd): yield nd class Flatten(View): def __iter__(self): sources = [iter(self.source)] while sources: try: nd = sources[-1].next() if isinstance(nd, Tree): sources.append(iter(nd.children)) else: yield nd except StopIteration: sources.pop() class Children(View): def __iter__(self): for nd in self.source: for child in nd.children: yield child class Attributes(View): def __iter__(self): for nd in self.source: for a in nd.attrs: yield a class Values(View): def __iter__(self): for name, value in self.source: yield value def flatten_path(path): if isinstance(path, basestring): for part in path.split("/"): yield part elif callable(path): yield path else: for p in path: for fp in flatten_path(p): yield fp class Query(View): def __iter__(self): for nd in self.source: yield nd def __getitem__(self, path): query = self.source for p in flatten_path(path): if callable(p): select = Query pred = p source = query elif isinstance(p, basestring): if p[0] == "@": select = Values pred = lambda x, n=p[1:]: x[0] == n source = Attributes(query) elif p[0] == "#": select = Query pred = lambda x, t=p[1:]: x.is_type(t) source = Children(query) else: select = Query pred = lambda x, n=p: isinstance(x, Tag) and x.name == n source = Flatten(Children(query)) else: raise ValueError(p) query = select(Filter(pred, source)) return query
apache-2.0
-4,284,463,407,971,938,300
19.958065
75
0.583654
false
happyleavesaoc/home-assistant
homeassistant/components/cover/myq.py
3
2882
""" Support for MyQ-Enabled Garage Doors. For more details about this platform, please refer to the documentation https://home-assistant.io/components/cover.myq/ """ import logging import voluptuous as vol from homeassistant.components.cover import CoverDevice from homeassistant.const import ( CONF_USERNAME, CONF_PASSWORD, CONF_TYPE, STATE_CLOSED) import homeassistant.helpers.config_validation as cv import homeassistant.loader as loader REQUIREMENTS = ['pymyq==0.0.8'] _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'myq' NOTIFICATION_ID = 'myq_notification' NOTIFICATION_TITLE = 'MyQ Cover Setup' COVER_SCHEMA = vol.Schema({ vol.Required(CONF_TYPE): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string }) def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the MyQ component.""" from pymyq import MyQAPI as pymyq username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) brand = config.get(CONF_TYPE) persistent_notification = loader.get_component('persistent_notification') myq = pymyq(username, password, brand) try: if not myq.is_supported_brand(): raise ValueError("Unsupported type. See documentation") if not myq.is_login_valid(): raise ValueError("Username or Password is incorrect") add_devices(MyQDevice(myq, door) for door in myq.get_garage_doors()) return True except (TypeError, KeyError, NameError, ValueError) as ex: _LOGGER.error("%s", ex) persistent_notification.create( hass, 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(ex), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) return False class MyQDevice(CoverDevice): """Representation of a MyQ cover.""" def __init__(self, myq, device): """Initialize with API object, device id.""" self.myq = myq self.device_id = device['deviceid'] self._name = device['name'] self._status = STATE_CLOSED @property def should_poll(self): """Poll for state.""" return True @property def name(self): """Return the name of the garage door if any.""" return self._name if self._name else DEFAULT_NAME @property def is_closed(self): """Return true if cover is closed, else False.""" return self._status == STATE_CLOSED def close_cover(self): """Issue close command to cover.""" self.myq.close_device(self.device_id) def open_cover(self): """Issue open command to cover.""" self.myq.open_device(self.device_id) def update(self): """Update status of cover.""" self._status = self.myq.get_status(self.device_id)
apache-2.0
-2,589,647,039,719,210,500
28.111111
77
0.649202
false
destijl/grr
grr/lib/key_utils.py
2
3080
#!/usr/bin/env python """This file abstracts the loading of the private key.""" from cryptography import x509 from cryptography.hazmat.backends import openssl from cryptography.hazmat.primitives import hashes from cryptography.x509 import oid from grr.lib import rdfvalue from grr.lib.rdfvalues import crypto as rdf_crypto def MakeCASignedCert(common_name, private_key, ca_cert, ca_private_key, serial_number=2): """Make a cert and sign it with the CA's private key.""" public_key = private_key.GetPublicKey() builder = x509.CertificateBuilder() builder = builder.issuer_name(ca_cert.GetIssuer()) subject = x509.Name( [x509.NameAttribute(oid.NameOID.COMMON_NAME, common_name)]) builder = builder.subject_name(subject) valid_from = rdfvalue.RDFDatetime.Now() - rdfvalue.Duration("1d") valid_until = rdfvalue.RDFDatetime.Now() + rdfvalue.Duration("3650d") builder = builder.not_valid_before(valid_from.AsDatetime()) builder = builder.not_valid_after(valid_until.AsDatetime()) builder = builder.serial_number(serial_number) builder = builder.public_key(public_key.GetRawPublicKey()) builder = builder.add_extension( x509.BasicConstraints( ca=False, path_length=None), critical=True) certificate = builder.sign( private_key=ca_private_key.GetRawPrivateKey(), algorithm=hashes.SHA256(), backend=openssl.backend) return rdf_crypto.RDFX509Cert(certificate) def MakeCACert(private_key, common_name=u"grr", issuer_cn=u"grr_test", issuer_c=u"US"): """Generate a CA certificate. Args: private_key: The private key to use. common_name: Name for cert. issuer_cn: Name for issuer. issuer_c: Country for issuer. Returns: The certificate. """ public_key = private_key.GetPublicKey() builder = x509.CertificateBuilder() issuer = x509.Name([ x509.NameAttribute(oid.NameOID.COMMON_NAME, issuer_cn), x509.NameAttribute(oid.NameOID.COUNTRY_NAME, issuer_c) ]) subject = x509.Name( [x509.NameAttribute(oid.NameOID.COMMON_NAME, common_name)]) builder = builder.subject_name(subject) builder = builder.issuer_name(issuer) valid_from = rdfvalue.RDFDatetime.Now() - rdfvalue.Duration("1d") valid_until = rdfvalue.RDFDatetime.Now() + rdfvalue.Duration("3650d") builder = builder.not_valid_before(valid_from.AsDatetime()) builder = builder.not_valid_after(valid_until.AsDatetime()) builder = builder.serial_number(1) builder = builder.public_key(public_key.GetRawPublicKey()) builder = builder.add_extension( x509.BasicConstraints( ca=True, path_length=None), critical=True) builder = builder.add_extension( x509.SubjectKeyIdentifier.from_public_key(public_key.GetRawPublicKey()), critical=False) certificate = builder.sign( private_key=private_key.GetRawPrivateKey(), algorithm=hashes.SHA256(), backend=openssl.backend) return rdf_crypto.RDFX509Cert(certificate)
apache-2.0
-7,206,638,405,950,660,000
31.765957
78
0.69513
false
bbrezillon/linux-sunxi
scripts/gdb/linux/symbols.py
68
6310
# # gdb helper commands and functions for Linux kernel debugging # # load kernel and module symbols # # Copyright (c) Siemens AG, 2011-2013 # # Authors: # Jan Kiszka <jan.kiszka@siemens.com> # # This work is licensed under the terms of the GNU GPL version 2. # import gdb import os import re from linux import modules if hasattr(gdb, 'Breakpoint'): class LoadModuleBreakpoint(gdb.Breakpoint): def __init__(self, spec, gdb_command): super(LoadModuleBreakpoint, self).__init__(spec, internal=True) self.silent = True self.gdb_command = gdb_command def stop(self): module = gdb.parse_and_eval("mod") module_name = module['name'].string() cmd = self.gdb_command # enforce update if object file is not found cmd.module_files_updated = False # Disable pagination while reporting symbol (re-)loading. # The console input is blocked in this context so that we would # get stuck waiting for the user to acknowledge paged output. show_pagination = gdb.execute("show pagination", to_string=True) pagination = show_pagination.endswith("on.\n") gdb.execute("set pagination off") if module_name in cmd.loaded_modules: gdb.write("refreshing all symbols to reload module " "'{0}'\n".format(module_name)) cmd.load_all_symbols() else: cmd.load_module_symbols(module) # restore pagination state gdb.execute("set pagination %s" % ("on" if pagination else "off")) return False class LxSymbols(gdb.Command): """(Re-)load symbols of Linux kernel and currently loaded modules. The kernel (vmlinux) is taken from the current working directly. Modules (.ko) are scanned recursively, starting in the same directory. Optionally, the module search path can be extended by a space separated list of paths passed to the lx-symbols command.""" module_paths = [] module_files = [] module_files_updated = False loaded_modules = [] breakpoint = None def __init__(self): super(LxSymbols, self).__init__("lx-symbols", gdb.COMMAND_FILES, gdb.COMPLETE_FILENAME) def _update_module_files(self): self.module_files = [] for path in self.module_paths: gdb.write("scanning for modules in {0}\n".format(path)) for root, dirs, files in os.walk(path): for name in files: if name.endswith(".ko"): self.module_files.append(root + "/" + name) self.module_files_updated = True def _get_module_file(self, module_name): module_pattern = ".*/{0}\.ko$".format( module_name.replace("_", r"[_\-]")) for name in self.module_files: if re.match(module_pattern, name) and os.path.exists(name): return name return None def _section_arguments(self, module): try: sect_attrs = module['sect_attrs'].dereference() except gdb.error: return "" attrs = sect_attrs['attrs'] section_name_to_address = { attrs[n]['name'].string(): attrs[n]['address'] for n in range(int(sect_attrs['nsections']))} args = [] for section_name in [".data", ".data..read_mostly", ".rodata", ".bss"]: address = section_name_to_address.get(section_name) if address: args.append(" -s {name} {addr}".format( name=section_name, addr=str(address))) return "".join(args) def load_module_symbols(self, module): module_name = module['name'].string() module_addr = str(module['core_layout']['base']).split()[0] module_file = self._get_module_file(module_name) if not module_file and not self.module_files_updated: self._update_module_files() module_file = self._get_module_file(module_name) if module_file: gdb.write("loading @{addr}: {filename}\n".format( addr=module_addr, filename=module_file)) cmdline = "add-symbol-file {filename} {addr}{sections}".format( filename=module_file, addr=module_addr, sections=self._section_arguments(module)) gdb.execute(cmdline, to_string=True) if module_name not in self.loaded_modules: self.loaded_modules.append(module_name) else: gdb.write("no module object found for '{0}'\n".format(module_name)) def load_all_symbols(self): gdb.write("loading vmlinux\n") # Dropping symbols will disable all breakpoints. So save their states # and restore them afterward. saved_states = [] if hasattr(gdb, 'breakpoints') and not gdb.breakpoints() is None: for bp in gdb.breakpoints(): saved_states.append({'breakpoint': bp, 'enabled': bp.enabled}) # drop all current symbols and reload vmlinux gdb.execute("symbol-file", to_string=True) gdb.execute("symbol-file vmlinux") self.loaded_modules = [] module_list = modules.module_list() if not module_list: gdb.write("no modules found\n") else: [self.load_module_symbols(module) for module in module_list] for saved_state in saved_states: saved_state['breakpoint'].enabled = saved_state['enabled'] def invoke(self, arg, from_tty): self.module_paths = arg.split() self.module_paths.append(os.getcwd()) # enforce update self.module_files = [] self.module_files_updated = False self.load_all_symbols() if hasattr(gdb, 'Breakpoint'): if self.breakpoint is not None: self.breakpoint.delete() self.breakpoint = None self.breakpoint = LoadModuleBreakpoint( "kernel/module.c:do_init_module", self) else: gdb.write("Note: symbol update on module loading not supported " "with this gdb version\n") LxSymbols()
gpl-2.0
-3,705,187,531,682,248,700
34.852273
79
0.58225
false
ataylor32/django
django/conf/locale/ml/formats.py
1007
1815
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'N j, Y' TIME_FORMAT = 'P' DATETIME_FORMAT = 'N j, Y, P' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'F j' SHORT_DATE_FORMAT = 'm/d/Y' SHORT_DATETIME_FORMAT = 'm/d/Y P' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = [ '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ] DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
bsd-3-clause
7,955,592,753,861,353,000
41.209302
81
0.516253
false
dharmabumstead/ansible
lib/ansible/plugins/action/command.py
117
1121
# Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible import constants as C from ansible.plugins.action import ActionBase from ansible.utils.vars import merge_hash class ActionModule(ActionBase): def run(self, tmp=None, task_vars=None): self._supports_async = True results = super(ActionModule, self).run(tmp, task_vars) del tmp # tmp no longer has any effect # Command module has a special config option to turn off the command nanny warnings if 'warn' not in self._task.args: self._task.args['warn'] = C.COMMAND_WARNINGS wrap_async = self._task.async_val and not self._connection.has_native_async results = merge_hash(results, self._execute_module(task_vars=task_vars, wrap_async=wrap_async)) if not wrap_async: # remove a temporary path we created self._remove_tmp_path(self._connection._shell.tmpdir) return results
gpl-3.0
6,676,477,658,934,152,000
36.366667
103
0.683318
false
TESScience/httm
httm/transformations/metadata.py
1
5125
# HTTM: A transformation library for RAW and Electron Flux TESS Images # Copyright (C) 2016, 2017 John Doty and Matthew Wampler-Doty of Noqsi Aerospace, 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/>. """ ``httm.transformations.metadata`` ================================= This module contains metadata related to transformation functions. - ``electron_flux_transformations`` is metadata describing transformation functions from images in electron counts to simulated raw images in *Analogue to Digital Converter Units* (ADU). - ``raw_transformations`` is metadata describing transformation functions from raw images in *Analogue to Digital Converter Units* (ADU) to calibrated images in electron counts. """ from collections import OrderedDict from .raw_converters_to_calibrated import remove_pattern_noise, convert_adu_to_electrons, remove_baseline, \ remove_start_of_line_ringing, remove_undershoot, remove_smear from .electron_flux_converters_to_raw import introduce_smear_rows, add_shot_noise, simulate_blooming, \ add_readout_noise, simulate_undershoot, simulate_start_of_line_ringing, add_baseline, convert_electrons_to_adu, \ add_pattern_noise electron_flux_transformations = OrderedDict([ ('introduce_smear_rows', { 'default': True, 'documentation': 'Introduce *smear rows* to each slice of the image.', 'function': introduce_smear_rows, }), ('add_shot_noise', { 'default': True, 'documentation': 'Add *shot noise* to each pixel in each slice of the image.', 'function': add_shot_noise, }), ('simulate_blooming', { 'default': True, 'documentation': 'Simulate *blooming* on for each column for each slice of the image.', 'function': simulate_blooming, }), ('add_readout_noise', { 'default': True, 'documentation': 'Add *readout noise* to each pixel in each slice of the image.', 'function': add_readout_noise, }), ('simulate_undershoot', { 'default': True, 'documentation': 'Simulate *undershoot* on each row of each slice in the image.', 'function': simulate_undershoot, }), ('simulate_start_of_line_ringing', { 'default': True, 'documentation': 'Simulate *start of line ringing* on each row of each slice in the image.', 'function': simulate_start_of_line_ringing, }), ('add_baseline', { 'default': True, 'documentation': 'Add a *baseline electron count* to each slice in the image.', 'function': add_baseline, }), ('convert_electrons_to_adu', { 'default': True, 'documentation': 'Convert the image from having pixel units in electron counts to ' '*Analogue to Digital Converter Units* (ADU).', 'function': convert_electrons_to_adu, }), ('add_pattern_noise', { 'default': True, 'documentation': 'Add a fixed *pattern noise* to each slice in the image.', 'function': add_pattern_noise, }), ]) raw_transformations = OrderedDict([ ('remove_pattern_noise', { 'default': True, 'documentation': 'Compensate for a fixed *pattern noise* on each slice of the image.', 'function': remove_pattern_noise, }), ('convert_adu_to_electrons', { 'default': True, 'documentation': 'Convert the image from having units in ' '*Analogue to Digital Converter Units* (ADU) ' 'to electron counts.', 'function': convert_adu_to_electrons, }), ('remove_baseline', { 'default': True, 'documentation': 'Average the pixels in the dark columns and subtract ' 'the result from each pixel in the image.', 'function': remove_baseline, }), ('remove_start_of_line_ringing', { 'default': True, 'documentation': 'Compensate for *start of line ringing* on each row of each slice of the image.', 'function': remove_start_of_line_ringing, }), ('remove_undershoot', { 'default': True, 'documentation': 'Compensate for *undershoot* for each row of each slice of the image.', 'function': remove_undershoot, }), ('remove_smear', { 'default': True, 'documentation': 'Compensate for *smear* in the image by reading it from the ' '*smear rows* each slice and removing it from the rest of the slice.', 'function': remove_smear, }), ])
gpl-3.0
368,438,116,170,356,100
41.008197
117
0.642537
false
aguedes/bluez
test/sap_client.py
86
30639
""" Copyright (C) 2010-2011 ST-Ericsson SA """ """ Author: Szymon Janc <szymon.janc@tieto.com> for ST-Ericsson. """ """ This program is free software; you can redistribute it and/or modify """ """ it under the terms of the GNU General Public License as published by """ """ the Free Software Foundation; either version 2 of the License, or """ """ (at your option) any later version. """ """ This program is distributed in the hope that it will be useful, """ """ but WITHOUT ANY WARRANTY; without even the implied warranty of """ """ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the """ """ GNU General Public License for more details. """ """ You should have received a copy of the GNU General Public License """ """ along with this program; if not, write to the Free Software """ """ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from array import array from bluetooth import * import time import re class SAPParam: """ SAP Parameter Class """ MaxMsgSize = 0x00 ConnectionStatus = 0x01 ResultCode = 0x02 DisconnectionType = 0x03 CommandAPDU = 0x04 ResponseAPDU = 0x05 ATR = 0x06 CardReaderStatus = 0x07 StatusChange = 0x08 TransportProtocol = 0x09 CommandAPDU7816 = 0x10 def __init__(self, name, id, value = None): self.name = name self.id = id self.value = value def _padding(self, buf): pad = array('B') while ( (len(buf) + len(pad)) % 4 ) != 0: pad.append(0) return pad def _basicCheck(self, buf): if len(buf) < 4 or (len(buf) % 4) != 0 or buf[1] != 0: return (-1, -1) if buf[0] != self.id: return (-1, -1) plen = buf[2] * 256 + buf[3] + 4 if plen > len(buf): return (-1, -1) pad = plen while (pad % 4) != 0: if buf[pad] != 0: return (-1, -1) pad+=1 return (plen, pad) def getID(self): return self.id def getValue(self): return self.value def getContent(self): return "%s(id=0x%.2X), value=%s \n" % (self.name, self.id, self.value) def serialize(self): a = array('B', '\00\00\00\00') a[0] = self.id a[1] = 0 # reserved a[2] = 0 # length a[3] = 1 # length a.append(self.value) a.extend(self._padding(a)) return a def deserialize(self, buf): p = self._basicCheck(buf) if p[0] == -1: return -1 self.id = buf[0] self.value = buf[4] return p[1] class SAPParam_MaxMsgSize(SAPParam): """MaxMsgSize Param """ def __init__(self, value = None): SAPParam.__init__(self,"MaxMsgSize", SAPParam.MaxMsgSize, value) self.__validate() def __validate(self): if self.value > 0xFFFF: self.value = 0xFFFF def serialize(self): a = array('B', '\00\00\00\00') a[0] = self.id a[3] = 2 a.append(self.value / 256) a.append(self.value % 256) a.extend(self._padding(a)) return a def deserialize(self, buf): p = self._basicCheck(buf) if p[0] == -1 : return -1 self.value = buf[4] * 256 + buf[5] return p[1] class SAPParam_CommandAPDU(SAPParam): def __init__(self, value = None): if value is None: SAPParam.__init__(self, "CommandAPDU", SAPParam.CommandAPDU, array('B')) else: SAPParam.__init__(self, "CommandAPDU", SAPParam.CommandAPDU, array('B', value)) def serialize(self): a = array('B', '\00\00\00\00') a[0] = self.id plen = len(self.value) a[2] = plen / 256 a[3] = plen % 256 a.extend(self.value) a.extend(self._padding(a)) return a def deserialize(self, buf): p = self._basicCheck(buf) if p[0] == -1: return -1 self.value = buf[4:p[0]] return p[1] class SAPParam_ResponseAPDU(SAPParam_CommandAPDU): """ResponseAPDU Param """ def __init__(self, value = None): if value is None: SAPParam.__init__(self, "ResponseAPDU", SAPParam.ResponseAPDU, array('B')) else: SAPParam.__init__(self, "ResponseAPDU", SAPParam.ResponseAPDU, array('B', value)) class SAPParam_ATR(SAPParam_CommandAPDU): """ATR Param """ def __init__(self, value = None): if value is None: SAPParam.__init__(self, "ATR", SAPParam.ATR, array('B')) else: SAPParam.__init__(self, "ATR", SAPParam.ATR, array('B', value)) class SAPParam_CommandAPDU7816(SAPParam_CommandAPDU): """Command APDU7816 Param.""" def __init__(self, value = None): if value is None: SAPParam.__init__(self, "CommandAPDU7816", SAPParam.CommandAPDU7816, array('B')) else: SAPParam.__init__(self, "CommandAPDU7816", SAPParam.CommandAPDU7816, array('B', value)) class SAPParam_ConnectionStatus(SAPParam): """Connection status Param.""" def __init__(self, value = None): SAPParam.__init__(self,"ConnectionStatus", SAPParam.ConnectionStatus, value) self.__validate() def __validate(self): if self.value is not None and self.value not in (0x00, 0x01, 0x02, 0x03, 0x04): print "Warning. ConnectionStatus value in reserved range (0x%x)" % self.value def deserialize(self, buf): ret = SAPParam.deserialize(self, buf) if ret == -1: return -1 self.__validate() return ret class SAPParam_ResultCode(SAPParam): """ Result Code Param """ def __init__(self, value = None): SAPParam.__init__(self,"ResultCode", SAPParam.ResultCode, value) self.__validate() def __validate(self): if self.value is not None and self.value not in (0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07): print "Warning. ResultCode value in reserved range (0x%x)" % self.value def deserialize(self, buf): ret = SAPParam.deserialize(self, buf) if ret == -1: return -1 self.__validate() return ret class SAPParam_DisconnectionType(SAPParam): """Disconnection Type Param.""" def __init__(self, value = None): SAPParam.__init__(self,"DisconnectionType", SAPParam.DisconnectionType, value) self.__validate() def __validate(self): if self.value is not None and self.value not in (0x00, 0x01): print "Warning. DisconnectionType value in reserved range (0x%x)" % self.value def deserialize(self, buf): ret = SAPParam.deserialize(self, buf) if ret == -1: return -1 self.__validate() return ret class SAPParam_CardReaderStatus(SAPParam_CommandAPDU): """Card reader Status Param.""" def __init__(self, value = None): if value is None: SAPParam.__init__(self, "CardReaderStatus", SAPParam.CardReaderStatus, array('B')) else: SAPParam.__init__(self, "CardReaderStatus", SAPParam.CardReaderStatus, array('B', value)) class SAPParam_StatusChange(SAPParam): """Status Change Param """ def __init__(self, value = None): SAPParam.__init__(self,"StatusChange", SAPParam.StatusChange, value) def __validate(self): if self.value is not None and self.value not in (0x00, 0x01, 0x02, 0x03, 0x04, 0x05): print "Warning. StatusChange value in reserved range (0x%x)" % self.value def deserialize(self, buf): ret = SAPParam.deserialize(self, buf) if ret == -1: return -1 self.__validate() return ret class SAPParam_TransportProtocol(SAPParam): """Transport Protocol Param """ def __init__(self, value = None): SAPParam.__init__(self,"TransportProtocol", SAPParam.TransportProtocol, value) self.__validate() def __validate(self): if self.value is not None and self.value not in (0x00, 0x01): print "Warning. TransportProtoco value in reserved range (0x%x)" % self.value def deserialize(self, buf): ret = SAPParam.deserialize(self, buf) if ret == -1: return -1 self.__validate() return ret class SAPMessage: CONNECT_REQ = 0x00 CONNECT_RESP = 0x01 DISCONNECT_REQ = 0x02 DISCONNECT_RESP =0x03 DISCONNECT_IND = 0x04 TRANSFER_APDU_REQ = 0x05 TRANSFER_APDU_RESP = 0x06 TRANSFER_ATR_REQ = 0x07 TRANSFER_ATR_RESP = 0x08 POWER_SIM_OFF_REQ = 0x09 POWER_SIM_OFF_RESP = 0x0A POWER_SIM_ON_REQ = 0x0B POWER_SIM_ON_RESP = 0x0C RESET_SIM_REQ = 0x0D RESET_SIM_RESP = 0x0E TRANSFER_CARD_READER_STATUS_REQ = 0x0F TRANSFER_CARD_READER_STATUS_RESP = 0x10 STATUS_IND = 0x11 ERROR_RESP = 0x12 SET_TRANSPORT_PROTOCOL_REQ = 0x13 SET_TRANSPORT_PROTOCOL_RESP = 0x14 def __init__(self, name, id): self.name = name self.id = id self.params = [] self.buf = array('B') def _basicCheck(self, buf): if len(buf) < 4 or (len(buf) % 4) != 0 : return False if buf[0] != self.id: return False return True def getID(self): return self.id def getContent(self): s = "%s(id=0x%.2X) " % (self.name, self.id) if len( self.buf): s = s + "[%s]" % re.sub("(.{2})", "0x\\1 " , self.buf.tostring().encode("hex").upper(), re.DOTALL) s = s + "\n\t" for p in self.params: s = s + "\t" + p.getContent() return s def getParams(self): return self.params def addParam(self, param): self.params.append(param) def serialize(self): ret = array('B', '\00\00\00\00') ret[0] = self.id ret[1] = len(self.params) ret[2] = 0 # reserved ret[3] = 0 # reserved for p in self.params: ret.extend(p.serialize()) self.buf = ret return ret def deserialize(self, buf): self.buf = buf return len(buf) == 4 and buf[1] == 0 and self._basicCheck(buf) class SAPMessage_CONNECT_REQ(SAPMessage): def __init__(self, MaxMsgSize = None): SAPMessage.__init__(self,"CONNECT_REQ", SAPMessage.CONNECT_REQ) if MaxMsgSize is not None: self.addParam(SAPParam_MaxMsgSize(MaxMsgSize)) def _validate(self): if len(self.params) == 1: if self.params[0].getID() == SAPParam.MaxMsgSize: return True return False def deserialize(self, buf): self.buf = buf self.params[:] = [] if SAPMessage._basicCheck(self, buf): p = SAPParam_MaxMsgSize() if p.deserialize(buf[4:]) == len(buf[4:]): self.addParam(p) return self._validate() return False class SAPMessage_CONNECT_RESP(SAPMessage): def __init__(self, ConnectionStatus = None, MaxMsgSize = None): SAPMessage.__init__(self,"CONNECT_RESP", SAPMessage.CONNECT_RESP) if ConnectionStatus is not None: self.addParam(SAPParam_ConnectionStatus(ConnectionStatus)) if MaxMsgSize is not None: self.addParam(SAPParam_MaxMsgSize(MaxMsgSize)) def _validate(self): if len(self.params) > 0: if self.params[0] .getID() == SAPParam.ConnectionStatus: if self.params[0].getValue() == 0x02: if len(self.params) == 2: return True else: if len(self.params) == 1: return True return False def deserialize(self, buf): self.buf = buf self.params[:] = [] if SAPMessage._basicCheck(self, buf): p = SAPParam_ConnectionStatus() r = p.deserialize(buf[4:]) if r != -1: self.addParam(p) if buf[1] == 2: p = SAPParam_MaxMsgSize() r = p.deserialize(buf[4+r:]) if r != -1: self.addParam(p) return self._validate() return False class SAPMessage_DISCONNECT_REQ(SAPMessage): def __init__(self): SAPMessage.__init__(self,"DISCONNECT_REQ", SAPMessage.DISCONNECT_REQ) class SAPMessage_DISCONNECT_RESP(SAPMessage): def __init__(self): SAPMessage.__init__(self,"DISCONNECT_RESP", SAPMessage.DISCONNECT_RESP) class SAPMessage_DISCONNECT_IND(SAPMessage): def __init__(self, Type = None): SAPMessage.__init__(self,"DISCONNECT_IND", SAPMessage.DISCONNECT_IND) if Type is not None: self.addParam(SAPParam_DisconnectionType(Type)) def _validate(self): if len(self.params) == 1: if self.params[0].getID() == SAPParam.DisconnectionType: return True return False def deserialize(self, buf): self.buf = buf self.params[:] = [] if SAPMessage._basicCheck(self, buf): p = SAPParam_DisconnectionType() if p.deserialize(buf[4:]) == len(buf[4:]): self.addParam(p) return self._validate() return False class SAPMessage_TRANSFER_APDU_REQ(SAPMessage): def __init__(self, APDU = None, T = False): SAPMessage.__init__(self,"TRANSFER_APDU_REQ", SAPMessage.TRANSFER_APDU_REQ) if APDU is not None: if T : self.addParam(SAPParam_CommandAPDU(APDU)) else: self.addParam(SAPParam_CommandAPDU7816(APDU)) def _validate(self): if len(self.params) == 1: if self.params[0].getID() == SAPParam.CommandAPDU or self.params[0].getID() == SAPParam.CommandAPDU7816: return True return False def deserialize(self, buf): self.buf = buf self.params[:] = [] if SAPMessage._basicCheck(self, buf): p = SAPParam_CommandAPDU() p2 = SAPParam_CommandAPDU7816() if p.deserialize(buf[4:]) == len(buf[4:]): self.addParam(p) return self._validate() elif p2.deserialize(buf[4:]) == len(buf[4:]): self.addParam(p2) return self._validate() return False class SAPMessage_TRANSFER_APDU_RESP(SAPMessage): def __init__(self, ResultCode = None, Response = None): SAPMessage.__init__(self,"TRANSFER_APDU_RESP", SAPMessage.TRANSFER_APDU_RESP) if ResultCode is not None: self.addParam(SAPParam_ResultCode(ResultCode)) if Response is not None: self.addParam(SAPParam_ResponseAPDU(Response)) def _validate(self): if len(self.params) > 0: if self.params[0] .getID() == SAPParam.ResultCode: if self.params[0].getValue() == 0x00: if len(self.params) == 2: return True else: if len(self.params) == 1: return True return False def deserialize(self, buf): self.buf = buf self.params[:] = [] if SAPMessage._basicCheck(self, buf): p = SAPParam_ResultCode() r = p.deserialize(buf[4:]) if r != -1: self.addParam(p) if buf[1] == 2: p = SAPParam_ResponseAPDU() r = p.deserialize(buf[4+r:]) if r != -1: self.addParam(p) return self._validate() return False class SAPMessage_TRANSFER_ATR_REQ(SAPMessage): def __init__(self): SAPMessage.__init__(self,"TRANSFER_ATR_REQ", SAPMessage.TRANSFER_ATR_REQ) class SAPMessage_TRANSFER_ATR_RESP(SAPMessage): def __init__(self, ResultCode = None, ATR = None): SAPMessage.__init__(self,"TRANSFER_ATR_RESP", SAPMessage.TRANSFER_ATR_RESP) if ResultCode is not None: self.addParam(SAPParam_ResultCode(ResultCode)) if ATR is not None: self.addParam(SAPParam_ATR(ATR)) def _validate(self): if len(self.params) > 0: if self.params[0] .getID() == SAPParam.ResultCode: if self.params[0].getValue() == 0x00: if len(self.params) == 2: return True else: if len(self.params) == 1: return True return False def deserialize(self, buf): self.buf = buf self.params[:] = [] if SAPMessage._basicCheck(self, buf): p = SAPParam_ResultCode() r = p.deserialize(buf[4:]) if r != -1: self.addParam(p) if buf[1] == 2: p = SAPParam_ATR() r = p.deserialize(buf[4+r:]) if r != -1: self.addParam(p) return self._validate() return False class SAPMessage_POWER_SIM_OFF_REQ(SAPMessage): def __init__(self): SAPMessage.__init__(self,"POWER_SIM_OFF_REQ", SAPMessage.POWER_SIM_OFF_REQ) class SAPMessage_POWER_SIM_OFF_RESP(SAPMessage): def __init__(self, ResultCode = None): SAPMessage.__init__(self,"POWER_SIM_OFF_RESP", SAPMessage.POWER_SIM_OFF_RESP) if ResultCode is not None: self.addParam(SAPParam_ResultCode(ResultCode)) def _validate(self): if len(self.params) == 1: if self.params[0].getID() == SAPParam.ResultCode: return True return False def deserialize(self, buf): self.buf = buf self.params[:] = [] if SAPMessage._basicCheck(self, buf): p = SAPParam_ResultCode() if p.deserialize(buf[4:]) == len(buf[4:]): self.addParam(p) return self._validate() return False class SAPMessage_POWER_SIM_ON_REQ(SAPMessage): def __init__(self): SAPMessage.__init__(self,"POWER_SIM_ON_REQ", SAPMessage.POWER_SIM_ON_REQ) class SAPMessage_POWER_SIM_ON_RESP(SAPMessage_POWER_SIM_OFF_RESP): def __init__(self, ResultCode = None): SAPMessage.__init__(self,"POWER_SIM_ON_RESP", SAPMessage.POWER_SIM_ON_RESP) if ResultCode is not None: self.addParam(SAPParam_ResultCode(ResultCode)) class SAPMessage_RESET_SIM_REQ(SAPMessage): def __init__(self): SAPMessage.__init__(self,"RESET_SIM_REQ", SAPMessage.RESET_SIM_REQ) class SAPMessage_RESET_SIM_RESP(SAPMessage_POWER_SIM_OFF_RESP): def __init__(self, ResultCode = None): SAPMessage.__init__(self,"RESET_SIM_RESP", SAPMessage.RESET_SIM_RESP) if ResultCode is not None: self.addParam(SAPParam_ResultCode(ResultCode)) class SAPMessage_STATUS_IND(SAPMessage): def __init__(self, StatusChange = None): SAPMessage.__init__(self,"STATUS_IND", SAPMessage.STATUS_IND) if StatusChange is not None: self.addParam(SAPParam_StatusChange(StatusChange)) def _validate(self): if len(self.params) == 1: if self.params[0].getID() == SAPParam.StatusChange: return True return False def deserialize(self, buf): self.buf = buf self.params[:] = [] if SAPMessage._basicCheck(self, buf): p = SAPParam_StatusChange() if p.deserialize(buf[4:]) == len(buf[4:]): self.addParam(p) return self._validate() return False class SAPMessage_TRANSFER_CARD_READER_STATUS_REQ(SAPMessage): def __init__(self): SAPMessage.__init__(self,"TRANSFER_CARD_READER_STATUS_REQ", SAPMessage.TRANSFER_CARD_READER_STATUS_REQ) class SAPMessage_TRANSFER_CARD_READER_STATUS_RESP(SAPMessage): def __init__(self, ResultCode = None, Status = None): SAPMessage.__init__(self,"TRANSFER_CARD_READER_STATUS_RESP", SAPMessage.TRANSFER_CARD_READER_STATUS_RESP) if ResultCode is not None: self.addParam(SAPParam_ResultCode(ResultCode)) if Status is not None: self.addParam(SAPParam_CardReaderStatus(Status)) def _validate(self): if len(self.params) > 0: if self.params[0] .getID() == SAPParam.ResultCode: if self.params[0].getValue() == 0x00: if len(self.params) == 2: return True else: if len(self.params) == 1: return True return False def deserialize(self, buf): self.buf = buf self.params[:] = [] if SAPMessage._basicCheck(self, buf): p = SAPParam_ResultCode() r = p.deserialize(buf[4:]) if r != -1: self.addParam(p) if buf[1] == 2: p = SAPParam_CardReaderStatus() r = p.deserialize(buf[4+r:]) if r != -1: self.addParam(p) return self._validate() return False class SAPMessage_ERROR_RESP(SAPMessage): def __init__(self): SAPMessage.__init__(self,"ERROR_RESP", SAPMessage.ERROR_RESP) class SAPMessage_SET_TRANSPORT_PROTOCOL_REQ(SAPMessage): def __init__(self, protocol = None): SAPMessage.__init__(self,"SET_TRANSPORT_PROTOCOL_REQ", SAPMessage.SET_TRANSPORT_PROTOCOL_REQ) if protocol is not None: self.addParam(SAPParam_TransportProtocol(protocol)) def _validate(self): if len(self.params) == 1: if self.params[0].getID() == SAPParam.TransportProtocol: return True return False def deserialize(self, buf): self.buf = buf self.params[:] = [] if SAPMessage._basicCheck(self, buf): p = SAPParam_TransportProtocol() if p.deserialize(buf[4:]) == len(buf[4:]): self.addParam(p) return self._validate() return False class SAPMessage_SET_TRANSPORT_PROTOCOL_RESP(SAPMessage_POWER_SIM_OFF_RESP): def __init__(self, ResultCode = None): SAPMessage.__init__(self,"SET_TRANSPORT_PROTOCOL_RESP", SAPMessage.SET_TRANSPORT_PROTOCOL_RESP) if ResultCode is not None: self.addParam(SAPParam_ResultCode(ResultCode)) class SAPClient: CONNECTED = 1 DISCONNECTED = 0 uuid = "0000112D-0000-1000-8000-00805F9B34FB" bufsize = 1024 timeout = 20 state = DISCONNECTED def __init__(self, host = None, port = None): self.sock = None if host is None or is_valid_address(host): self.host = host else: raise BluetoothError ("%s is not a valid BT address." % host) self.host = None return if port is None: self.__discover() else: self.port = port self.__connectRFCOMM() def __del__(self): self.__disconnectRFCOMM() def __disconnectRFCOMM(self): if self.sock is not None: self.sock.close() self.state = self.DISCONNECTED def __discover(self): service_matches = find_service(self.uuid, self.host) if len(service_matches) == 0: raise BluetoothError ("No SAP service found") return first_match = service_matches[0] self.port = first_match["port"] self.host = first_match["host"] print "SAP Service found on %s(%s)" % first_match["name"] % self.host def __connectRFCOMM(self): self.sock=BluetoothSocket( RFCOMM ) self.sock.connect((self.host, self.port)) self.sock.settimeout(self.timeout) self.state = self.CONNECTED def __sendMsg(self, msg): if isinstance(msg, SAPMessage): s = msg.serialize() print "\tTX: " + msg.getContent() return self.sock.send(s.tostring()) def __rcvMsg(self, msg): if isinstance(msg, SAPMessage): print "\tRX Wait: %s(id = 0x%.2x)" % (msg.name, msg.id) data = self.sock.recv(self.bufsize) if data: if msg.deserialize(array('B',data)): print "\tRX: len(%d) %s" % (len(data), msg.getContent()) return msg else: print "msg: %s" % array('B',data) raise BluetoothError ("Message deserialization failed.") else: raise BluetoothError ("Timeout. No data received.") def connect(self): self.__connectRFCOMM() def disconnect(self): self.__disconnectRFCOMM() def isConnected(self): return self.state def proc_connect(self): try: self.__sendMsg(SAPMessage_CONNECT_REQ(self.bufsize)) params = self.__rcvMsg(SAPMessage_CONNECT_RESP()).getParams() if params[0].getValue() in (0x00, 0x04): pass elif params[0].getValue() == 0x02: self.bufsize = params[1].getValue() self.__sendMsg(SAPMessage_CONNECT_REQ(self.bufsize)) params = self.__rcvMsg(SAPMessage_CONNECT_RESP()).getParams() if params[0].getValue() not in (0x00, 0x04): return False else: return False params = self.__rcvMsg(SAPMessage_STATUS_IND()).getParams() if params[0].getValue() == 0x00: return False elif params[0].getValue() == 0x01: """OK, Card reset""" return self.proc_transferATR() elif params[0].getValue() == 0x02: """T0 not supported""" if self.proc_transferATR(): return self.proc_setTransportProtocol(1) else: return False else: return False except BluetoothError , e: print "Error. " +str(e) return False def proc_disconnectByClient(self, timeout=0): try: self.__sendMsg(SAPMessage_DISCONNECT_REQ()) self.__rcvMsg(SAPMessage_DISCONNECT_RESP()) time.sleep(timeout) # let srv to close rfcomm self.__disconnectRFCOMM() return True except BluetoothError , e: print "Error. " +str(e) return False def proc_disconnectByServer(self, timeout=0): try: params = self.__rcvMsg(SAPMessage_DISCONNECT_IND()).getParams() """graceful""" if params[0].getValue() == 0x00: if not self.proc_transferAPDU(): return False return self.proc_disconnectByClient(timeout) except BluetoothError , e: print "Error. " +str(e) return False def proc_transferAPDU(self, apdu = "Sample APDU command"): try: self.__sendMsg(SAPMessage_TRANSFER_APDU_REQ(apdu)) params = self.__rcvMsg(SAPMessage_TRANSFER_APDU_RESP()).getParams() return True except BluetoothError , e: print "Error. " +str(e) return False def proc_transferATR(self): try: self.__sendMsg(SAPMessage_TRANSFER_ATR_REQ()) params = self.__rcvMsg(SAPMessage_TRANSFER_ATR_RESP()).getParams() return True except BluetoothError , e: print "Error. " +str(e) return False def proc_powerSimOff(self): try: self.__sendMsg(SAPMessage_POWER_SIM_OFF_REQ()) params = self.__rcvMsg(SAPMessage_POWER_SIM_OFF_RESP()).getParams() return True except BluetoothError , e: print "Error. " +str(e) return False def proc_powerSimOn(self): try: self.__sendMsg(SAPMessage_POWER_SIM_ON_REQ()) params = self.__rcvMsg(SAPMessage_POWER_SIM_ON_RESP()).getParams() if params[0].getValue() == 0x00: return self.proc_transferATR() return True except BluetoothError , e: print "Error. " +str(e) return False def proc_resetSim(self): try: self.__sendMsg(SAPMessage_RESET_SIM_REQ()) params = self.__rcvMsg(SAPMessage_RESET_SIM_RESP()).getParams() if params[0].getValue() == 0x00: return self.proc_transferATR() return True except BluetoothError , e: print "Error. " +str(e) return False def proc_reportStatus(self): try: params = self.__rcvMsg(SAPMessage_STATUS_IND()).getParams() except BluetoothError , e: print "Error. " +str(e) return False def proc_transferCardReaderStatus(self): try: self.__sendMsg(SAPMessage_TRANSFER_CARD_READER_STATUS_REQ()) params = self.__rcvMsg(SAPMessage_TRANSFER_CARD_READER_STATUS_RESP()).getParams() except BluetoothError , e: print "Error. " +str(e) return False def proc_errorResponse(self): try: """ send malformed message, no mandatory maxmsgsize parameter""" self.__sendMsg(SAPMessage_CONNECT_REQ()) params = self.__rcvMsg(SAPMessage_ERROR_RESP()).getParams() except BluetoothError , e: print "Error. " +str(e) return False def proc_setTransportProtocol(self, protocol = 0): try: self.__sendMsg(SAPMessage_SET_TRANSPORT_PROTOCOL_REQ(protocol)) params = self.__rcvMsg(SAPMessage_SET_TRANSPORT_PROTOCOL_RESP()).getParams() if params[0].getValue() == 0x00: params = self.__rcvMsg(SAPMessage_STATUS_IND()).getParams() if params[0].getValue() in (0x01, 0x02): return self.proc_transferATR() else: return True """return False ???""" elif params[0].getValue == 0x07: """not supported""" return True """return False ???""" else: return False except BluetoothError , e: print "Error. " +str(e) return False if __name__ == "__main__": pass
gpl-2.0
-5,468,918,267,625,201,000
31.490986
125
0.549561
false
mvidalgarcia/indico
indico/core/webpack.py
2
1598
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals import os from flask_webpackext import FlaskWebpackExt from flask_webpackext.manifest import JinjaManifestLoader from pywebpack import ManifestLoader from indico.web.assets.util import get_custom_assets class IndicoManifestLoader(JinjaManifestLoader): cache = {} def __init__(self, *args, **kwargs): self.custom = kwargs.pop('custom', True) super(IndicoManifestLoader, self).__init__(*args, **kwargs) def load(self, filepath): key = (filepath, os.path.getmtime(filepath)) if key not in IndicoManifestLoader.cache: IndicoManifestLoader.cache[key] = manifest = ManifestLoader.load(self, filepath) if self.custom: self._add_custom_assets(manifest) return IndicoManifestLoader.cache[key] def _add_custom_assets(self, manifest): # custom assets (from CUSTOMIZATION_DIR) are not part of the webpack manifest # since they are not build with webpack (it's generally not available on the # machine running indico), but we add them here anyway so they can be handled # without too much extra code, e.g. when building a static site. manifest.add(self.entry_cls('__custom.css', get_custom_assets('css'))) manifest.add(self.entry_cls('__custom.js', get_custom_assets('js'))) webpack = FlaskWebpackExt()
mit
-9,097,333,290,528,816,000
36.162791
92
0.69587
false
seanwestfall/django
django/views/static.py
190
5142
""" Views and functions for serving static files. These are only to be used during development, and SHOULD NOT be used in a production setting. """ from __future__ import unicode_literals import mimetypes import os import posixpath import re import stat from django.http import ( FileResponse, Http404, HttpResponse, HttpResponseNotModified, HttpResponseRedirect, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils.http import http_date, parse_http_date from django.utils.six.moves.urllib.parse import unquote from django.utils.translation import ugettext as _, ugettext_lazy def serve(request, path, document_root=None, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: from django.views.static import serve url(r'^(?P<path>.*)$', serve, {'document_root': '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not part: # Strip empty path components. continue drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # Strip '.' and '..' in path. continue newpath = os.path.join(newpath, part).replace('\\', '/') if newpath and path != newpath: return HttpResponseRedirect(newpath) fullpath = os.path.join(document_root, newpath) if os.path.isdir(fullpath): if show_indexes: return directory_index(newpath, fullpath) raise Http404(_("Directory indexes are not allowed here.")) if not os.path.exists(fullpath): raise Http404(_('"%(path)s" does not exist') % {'path': fullpath}) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj.st_mtime, statobj.st_size): return HttpResponseNotModified() content_type, encoding = mimetypes.guess_type(fullpath) content_type = content_type or 'application/octet-stream' response = FileResponse(open(fullpath, 'rb'), content_type=content_type) response["Last-Modified"] = http_date(statobj.st_mtime) if stat.S_ISREG(statobj.st_mode): response["Content-Length"] = statobj.st_size if encoding: response["Content-Encoding"] = encoding return response DEFAULT_DIRECTORY_INDEX_TEMPLATE = """ {% load i18n %} <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Language" content="en-us" /> <meta name="robots" content="NONE,NOARCHIVE" /> <title>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</title> </head> <body> <h1>{% blocktrans %}Index of {{ directory }}{% endblocktrans %}</h1> <ul> {% ifnotequal directory "/" %} <li><a href="../">../</a></li> {% endifnotequal %} {% for f in file_list %} <li><a href="{{ f|urlencode }}">{{ f }}</a></li> {% endfor %} </ul> </body> </html> """ template_translatable = ugettext_lazy("Index of %(directory)s") def directory_index(path, fullpath): try: t = loader.select_template([ 'static/directory_index.html', 'static/directory_index', ]) except TemplateDoesNotExist: t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE) files = [] for f in os.listdir(fullpath): if not f.startswith('.'): if os.path.isdir(os.path.join(fullpath, f)): f += '/' files.append(f) c = Context({ 'directory': path + '/', 'file_list': files, }) return HttpResponse(t.render(c)) def was_modified_since(header=None, mtime=0, size=0): """ Was something modified since the user last downloaded it? header This is the value of the If-Modified-Since header. If this is None, I'll just return True. mtime This is the modification time of the item we're talking about. size This is the size of the item we're talking about. """ try: if header is None: raise ValueError matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header, re.IGNORECASE) header_mtime = parse_http_date(matches.group(1)) header_len = matches.group(3) if header_len and int(header_len) != size: raise ValueError if int(mtime) > header_mtime: raise ValueError except (AttributeError, ValueError, OverflowError): return True return False
bsd-3-clause
-7,987,543,726,296,927,000
33.05298
78
0.624854
false
lhopps/grit-i18n
grit/tclib_unittest.py
36
8122
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''Unit tests for grit.tclib''' import sys import os.path if __name__ == '__main__': sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import types import unittest from grit import tclib from grit import exception import grit.extern.tclib class TclibUnittest(unittest.TestCase): def testInit(self): msg = tclib.Message(text=u'Hello Earthlings', description='Greetings\n\t message') self.failUnlessEqual(msg.GetPresentableContent(), 'Hello Earthlings') self.failUnless(isinstance(msg.GetPresentableContent(), types.StringTypes)) self.failUnlessEqual(msg.GetDescription(), 'Greetings message') def testGetAttr(self): msg = tclib.Message() msg.AppendText(u'Hello') # Tests __getattr__ self.failUnless(msg.GetPresentableContent() == 'Hello') self.failUnless(isinstance(msg.GetPresentableContent(), types.StringTypes)) def testAll(self): text = u'Howdie USERNAME' phs = [tclib.Placeholder(u'USERNAME', u'%s', 'Joi')] msg = tclib.Message(text=text, placeholders=phs) self.failUnless(msg.GetPresentableContent() == 'Howdie USERNAME') trans = tclib.Translation(text=text, placeholders=phs) self.failUnless(trans.GetPresentableContent() == 'Howdie USERNAME') self.failUnless(isinstance(trans.GetPresentableContent(), types.StringTypes)) def testUnicodeReturn(self): text = u'\u00fe' msg = tclib.Message(text=text) self.failUnless(msg.GetPresentableContent() == text) from_list = msg.GetContent()[0] self.failUnless(from_list == text) def testRegressionTranslationInherited(self): '''Regression tests a bug that was caused by grit.tclib.Translation inheriting from the translation console's Translation object instead of only owning an instance of it. ''' msg = tclib.Message(text=u"BLA1\r\nFrom: BLA2 \u00fe BLA3", placeholders=[ tclib.Placeholder('BLA1', '%s', '%s'), tclib.Placeholder('BLA2', '%s', '%s'), tclib.Placeholder('BLA3', '%s', '%s')]) transl = tclib.Translation(text=msg.GetPresentableContent(), placeholders=msg.GetPlaceholders()) content = transl.GetContent() self.failUnless(isinstance(content[3], types.UnicodeType)) def testFingerprint(self): # This has Windows line endings. That is on purpose. id = grit.extern.tclib.GenerateMessageId( 'Google Desktop for Enterprise\r\n' 'Copyright (C) 2006 Google Inc.\r\n' 'All Rights Reserved\r\n' '\r\n' '---------\r\n' 'Contents\r\n' '---------\r\n' 'This distribution contains the following files:\r\n' '\r\n' 'GoogleDesktopSetup.msi - Installation and setup program\r\n' 'GoogleDesktop.adm - Group Policy administrative template file\r\n' 'AdminGuide.pdf - Google Desktop for Enterprise administrative guide\r\n' '\r\n' '\r\n' '--------------\r\n' 'Documentation\r\n' '--------------\r\n' 'Full documentation and installation instructions are in the \r\n' 'administrative guide, and also online at \r\n' 'http://desktop.google.com/enterprise/adminguide.html.\r\n' '\r\n' '\r\n' '------------------------\r\n' 'IBM Lotus Notes Plug-In\r\n' '------------------------\r\n' 'The Lotus Notes plug-in is included in the release of Google \r\n' 'Desktop for Enterprise. The IBM Lotus Notes Plug-in for Google \r\n' 'Desktop indexes mail, calendar, task, contact and journal \r\n' 'documents from Notes. Discussion documents including those from \r\n' 'the discussion and team room templates can also be indexed by \r\n' 'selecting an option from the preferences. Once indexed, this data\r\n' 'will be returned in Google Desktop searches. The corresponding\r\n' 'document can be opened in Lotus Notes from the Google Desktop \r\n' 'results page.\r\n' '\r\n' 'Install: The plug-in will install automatically during the Google \r\n' 'Desktop setup process if Lotus Notes is already installed. Lotus \r\n' 'Notes must not be running in order for the install to occur. \r\n' '\r\n' 'Preferences: Preferences and selection of databases to index are\r\n' 'set in the \'Google Desktop for Notes\' dialog reached through the \r\n' '\'Actions\' menu.\r\n' '\r\n' 'Reindexing: Selecting \'Reindex all databases\' will index all the \r\n' 'documents in each database again.\r\n' '\r\n' '\r\n' 'Notes Plug-in Known Issues\r\n' '---------------------------\r\n' '\r\n' 'If the \'Google Desktop for Notes\' item is not available from the \r\n' 'Lotus Notes Actions menu, then installation was not successful. \r\n' 'Installation consists of writing one file, notesgdsplugin.dll, to \r\n' 'the Notes application directory and a setting to the notes.ini \r\n' 'configuration file. The most likely cause of an unsuccessful \r\n' 'installation is that the installer was not able to locate the \r\n' 'notes.ini file. Installation will complete if the user closes Notes\r\n' 'and manually adds the following setting to this file on a new line:\r\n' 'AddinMenus=notegdsplugin.dll\r\n' '\r\n' 'If the notesgdsplugin.dll file is not in the application directory\r\n' '(e.g., C:\Program Files\Lotus\Notes) after Google Desktop \r\n' 'installation, it is likely that Notes was not installed correctly. \r\n' '\r\n' 'Only local databases can be indexed. If they can be determined, \r\n' 'the user\'s local mail file and address book will be included in the\r\n' 'list automatically. Mail archives and other databases must be \r\n' 'added with the \'Add\' button.\r\n' '\r\n' 'Some users may experience performance issues during the initial \r\n' 'indexing of a database. The \'Perform the initial index of a \r\n' 'database only when I\'m idle\' option will limit the indexing process\r\n' 'to times when the user is not using the machine. If this does not \r\n' 'alleviate the problem or the user would like to continually index \r\n' 'but just do so more slowly or quickly, the GoogleWaitTime notes.ini\r\n' 'value can be set. Increasing the GoogleWaitTime value will slow \r\n' 'down the indexing process, and lowering the value will speed it up.\r\n' 'A value of zero causes the fastest possible indexing. Removing the\r\n' 'ini parameter altogether returns it to the default (20).\r\n' '\r\n' 'Crashes have been known to occur with certain types of history \r\n' 'bookmarks. If the Notes client seems to crash randomly, try \r\n' 'disabling the \'Index note history\' option. If it crashes before,\r\n' 'you can get to the preferences, add the following line to your \r\n' 'notes.ini file:\r\n' 'GDSNoIndexHistory=1\r\n') self.failUnless(id == '8961534701379422820') def testPlaceholderNameChecking(self): try: ph = tclib.Placeholder('BINGO BONGO', 'bla', 'bla') raise Exception("We shouldn't get here") except exception.InvalidPlaceholderName: pass # Expect exception to be thrown because presentation contained space def testTagsWithCommonSubstring(self): word = 'ABCDEFGHIJ' text = ' '.join([word[:i] for i in range(1, 11)]) phs = [tclib.Placeholder(word[:i], str(i), str(i)) for i in range(1, 11)] try: msg = tclib.Message(text=text, placeholders=phs) self.failUnless(msg.GetRealContent() == '1 2 3 4 5 6 7 8 9 10') except: self.fail('tclib.Message() should handle placeholders that are ' 'substrings of each other') if __name__ == '__main__': unittest.main()
bsd-2-clause
2,623,659,705,779,324,000
44.374302
81
0.650086
false
dionbosschieter/NetworkMonitor
src/Client/InfoContainer.py
1
1892
import terminal import curses import time from curses import panel class InfoContainer(object): def __init__(self, stdscreen, title, debug_console): self.debug_console = debug_console self.height = int(terminal.height/2) self.width = terminal.width - 2 self.title = title self.window = stdscreen.subwin(self.height,self.width,1,1) self.window.border(0) self.window.addstr(0,1,title) self.panel = panel.new_panel(self.window) self.panel.hide() panel.update_panels() # Add the Border self.second = time.time() self.writebuffer = [] def display(self): self.panel.top() self.panel.show() #self.window.clear() def hide(self): self.window.clear() self.panel.hide() panel.update_panels() curses.doupdate() def refresh(self): self.window.clear() self.window.border(0) self.window.addstr(0,1,self.title) #draw the last 20 log items #foreach i from 0 till (self.height-2) #draw string on i place #self.writebuffer[-(self.height-2):] maxlength = (self.height-3) lengthofbuffer = len(self.writebuffer) if(lengthofbuffer>maxlength): startindex = (lengthofbuffer-1)-maxlength else: startindex = 0 maxlength = lengthofbuffer for i in range(0, maxlength): #self.window.addstr(i,1,str(i)) self.window.addstr(i+1,1,self.writebuffer[i+startindex]) self.window.refresh() curses.doupdate() def addPacket(self, packet): #1 refresh per second// or 2? if(time.time() - self.second >= 1): self.writebuffer.append(packet) self.second = time.time() else: self.writebuffer.append(packet)
mit
8,029,939,048,508,223,000
27.666667
68
0.581924
false
eriol/circuits
examples/node/nodeserver.py
3
2429
#!/usr/bin/env python """Node Server Example This example demonstrates how to create a very simple node server that supports bi-diractional messaging between server and connected clients forming a cluster of nodes. """ from __future__ import print_function from os import getpid from optparse import OptionParser from circuits.node import Node from circuits import Component, Debugger __version__ = "0.0.1" USAGE = "%prog [options]" VERSION = "%prog v" + __version__ def parse_options(): parser = OptionParser(usage=USAGE, version=VERSION) parser.add_option( "-b", "--bind", action="store", type="string", default="0.0.0.0:8000", dest="bind", help="Bind to address:[port]" ) parser.add_option( "-d", "--debug", action="store_true", default=False, dest="debug", help="Enable debug mode" ) opts, args = parser.parse_args() return opts, args class NodeServer(Component): def init(self, args, opts): """Initialize our ``ChatServer`` Component. This uses the convenience ``init`` method which is called after the component is proeprly constructed and initialized and passed the same args and kwargs that were passed during construction. """ self.args = args self.opts = opts self.clients = {} if opts.debug: Debugger().register(self) if ":" in opts.bind: address, port = opts.bind.split(":") port = int(port) else: address, port = opts.bind, 8000 Node(port=port, server_ip=address).register(self) def connect(self, sock, host, port): """Connect Event -- Triggered for new connecting clients""" self.clients[sock] = { "host": sock, "port": port, } def disconnect(self, sock): """Disconnect Event -- Triggered for disconnecting clients""" if sock not in self.clients: return del self.clients[sock] def ready(self, server, bind): print("Ready! Listening on {}:{}".format(*bind)) print("Waiting for remote events...") def hello(self): return "Hello World! ({0:d})".format(getpid()) def main(): opts, args = parse_options() # Configure and "run" the System. NodeServer(args, opts).run() if __name__ == "__main__": main()
mit
-6,181,088,414,534,044,000
21.490741
75
0.59613
false
klickagent/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/port/mac.py
113
14225
# Copyright (C) 2011 Google Inc. All rights reserved. # Copyright (C) 2012, 2013 Apple 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 Google name 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 logging import os import time from webkitpy.common.system.crashlogs import CrashLogs from webkitpy.common.system.executive import ScriptError from webkitpy.port.apple import ApplePort from webkitpy.port.leakdetector import LeakDetector _log = logging.getLogger(__name__) class MacPort(ApplePort): port_name = "mac" VERSION_FALLBACK_ORDER = ['mac-snowleopard', 'mac-lion', 'mac-mountainlion'] ARCHITECTURES = ['x86_64', 'x86'] def __init__(self, host, port_name, **kwargs): ApplePort.__init__(self, host, port_name, **kwargs) self._architecture = self.get_option('architecture') if not self._architecture: self._architecture = 'x86_64' self._leak_detector = LeakDetector(self) if self.get_option("leaks"): # DumpRenderTree slows down noticably if we run more than about 1000 tests in a batch # with MallocStackLogging enabled. self.set_option_default("batch_size", 1000) def default_timeout_ms(self): if self.get_option('guard_malloc'): return 350 * 1000 return super(MacPort, self).default_timeout_ms() def supports_per_test_timeout(self): return True def _build_driver_flags(self): return ['ARCHS=i386'] if self.architecture() == 'x86' else [] def should_retry_crashes(self): # On Apple Mac, we retry crashes due to https://bugs.webkit.org/show_bug.cgi?id=82233 return True def default_baseline_search_path(self): name = self._name.replace('-wk2', '') if name.endswith(self.FUTURE_VERSION): fallback_names = [self.port_name] else: fallback_names = self.VERSION_FALLBACK_ORDER[self.VERSION_FALLBACK_ORDER.index(name):-1] + [self.port_name] if self.get_option('webkit_test_runner'): fallback_names = [self._wk2_port_name(), 'wk2'] + fallback_names return map(self._webkit_baseline_path, fallback_names) def _port_specific_expectations_files(self): return list(reversed([self._filesystem.join(self._webkit_baseline_path(p), 'TestExpectations') for p in self.baseline_search_path()])) def setup_environ_for_server(self, server_name=None): env = super(MacPort, self).setup_environ_for_server(server_name) if server_name == self.driver_name(): if self.get_option('leaks'): env['MallocStackLogging'] = '1' if self.get_option('guard_malloc'): env['DYLD_INSERT_LIBRARIES'] = '/usr/lib/libgmalloc.dylib:' + self._build_path("libWebCoreTestShim.dylib") else: env['DYLD_INSERT_LIBRARIES'] = self._build_path("libWebCoreTestShim.dylib") env['XML_CATALOG_FILES'] = '' # work around missing /etc/catalog <rdar://problem/4292995> return env def operating_system(self): return 'mac' # Belongs on a Platform object. def is_snowleopard(self): return self._version == "snowleopard" # Belongs on a Platform object. def is_lion(self): return self._version == "lion" def default_child_processes(self): if self._version == "snowleopard": _log.warning("Cannot run tests in parallel on Snow Leopard due to rdar://problem/10621525.") return 1 default_count = super(MacPort, self).default_child_processes() # FIXME: https://bugs.webkit.org/show_bug.cgi?id=95906 With too many WebProcess WK2 tests get stuck in resource contention. # To alleviate the issue reduce the number of running processes # Anecdotal evidence suggests that a 4 core/8 core logical machine may run into this, but that a 2 core/4 core logical machine does not. should_throttle_for_wk2 = self.get_option('webkit_test_runner') and default_count > 4 # We also want to throttle for leaks bots. if should_throttle_for_wk2 or self.get_option('leaks'): default_count = int(.75 * default_count) # Make sure we have enough ram to support that many instances: total_memory = self.host.platform.total_bytes_memory() if total_memory: bytes_per_drt = 256 * 1024 * 1024 # Assume each DRT needs 256MB to run. overhead = 2048 * 1024 * 1024 # Assume we need 2GB free for the O/S supportable_instances = max((total_memory - overhead) / bytes_per_drt, 1) # Always use one process, even if we don't have space for it. if supportable_instances < default_count: _log.warning("This machine could support %s child processes, but only has enough memory for %s." % (default_count, supportable_instances)) else: _log.warning("Cannot determine available memory for child processes, using default child process count of %s." % default_count) supportable_instances = default_count return min(supportable_instances, default_count) def _build_java_test_support(self): java_tests_path = self._filesystem.join(self.layout_tests_dir(), "java") build_java = [self.make_command(), "-C", java_tests_path] if self._executive.run_command(build_java, return_exit_code=True): # Paths are absolute, so we don't need to set a cwd. _log.error("Failed to build Java support files: %s" % build_java) return False return True def check_for_leaks(self, process_name, process_pid): if not self.get_option('leaks'): return # We could use http://code.google.com/p/psutil/ to get the process_name from the pid. self._leak_detector.check_for_leaks(process_name, process_pid) def print_leaks_summary(self): if not self.get_option('leaks'): return # We're in the manager process, so the leak detector will not have a valid list of leak files. # FIXME: This is a hack, but we don't have a better way to get this information from the workers yet. # FIXME: This will include too many leaks in subsequent runs until the results directory is cleared! leaks_files = self._leak_detector.leaks_files_in_directory(self.results_directory()) if not leaks_files: return total_bytes_string, unique_leaks = self._leak_detector.count_total_bytes_and_unique_leaks(leaks_files) total_leaks = self._leak_detector.count_total_leaks(leaks_files) _log.info("%s total leaks found for a total of %s!" % (total_leaks, total_bytes_string)) _log.info("%s unique leaks found!" % unique_leaks) def _check_port_build(self): return self.get_option('nojava') or self._build_java_test_support() def _path_to_webcore_library(self): return self._build_path('WebCore.framework/Versions/A/WebCore') def show_results_html_file(self, results_filename): # We don't use self._run_script() because we don't want to wait for the script # to exit and we want the output to show up on stdout in case there are errors # launching the browser. self._executive.popen([self.path_to_script('run-safari')] + self._arguments_for_configuration() + ['--no-saved-state', '-NSOpen', results_filename], cwd=self.webkit_base(), stdout=file(os.devnull), stderr=file(os.devnull)) # FIXME: The next two routines turn off the http locking in order # to work around failures on the bots caused when the slave restarts. # See https://bugs.webkit.org/show_bug.cgi?id=64886 for more info. # The proper fix is to make sure the slave is actually stopping NRWT # properly on restart. Note that by removing the lock file and not waiting, # the result should be that if there is a web server already running, # it'll be killed and this one will be started in its place; this # may lead to weird things happening in the other run. However, I don't # think we're (intentionally) actually running multiple runs concurrently # on any Mac bots. def acquire_http_lock(self): pass def release_http_lock(self): pass def sample_file_path(self, name, pid): return self._filesystem.join(self.results_directory(), "{0}-{1}-sample.txt".format(name, pid)) def _get_crash_log(self, name, pid, stdout, stderr, newer_than, time_fn=None, sleep_fn=None, wait_for_log=True): # Note that we do slow-spin here and wait, since it appears the time # ReportCrash takes to actually write and flush the file varies when there are # lots of simultaneous crashes going on. # FIXME: Should most of this be moved into CrashLogs()? time_fn = time_fn or time.time sleep_fn = sleep_fn or time.sleep crash_log = '' crash_logs = CrashLogs(self.host) now = time_fn() # FIXME: delete this after we're sure this code is working ... _log.debug('looking for crash log for %s:%s' % (name, str(pid))) deadline = now + 5 * int(self.get_option('child_processes', 1)) while not crash_log and now <= deadline: crash_log = crash_logs.find_newest_log(name, pid, include_errors=True, newer_than=newer_than) if not wait_for_log: break if not crash_log or not [line for line in crash_log.splitlines() if not line.startswith('ERROR')]: sleep_fn(0.1) now = time_fn() if not crash_log: return (stderr, None) return (stderr, crash_log) def look_for_new_crash_logs(self, crashed_processes, start_time): """Since crash logs can take a long time to be written out if the system is under stress do a second pass at the end of the test run. crashes: test_name -> pid, process_name tuple of crashed process start_time: time the tests started at. We're looking for crash logs after that time. """ crash_logs = {} for (test_name, process_name, pid) in crashed_processes: # Passing None for output. This is a second pass after the test finished so # if the output had any logging we would have already collected it. crash_log = self._get_crash_log(process_name, pid, None, None, start_time, wait_for_log=False)[1] if not crash_log: continue crash_logs[test_name] = crash_log return crash_logs def look_for_new_samples(self, unresponsive_processes, start_time): sample_files = {} for (test_name, process_name, pid) in unresponsive_processes: sample_file = self.sample_file_path(process_name, pid) if not self._filesystem.isfile(sample_file): continue sample_files[test_name] = sample_file return sample_files def sample_process(self, name, pid): try: hang_report = self.sample_file_path(name, pid) self._executive.run_command([ "/usr/bin/sample", pid, 10, 10, "-file", hang_report, ]) except ScriptError as e: _log.warning('Unable to sample process:' + str(e)) def _path_to_helper(self): binary_name = 'LayoutTestHelper' return self._build_path(binary_name) def start_helper(self): helper_path = self._path_to_helper() if helper_path: _log.debug("Starting layout helper %s" % helper_path) self._helper = self._executive.popen([helper_path], stdin=self._executive.PIPE, stdout=self._executive.PIPE, stderr=None) is_ready = self._helper.stdout.readline() if not is_ready.startswith('ready'): _log.error("LayoutTestHelper failed to be ready") def stop_helper(self): if self._helper: _log.debug("Stopping LayoutTestHelper") try: self._helper.stdin.write("x\n") self._helper.stdin.close() self._helper.wait() except IOError, e: _log.debug("IOError raised while stopping helper: %s" % str(e)) self._helper = None def make_command(self): return self.xcrun_find('make', '/usr/bin/make') def nm_command(self): return self.xcrun_find('nm', 'nm') def xcrun_find(self, command, fallback): try: return self._executive.run_command(['xcrun', '-find', command]).rstrip() except ScriptError: _log.warn("xcrun failed; falling back to '%s'." % fallback) return fallback
bsd-3-clause
-1,683,058,798,068,343,300
45.639344
156
0.644499
false
krieger-od/nwjs_chromium.src
chrome/common/extensions/docs/server2/build_server.py
80
3340
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This script is used to copy all dependencies into the local directory. # The package of files can then be uploaded to App Engine. import os import shutil import stat import sys SRC_DIR = os.path.join(sys.path[0], os.pardir, os.pardir, os.pardir, os.pardir, os.pardir) THIRD_PARTY_DIR = os.path.join(SRC_DIR, 'third_party') LOCAL_THIRD_PARTY_DIR = os.path.join(sys.path[0], 'third_party') TOOLS_DIR = os.path.join(SRC_DIR, 'tools') SCHEMA_COMPILER_FILES = ['memoize.py', 'model.py', 'idl_schema.py', 'schema_util.py', 'json_parse.py', 'json_schema.py'] def MakeInit(path): path = os.path.join(path, '__init__.py') with open(os.path.join(path), 'w') as f: os.utime(os.path.join(path), None) def OnError(function, path, excinfo): os.chmod(path, stat.S_IWUSR) function(path) def CopyThirdParty(src, dest, files=None, make_init=True): dest_path = os.path.join(LOCAL_THIRD_PARTY_DIR, dest) if not files: shutil.copytree(src, dest_path) if make_init: MakeInit(dest_path) return try: os.makedirs(dest_path) except Exception: pass if make_init: MakeInit(dest_path) for filename in files: shutil.copy(os.path.join(src, filename), os.path.join(dest_path, filename)) def main(): if os.path.isdir(LOCAL_THIRD_PARTY_DIR): try: shutil.rmtree(LOCAL_THIRD_PARTY_DIR, False, OnError) except OSError: print('*-------------------------------------------------------------*\n' '| If you are receiving an upload error, try removing |\n' '| chrome/common/extensions/docs/server2/third_party manually. |\n' '*-------------------------------------------------------------*\n') CopyThirdParty(os.path.join(THIRD_PARTY_DIR, 'motemplate'), 'motemplate') CopyThirdParty(os.path.join(THIRD_PARTY_DIR, 'markdown'), 'markdown', make_init=False) CopyThirdParty(os.path.join(SRC_DIR, 'ppapi', 'generators'), 'json_schema_compiler') CopyThirdParty(os.path.join(THIRD_PARTY_DIR, 'ply'), os.path.join('json_schema_compiler', 'ply')) CopyThirdParty(os.path.join(TOOLS_DIR, 'json_schema_compiler'), 'json_schema_compiler', SCHEMA_COMPILER_FILES) CopyThirdParty(os.path.join(TOOLS_DIR, 'json_comment_eater'), 'json_schema_compiler', ['json_comment_eater.py']) CopyThirdParty(os.path.join(THIRD_PARTY_DIR, 'simplejson'), os.path.join('json_schema_compiler', 'simplejson'), make_init=False) MakeInit(LOCAL_THIRD_PARTY_DIR) CopyThirdParty(os.path.join(THIRD_PARTY_DIR, 'google_appengine_cloudstorage', 'cloudstorage'), 'cloudstorage') # To be able to use the Motemplate class we need this import in __init__.py. with open(os.path.join(LOCAL_THIRD_PARTY_DIR, 'motemplate', '__init__.py'), 'a') as f: f.write('from motemplate import Motemplate\n') if __name__ == '__main__': main()
bsd-3-clause
-4,363,357,893,083,128,000
36.52809
80
0.594611
false
fossoult/odoo
addons/l10n_fr/__init__.py
424
1447
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2008 JAILLET Simon - CrysaLEAD - www.crysalead.fr # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company # # 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 l10n_fr import report import wizard # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
5,042,121,340,552,376,000
41.558824
80
0.689012
false
bijanfallah/OI_CCLM
src/RMSE_MAPS_INGO.py
1
2007
# Program to show the maps of RMSE averaged over time import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error import os from netCDF4 import Dataset as NetCDFFile import numpy as np from CCLM_OUTS import Plot_CCLM # option == 1 -> shift 4 with default cclm domain and nboundlines = 3 # option == 2 -> shift 4 with smaller cclm domain and nboundlines = 3 # option == 3 -> shift 4 with smaller cclm domain and nboundlines = 6 # option == 4 -> shift 4 with corrected smaller cclm domain and nboundlines = 3 # option == 5 -> shift 4 with corrected smaller cclm domain and nboundlines = 4 # option == 6 -> shift 4 with corrected smaller cclm domain and nboundlines = 6 # option == 7 -> shift 4 with corrected smaller cclm domain and nboundlines = 9 # option == 8 -> shift 4 with corrected bigger cclm domain and nboundlines = 3 from CCLM_OUTS import Plot_CCLM #def f(x): # if x==-9999: # return float('NaN') # else: # return x def read_data_from_mistral(dir='/work/bb1029/b324045/work1/work/member/post/',name='member_T_2M_ts_seasmean.nc',var='T_2M'): # type: (object, object, object) -> object #a function to read the data from mistral work """ :rtype: object """ #CMD = 'scp $mistral:' + dir + name + ' ./' CMD = 'wget users.met.fu-berlin.de/~BijanFallah/' + dir + name os.system(CMD) nc = NetCDFFile(name) # for name2, variable in nc.variables.items(): # for attrname in variable.ncattrs(): # print(name2, variable, '-----------------',attrname) # #print("{} -- {}".format(attrname, getattr(variable, attrname))) os.remove(name) lats = nc.variables['lat'][:] lons = nc.variables['lon'][:] t = nc.variables[var][:].squeeze() rlats = nc.variables['rlat'][:] # extract/copy the data rlons = nc.variables['rlon'][:] #f2 = np.vectorize(f) #t= f2(t) #t=t.data t=t.squeeze() #print() nc.close() return(t, lats, lons, rlats, rlons)
mit
6,172,872,896,229,471,000
37.596154
124
0.63727
false
steven-hadfield/dpxdt
deployment/appengine/appengine_config.py
4
2989
#!/usr/bin/env python # Copyright 2013 Brett Slatkin # # 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. """App Engine configuration file. See: https://developers.google.com/appengine/docs/python/tools/appengineconfig """ import os import logging import os import sys # Log to disk for managed VMs: # https://cloud.google.com/appengine/docs/managed-vms/custom-runtimes#logging if os.environ.get('LOG_TO_DISK'): log_dir = '/var/log/app_engine/custom_logs' try: os.makedirs(log_dir) except OSError: pass # Directory already exists log_path = os.path.join(log_dir, 'app.log') handler = logging.FileHandler(log_path) handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter( '%(levelname)s %(filename)s:%(lineno)s] %(message)s')) logging.getLogger().addHandler(handler) # Load up our app and all its dependencies. Make the environment sane. from dpxdt.tools import run_server # Initialize flags from flags file or enviornment. import gflags gflags.FLAGS(['dpxdt_server', '--flagfile=flags.cfg']) logging.info('BEGIN Flags') for key, flag in gflags.FLAGS.FlagDict().iteritems(): logging.info('%s = %s', key, flag.value) logging.info('END Flags') # When in production use precompiled templates. Sometimes templates break # in production. To debug templates there, comment this out entirely. if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'): import jinja2 from dpxdt.server import app app.jinja_env.auto_reload = False app.jinja_env.loader = jinja2.ModuleLoader('templates_compiled.zip') # Install dpxdt.server override hooks. from dpxdt.server import api import hooks api._artifact_created = hooks._artifact_created api._get_artifact_response = hooks._get_artifact_response # Don't log when appstats is active. appstats_DUMP_LEVEL = -1 # SQLAlchemy stacks are really deep. appstats_MAX_STACK = 20 # Use very shallow local variable reprs to reduce noise. appstats_MAX_DEPTH = 2 # Enable the remote shell, since the old admin interactive console doesn't # work with managed VMs. appstats_SHELL_OK = True # These are only used if gae_mini_profiler was properly installed def gae_mini_profiler_should_profile_production(): from google.appengine.api import users return users.is_current_user_admin() def gae_mini_profiler_should_profile_development(): return True # Fix the appstats module's formatting helper function. import appstats_monkey_patch
apache-2.0
6,358,295,125,254,556,000
28.89
77
0.742389
false
gangadharkadam/contributionerp
erpnext/projects/report/project_wise_stock_tracking/project_wise_stock_tracking.py
46
3173
# 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 import _ def execute(filters=None): columns = get_columns() proj_details = get_project_details() pr_item_map = get_purchased_items_cost() se_item_map = get_issued_items_cost() dn_item_map = get_delivered_items_cost() data = [] for project in proj_details: data.append([project.name, pr_item_map.get(project.name, 0), se_item_map.get(project.name, 0), dn_item_map.get(project.name, 0), project.project_name, project.status, project.company, project.customer, project.estimated_costing, project.expected_start_date, project.expected_end_date]) return columns, data def get_columns(): return [_("Project Id") + ":Link/Project:140", _("Cost of Purchased Items") + ":Currency:160", _("Cost of Issued Items") + ":Currency:160", _("Cost of Delivered Items") + ":Currency:160", _("Project Name") + "::120", _("Project Status") + "::120", _("Company") + ":Link/Company:100", _("Customer") + ":Link/Customer:140", _("Project Value") + ":Currency:120", _("Project Start Date") + ":Date:120", _("Completion Date") + ":Date:120"] def get_project_details(): return frappe.db.sql(""" select name, project_name, status, company, customer, estimated_costing, expected_start_date, expected_end_date from tabProject where docstatus < 2""", as_dict=1) def get_purchased_items_cost(): pr_items = frappe.db.sql("""select project_name, sum(base_net_amount) as amount from `tabPurchase Receipt Item` where ifnull(project_name, '') != '' and docstatus = 1 group by project_name""", as_dict=1) pr_item_map = {} for item in pr_items: pr_item_map.setdefault(item.project_name, item.amount) return pr_item_map def get_issued_items_cost(): se_items = frappe.db.sql("""select se.project_name, sum(se_item.amount) as amount from `tabStock Entry` se, `tabStock Entry Detail` se_item where se.name = se_item.parent and se.docstatus = 1 and ifnull(se_item.t_warehouse, '') = '' and ifnull(se.project_name, '') != '' group by se.project_name""", as_dict=1) se_item_map = {} for item in se_items: se_item_map.setdefault(item.project_name, item.amount) return se_item_map def get_delivered_items_cost(): dn_items = frappe.db.sql("""select dn.project_name, sum(dn_item.base_net_amount) as amount from `tabDelivery Note` dn, `tabDelivery Note Item` dn_item where dn.name = dn_item.parent and dn.docstatus = 1 and ifnull(dn.project_name, '') != '' group by dn.project_name""", as_dict=1) si_items = frappe.db.sql("""select si.project_name, sum(si_item.base_net_amount) as amount from `tabSales Invoice` si, `tabSales Invoice Item` si_item where si.name = si_item.parent and si.docstatus = 1 and ifnull(si.update_stock, 0) = 1 and ifnull(si.is_pos, 0) = 1 and ifnull(si.project_name, '') != '' group by si.project_name""", as_dict=1) dn_item_map = {} for item in dn_items: dn_item_map.setdefault(item.project_name, item.amount) for item in si_items: dn_item_map.setdefault(item.project_name, item.amount) return dn_item_map
agpl-3.0
-2,526,490,087,109,348,000
39.164557
98
0.69209
false
imsparsh/python-for-android
python3-alpha/extra_modules/gdata/books/__init__.py
124
18532
#!/usr/bin/python """ Data Models for books.service All classes can be instantiated from an xml string using their FromString class method. Notes: * Book.title displays the first dc:title because the returned XML repeats that datum as atom:title. There is an undocumented gbs:openAccess element that is not parsed. """ __author__ = "James Sams <sams.james@gmail.com>" __copyright__ = "Apache License v2.0" import atom import gdata BOOK_SEARCH_NAMESPACE = 'http://schemas.google.com/books/2008' DC_NAMESPACE = 'http://purl.org/dc/terms' ANNOTATION_REL = "http://schemas.google.com/books/2008/annotation" INFO_REL = "http://schemas.google.com/books/2008/info" LABEL_SCHEME = "http://schemas.google.com/books/2008/labels" PREVIEW_REL = "http://schemas.google.com/books/2008/preview" THUMBNAIL_REL = "http://schemas.google.com/books/2008/thumbnail" FULL_VIEW = "http://schemas.google.com/books/2008#view_all_pages" PARTIAL_VIEW = "http://schemas.google.com/books/2008#view_partial" NO_VIEW = "http://schemas.google.com/books/2008#view_no_pages" UNKNOWN_VIEW = "http://schemas.google.com/books/2008#view_unknown" EMBEDDABLE = "http://schemas.google.com/books/2008#embeddable" NOT_EMBEDDABLE = "http://schemas.google.com/books/2008#not_embeddable" class _AtomFromString(atom.AtomBase): #@classmethod def FromString(cls, s): return atom.CreateClassFromXMLString(cls, s) FromString = classmethod(FromString) class Creator(_AtomFromString): """ The <dc:creator> element identifies an author-or more generally, an entity responsible for creating the volume in question. Examples of a creator include a person, an organization, or a service. In the case of anthologies, proceedings, or other edited works, this field may be used to indicate editors or other entities responsible for collecting the volume's contents. This element appears as a child of <entry>. If there are multiple authors or contributors to the book, there may be multiple <dc:creator> elements in the volume entry (one for each creator or contributor). """ _tag = 'creator' _namespace = DC_NAMESPACE class Date(_AtomFromString): #iso 8601 / W3CDTF profile """ The <dc:date> element indicates the publication date of the specific volume in question. If the book is a reprint, this is the reprint date, not the original publication date. The date is encoded according to the ISO-8601 standard (and more specifically, the W3CDTF profile). The <dc:date> element can appear only as a child of <entry>. Usually only the year or the year and the month are given. YYYY-MM-DDThh:mm:ssTZD TZD = -hh:mm or +hh:mm """ _tag = 'date' _namespace = DC_NAMESPACE class Description(_AtomFromString): """ The <dc:description> element includes text that describes a book or book result. In a search result feed, this may be a search result "snippet" that contains the words around the user's search term. For a single volume feed, this element may contain a synopsis of the book. The <dc:description> element can appear only as a child of <entry> """ _tag = 'description' _namespace = DC_NAMESPACE class Format(_AtomFromString): """ The <dc:format> element describes the physical properties of the volume. Currently, it indicates the number of pages in the book, but more information may be added to this field in the future. This element can appear only as a child of <entry>. """ _tag = 'format' _namespace = DC_NAMESPACE class Identifier(_AtomFromString): """ The <dc:identifier> element provides an unambiguous reference to a particular book. * Every <entry> contains at least one <dc:identifier> child. * The first identifier is always the unique string Book Search has assigned to the volume (such as s1gVAAAAYAAJ). This is the ID that appears in the book's URL in the Book Search GUI, as well as in the URL of that book's single item feed. * Many books contain additional <dc:identifier> elements. These provide alternate, external identifiers to the volume. Such identifiers may include the ISBNs, ISSNs, Library of Congress Control Numbers (LCCNs), and OCLC numbers; they are prepended with a corresponding namespace prefix (such as "ISBN:"). * Any <dc:identifier> can be passed to the Dynamic Links, used to instantiate an Embedded Viewer, or even used to construct static links to Book Search. The <dc:identifier> element can appear only as a child of <entry>. """ _tag = 'identifier' _namespace = DC_NAMESPACE class Publisher(_AtomFromString): """ The <dc:publisher> element contains the name of the entity responsible for producing and distributing the volume (usually the specific edition of this book). Examples of a publisher include a person, an organization, or a service. This element can appear only as a child of <entry>. If there is more than one publisher, multiple <dc:publisher> elements may appear. """ _tag = 'publisher' _namespace = DC_NAMESPACE class Subject(_AtomFromString): """ The <dc:subject> element identifies the topic of the book. Usually this is a Library of Congress Subject Heading (LCSH) or Book Industry Standards and Communications Subject Heading (BISAC). The <dc:subject> element can appear only as a child of <entry>. There may be multiple <dc:subject> elements per entry. """ _tag = 'subject' _namespace = DC_NAMESPACE class Title(_AtomFromString): """ The <dc:title> element contains the title of a book as it was published. If a book has a subtitle, it appears as a second <dc:title> element in the book result's <entry>. """ _tag = 'title' _namespace = DC_NAMESPACE class Viewability(_AtomFromString): """ Google Book Search respects the user's local copyright restrictions. As a result, previews or full views of some books are not available in all locations. The <gbs:viewability> element indicates whether a book is fully viewable, can be previewed, or only has "about the book" information. These three "viewability modes" are the same ones returned by the Dynamic Links API. The <gbs:viewability> element can appear only as a child of <entry>. The value attribute will take the form of the following URIs to represent the relevant viewing capability: Full View: http://schemas.google.com/books/2008#view_all_pages Limited Preview: http://schemas.google.com/books/2008#view_partial Snippet View/No Preview: http://schemas.google.com/books/2008#view_no_pages Unknown view: http://schemas.google.com/books/2008#view_unknown """ _tag = 'viewability' _namespace = BOOK_SEARCH_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, text=None, extension_elements=None, extension_attributes=None): self.value = value _AtomFromString.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Embeddability(_AtomFromString): """ Many of the books found on Google Book Search can be embedded on third-party sites using the Embedded Viewer. The <gbs:embeddability> element indicates whether a particular book result is available for embedding. By definition, a book that cannot be previewed on Book Search cannot be embedded on third- party sites. The <gbs:embeddability> element can appear only as a child of <entry>. The value attribute will take on one of the following URIs: embeddable: http://schemas.google.com/books/2008#embeddable not embeddable: http://schemas.google.com/books/2008#not_embeddable """ _tag = 'embeddability' _namespace = BOOK_SEARCH_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, text=None, extension_elements=None, extension_attributes=None): self.value = value _AtomFromString.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Review(_AtomFromString): """ When present, the <gbs:review> element contains a user-generated review for a given book. This element currently appears only in the user library and user annotation feeds, as a child of <entry>. type: text, html, xhtml xml:lang: id of the language, a guess, (always two letters?) """ _tag = 'review' _namespace = BOOK_SEARCH_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' _attributes['{http://www.w3.org/XML/1998/namespace}lang'] = 'lang' def __init__(self, type=None, lang=None, text=None, extension_elements=None, extension_attributes=None): self.type = type self.lang = lang _AtomFromString.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Rating(_AtomFromString): """All attributes must take an integral string between 1 and 5. The min, max, and average attributes represent 'community' ratings. The value attribute is the user's (of the feed from which the item is fetched, not necessarily the authenticated user) rating of the book. """ _tag = 'rating' _namespace = gdata.GDATA_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['min'] = 'min' _attributes['max'] = 'max' _attributes['average'] = 'average' _attributes['value'] = 'value' def __init__(self, min=None, max=None, average=None, value=None, text=None, extension_elements=None, extension_attributes=None): self.min = min self.max = max self.average = average self.value = value _AtomFromString.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Book(_AtomFromString, gdata.GDataEntry): """ Represents an <entry> from either a search, annotation, library, or single item feed. Note that dc_title attribute is the proper title of the volume, title is an atom element and may not represent the full title. """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() for i in (Creator, Identifier, Publisher, Subject,): _children['{%s}%s' % (i._namespace, i._tag)] = (i._tag, [i]) for i in (Date, Description, Format, Viewability, Embeddability, Review, Rating): # Review, Rating maybe only in anno/lib entrys _children['{%s}%s' % (i._namespace, i._tag)] = (i._tag, i) # there is an atom title as well, should we clobber that? del(i) _children['{%s}%s' % (Title._namespace, Title._tag)] = ('dc_title', [Title]) def to_dict(self): """Returns a dictionary of the book's available metadata. If the data cannot be discovered, it is not included as a key in the returned dict. The possible keys are: authors, embeddability, date, description, format, identifiers, publishers, rating, review, subjects, title, and viewability. Notes: * Plural keys will be lists * Singular keys will be strings * Title, despite usually being a list, joins the title and subtitle with a space as a single string. * embeddability and viewability only return the portion of the URI after # * identifiers is a list of tuples, where the first item of each tuple is the type of identifier and the second item is the identifying string. Note that while doing dict() on this tuple may be possible, some items may have multiple of the same identifier and converting to a dict may resulted in collisions/dropped data. * Rating returns only the user's rating. See Rating class for precise definition. """ d = {} if self.GetAnnotationLink(): d['annotation'] = self.GetAnnotationLink().href if self.creator: d['authors'] = [x.text for x in self.creator] if self.embeddability: d['embeddability'] = self.embeddability.value.split('#')[-1] if self.date: d['date'] = self.date.text if self.description: d['description'] = self.description.text if self.format: d['format'] = self.format.text if self.identifier: d['identifiers'] = [('google_id', self.identifier[0].text)] for x in self.identifier[1:]: l = x.text.split(':') # should we lower the case of the ids? d['identifiers'].append((l[0], ':'.join(l[1:]))) if self.GetInfoLink(): d['info'] = self.GetInfoLink().href if self.GetPreviewLink(): d['preview'] = self.GetPreviewLink().href if self.publisher: d['publishers'] = [x.text for x in self.publisher] if self.rating: d['rating'] = self.rating.value if self.review: d['review'] = self.review.text if self.subject: d['subjects'] = [x.text for x in self.subject] if self.GetThumbnailLink(): d['thumbnail'] = self.GetThumbnailLink().href if self.dc_title: d['title'] = ' '.join([x.text for x in self.dc_title]) if self.viewability: d['viewability'] = self.viewability.value.split('#')[-1] return d def __init__(self, creator=None, date=None, description=None, format=None, author=None, identifier=None, publisher=None, subject=None, dc_title=None, viewability=None, embeddability=None, review=None, rating=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, title=None, control=None, updated=None, text=None, extension_elements=None, extension_attributes=None): self.creator = creator self.date = date self.description = description self.format = format self.identifier = identifier self.publisher = publisher self.subject = subject self.dc_title = dc_title or [] self.viewability = viewability self.embeddability = embeddability self.review = review self.rating = rating gdata.GDataEntry.__init__(self, author=author, category=category, content=content, contributor=contributor, atom_id=atom_id, link=link, published=published, rights=rights, source=source, summary=summary, title=title, control=control, updated=updated, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) def GetThumbnailLink(self): """Returns the atom.Link object representing the thumbnail URI.""" for i in self.link: if i.rel == THUMBNAIL_REL: return i def GetInfoLink(self): """ Returns the atom.Link object representing the human-readable info URI. """ for i in self.link: if i.rel == INFO_REL: return i def GetPreviewLink(self): """Returns the atom.Link object representing the preview URI.""" for i in self.link: if i.rel == PREVIEW_REL: return i def GetAnnotationLink(self): """ Returns the atom.Link object representing the Annotation URI. Note that the use of www.books in the href of this link seems to make this information useless. Using books.service.ANNOTATION_FEED and BOOK_SERVER to construct your URI seems to work better. """ for i in self.link: if i.rel == ANNOTATION_REL: return i def set_rating(self, value): """Set user's rating. Must be an integral string between 1 nad 5""" assert (value in ('1','2','3','4','5')) if not isinstance(self.rating, Rating): self.rating = Rating() self.rating.value = value def set_review(self, text, type='text', lang='en'): """Set user's review text""" self.review = Review(text=text, type=type, lang=lang) def get_label(self): """Get users label for the item as a string""" for i in self.category: if i.scheme == LABEL_SCHEME: return i.term def set_label(self, term): """Clear pre-existing label for the item and set term as the label.""" self.remove_label() self.category.append(atom.Category(term=term, scheme=LABEL_SCHEME)) def remove_label(self): """Clear the user's label for the item""" ln = len(self.category) for i, j in enumerate(self.category[::-1]): if j.scheme == LABEL_SCHEME: del(self.category[ln-1-i]) def clean_annotations(self): """Clear all annotations from an item. Useful for taking an item from another user's library/annotation feed and adding it to the authenticated user's library without adopting annotations.""" self.remove_label() self.review = None self.rating = None def get_google_id(self): """Get Google's ID of the item.""" return self.id.text.split('/')[-1] class BookFeed(_AtomFromString, gdata.GDataFeed): """Represents a feed of entries from a search.""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _children['{%s}%s' % (Book._namespace, Book._tag)] = (Book._tag, [Book]) if __name__ == '__main__': import doctest doctest.testfile('datamodels.txt')
apache-2.0
7,942,596,538,569,523,000
38.179704
80
0.642402
false
jjmleiro/hue
desktop/core/ext-py/Django-1.6.10/tests/save_delete_hooks/models.py
130
1035
""" 13. Adding hooks before/after saving and deleting To execute arbitrary code around ``save()`` and ``delete()``, just subclass the methods. """ from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) def __init__(self, *args, **kwargs): super(Person, self).__init__(*args, **kwargs) self.data = [] def __str__(self): return "%s %s" % (self.first_name, self.last_name) def save(self, *args, **kwargs): self.data.append("Before save") # Call the "real" save() method super(Person, self).save(*args, **kwargs) self.data.append("After save") def delete(self): self.data.append("Before deletion") # Call the "real" delete() method super(Person, self).delete() self.data.append("After deletion")
apache-2.0
5,388,654,497,079,564,000
28.571429
75
0.635749
false
mcardillo55/django
tests/check_framework/test_templates.py
288
1403
from copy import deepcopy from django.core.checks.templates import E001 from django.test import SimpleTestCase from django.test.utils import override_settings class CheckTemplateSettingsAppDirsTest(SimpleTestCase): TEMPLATES_APP_DIRS_AND_LOADERS = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'loaders': ['django.template.loaders.filesystem.Loader'], }, }, ] @property def func(self): from django.core.checks.templates import check_setting_app_dirs_loaders return check_setting_app_dirs_loaders @override_settings(TEMPLATES=TEMPLATES_APP_DIRS_AND_LOADERS) def test_app_dirs_and_loaders(self): """ Error if template loaders are specified and APP_DIRS is True. """ self.assertEqual(self.func(None), [E001]) def test_app_dirs_removed(self): TEMPLATES = deepcopy(self.TEMPLATES_APP_DIRS_AND_LOADERS) del TEMPLATES[0]['APP_DIRS'] with self.settings(TEMPLATES=TEMPLATES): self.assertEqual(self.func(None), []) def test_loaders_removed(self): TEMPLATES = deepcopy(self.TEMPLATES_APP_DIRS_AND_LOADERS) del TEMPLATES[0]['OPTIONS']['loaders'] with self.settings(TEMPLATES=TEMPLATES): self.assertEqual(self.func(None), [])
bsd-3-clause
1,601,499,405,735,537,200
33.219512
79
0.64861
false
kasioumis/invenio
invenio/modules/documentation/views.py
1
3579
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2013, 2014 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Documentation Flask Blueprint.""" import os from flask import render_template, current_app, abort, url_for, Blueprint from flask.helpers import send_from_directory from werkzeug.utils import cached_property, import_string from sphinx.websupport import WebSupport from sphinx.websupport.errors import DocumentNotFoundError from invenio.base.globals import cfg from invenio.base.i18n import _ from flask.ext.breadcrumbs import (default_breadcrumb_root, register_breadcrumb, current_breadcrumbs) from flask.ext.menu import register_menu class DocsBlueprint(Blueprint): """Wrap blueprint with Sphinx ``WebSupport``.""" @cached_property def documentation_package(self): """Return documentation package.""" try: invenio_docs = import_string(cfg['DOCUMENTATION_PACKAGE']) except ImportError: import docs as invenio_docs return invenio_docs @cached_property def support(self): """Return an instance of Sphinx ``WebSupport``.""" builddir = os.path.abspath(os.path.join( current_app.instance_path, 'docs')) return WebSupport( srcdir=self.documentation_package.__path__[0], builddir=builddir, staticroot=os.path.join(blueprint.url_prefix, 'static'), docroot=blueprint.url_prefix ) def send_static_file(self, filename): """Return static file.""" try: return super(self.__class__, self).send_static_file(filename) except: cache_timeout = self.get_send_file_max_age(filename) return send_from_directory( os.path.join(current_app.instance_path, "docs", "static"), filename, cache_timeout=cache_timeout) blueprint = DocsBlueprint('documentation', __name__, url_prefix="/documentation", template_folder='templates', static_folder='static') default_breadcrumb_root(blueprint, '.documentation') @blueprint.route('/', strict_slashes=True) @blueprint.route('/<path:docname>') @register_menu(blueprint, 'main.documentation', _('Help'), order=99) @register_breadcrumb(blueprint, '.', _('Help')) def index(docname=None): """Render documentation page.""" try: document = blueprint.support.get_document( docname or cfg["DOCUMENTATION_INDEX"]) except DocumentNotFoundError: abort(404) additional_breadcrumbs = [{'text': document['title'], 'url': url_for('.index', docname=docname)}] return render_template( 'documentation/index.html', document=document, breadcrumbs=current_breadcrumbs + additional_breadcrumbs)
gpl-2.0
9,194,547,294,458,207,000
35.520408
78
0.657726
false
crosswalk-project/blink-crosswalk-efl
Source/devtools/scripts/concatenate_module_scripts.py
11
2413
#!/usr/bin/env python # # Copyright 2014 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. """ Concatenates module scripts based on the module.json descriptor. Optionally, minifies the result using rjsmin. """ from cStringIO import StringIO from os import path import os import re import sys try: import simplejson as json except ImportError: import json rjsmin_path = path.abspath(path.join( path.dirname(__file__), '..', '..', 'build', 'scripts')) sys.path.append(rjsmin_path) import rjsmin def read_file(filename): with open(path.normpath(filename), 'rt') as file: return file.read() def write_file(filename, content): # This is here to avoid overwriting source tree files due to hard links. if path.exists(filename): os.remove(filename) with open(filename, 'wt') as file: file.write(content) def concatenate_scripts(file_names, module_dir, output_dir, output): for file_name in file_names: output.write('/* %s */\n' % file_name) file_path = path.join(module_dir, file_name) # This allows to also concatenate generated files found in output_dir. if not path.isfile(file_path): file_path = path.join(output_dir, path.basename(module_dir), file_name) output.write(read_file(file_path)) output.write(';') def main(argv): if len(argv) < 3: print('Usage: %s module_json output_file no_minify' % argv[0]) return 1 module_json_file_name = argv[1] output_file_name = argv[2] no_minify = len(argv) > 3 and argv[3] module_dir = path.dirname(module_json_file_name) output = StringIO() descriptor = None try: descriptor = json.loads(read_file(module_json_file_name)) except: print 'ERROR: Failed to load JSON from ' + module_json_file_name raise # pylint: disable=E1103 scripts = descriptor.get('scripts') assert(scripts) output_root_dir = path.join(path.dirname(output_file_name), '..') concatenate_scripts(scripts, module_dir, output_root_dir, output) output_script = output.getvalue() output.close() write_file(output_file_name, output_script if no_minify else rjsmin.jsmin(output_script)) if __name__ == '__main__': sys.exit(main(sys.argv))
bsd-3-clause
-1,551,874,067,306,360,800
26.735632
93
0.654787
false
40323155/2016springcd_aG6
static/plugin/render_math/pelican_mathjax_markdown_extension.py
348
6929
# -*- coding: utf-8 -*- """ Pelican Mathjax Markdown Extension ================================== An extension for the Python Markdown module that enables the Pelican python blog to process mathjax. This extension gives Pelican the ability to use Mathjax as a "first class citizen" of the blog """ import markdown from markdown.util import etree from markdown.util import AtomicString class PelicanMathJaxPattern(markdown.inlinepatterns.Pattern): """Inline markdown processing that matches mathjax""" def __init__(self, pelican_mathjax_extension, tag, pattern): super(PelicanMathJaxPattern,self).__init__(pattern) self.math_tag_class = pelican_mathjax_extension.getConfig('math_tag_class') self.pelican_mathjax_extension = pelican_mathjax_extension self.tag = tag def handleMatch(self, m): node = markdown.util.etree.Element(self.tag) node.set('class', self.math_tag_class) prefix = '\\(' if m.group('prefix') == '$' else m.group('prefix') suffix = '\\)' if m.group('suffix') == '$' else m.group('suffix') node.text = markdown.util.AtomicString(prefix + m.group('math') + suffix) # If mathjax was successfully matched, then JavaScript needs to be added # for rendering. The boolean below indicates this self.pelican_mathjax_extension.mathjax_needed = True return node class PelicanMathJaxCorrectDisplayMath(markdown.treeprocessors.Treeprocessor): """Corrects invalid html that results from a <div> being put inside a <p> for displayed math""" def __init__(self, pelican_mathjax_extension): self.pelican_mathjax_extension = pelican_mathjax_extension def correct_html(self, root, children, div_math, insert_idx, text): """Separates out <div class="math"> from the parent tag <p>. Anything in between is put into its own parent tag of <p>""" current_idx = 0 for idx in div_math: el = markdown.util.etree.Element('p') el.text = text el.extend(children[current_idx:idx]) # Test to ensure that empty <p> is not inserted if len(el) != 0 or (el.text and not el.text.isspace()): root.insert(insert_idx, el) insert_idx += 1 text = children[idx].tail children[idx].tail = None root.insert(insert_idx, children[idx]) insert_idx += 1 current_idx = idx+1 el = markdown.util.etree.Element('p') el.text = text el.extend(children[current_idx:]) if len(el) != 0 or (el.text and not el.text.isspace()): root.insert(insert_idx, el) def run(self, root): """Searches for <div class="math"> that are children in <p> tags and corrects the invalid HTML that results""" math_tag_class = self.pelican_mathjax_extension.getConfig('math_tag_class') for parent in root: div_math = [] children = list(parent) for div in parent.findall('div'): if div.get('class') == math_tag_class: div_math.append(children.index(div)) # Do not process further if no displayed math has been found if not div_math: continue insert_idx = list(root).index(parent) self.correct_html(root, children, div_math, insert_idx, parent.text) root.remove(parent) # Parent must be removed last for correct insertion index return root class PelicanMathJaxAddJavaScript(markdown.treeprocessors.Treeprocessor): """Tree Processor for adding Mathjax JavaScript to the blog""" def __init__(self, pelican_mathjax_extension): self.pelican_mathjax_extension = pelican_mathjax_extension def run(self, root): # If no mathjax was present, then exit if (not self.pelican_mathjax_extension.mathjax_needed): return root # Add the mathjax script to the html document mathjax_script = etree.Element('script') mathjax_script.set('type','text/javascript') mathjax_script.text = AtomicString(self.pelican_mathjax_extension.getConfig('mathjax_script')) root.append(mathjax_script) # Reset the boolean switch to false so that script is only added # to other pages if needed self.pelican_mathjax_extension.mathjax_needed = False return root class PelicanMathJaxExtension(markdown.Extension): """A markdown extension enabling mathjax processing in Markdown for Pelican""" def __init__(self, config): try: # Needed for markdown versions >= 2.5 self.config['mathjax_script'] = ['', 'Mathjax JavaScript script'] self.config['math_tag_class'] = ['math', 'The class of the tag in which mathematics is wrapped'] self.config['auto_insert'] = [True, 'Determines if mathjax script is automatically inserted into content'] super(PelicanMathJaxExtension,self).__init__(**config) except AttributeError: # Markdown versions < 2.5 config['mathjax_script'] = [config['mathjax_script'], 'Mathjax JavaScript script'] config['math_tag_class'] = [config['math_tag_class'], 'The class of the tag in which mathematic is wrapped'] config['auto_insert'] = [config['auto_insert'], 'Determines if mathjax script is automatically inserted into content'] super(PelicanMathJaxExtension,self).__init__(config) # Used as a flag to determine if javascript # needs to be injected into a document self.mathjax_needed = False def extendMarkdown(self, md, md_globals): # Regex to detect mathjax mathjax_inline_regex = r'(?P<prefix>\$)(?P<math>.+?)(?P<suffix>(?<!\s)\2)' mathjax_display_regex = r'(?P<prefix>\$\$|\\begin\{(.+?)\})(?P<math>.+?)(?P<suffix>\2|\\end\{\3\})' # Process mathjax before escapes are processed since escape processing will # intefer with mathjax. The order in which the displayed and inlined math # is registered below matters md.inlinePatterns.add('mathjax_displayed', PelicanMathJaxPattern(self, 'div', mathjax_display_regex), '<escape') md.inlinePatterns.add('mathjax_inlined', PelicanMathJaxPattern(self, 'span', mathjax_inline_regex), '<escape') # Correct the invalid HTML that results from teh displayed math (<div> tag within a <p> tag) md.treeprocessors.add('mathjax_correctdisplayedmath', PelicanMathJaxCorrectDisplayMath(self), '>inline') # If necessary, add the JavaScript Mathjax library to the document. This must # be last in the ordered dict (hence it is given the position '_end') if self.getConfig('auto_insert'): md.treeprocessors.add('mathjax_addjavascript', PelicanMathJaxAddJavaScript(self), '_end')
agpl-3.0
2,092,622,600,191,289,000
42.85443
130
0.641362
false
aman-iitj/scipy
scipy/ndimage/__init__.py
46
5436
""" ========================================================= Multi-dimensional image processing (:mod:`scipy.ndimage`) ========================================================= .. currentmodule:: scipy.ndimage This package contains various functions for multi-dimensional image processing. Filters :mod:`scipy.ndimage.filters` ==================================== .. module:: scipy.ndimage.filters .. autosummary:: :toctree: generated/ convolve - Multi-dimensional convolution convolve1d - 1-D convolution along the given axis correlate - Multi-dimensional correlation correlate1d - 1-D correlation along the given axis gaussian_filter gaussian_filter1d gaussian_gradient_magnitude gaussian_laplace generic_filter - Multi-dimensional filter using a given function generic_filter1d - 1-D generic filter along the given axis generic_gradient_magnitude generic_laplace laplace - n-D Laplace filter based on approximate second derivatives maximum_filter maximum_filter1d median_filter - Calculates a multi-dimensional median filter minimum_filter minimum_filter1d percentile_filter - Calculates a multi-dimensional percentile filter prewitt rank_filter - Calculates a multi-dimensional rank filter sobel uniform_filter - Multi-dimensional uniform filter uniform_filter1d - 1-D uniform filter along the given axis Fourier filters :mod:`scipy.ndimage.fourier` ============================================ .. module:: scipy.ndimage.fourier .. autosummary:: :toctree: generated/ fourier_ellipsoid fourier_gaussian fourier_shift fourier_uniform Interpolation :mod:`scipy.ndimage.interpolation` ================================================ .. module:: scipy.ndimage.interpolation .. autosummary:: :toctree: generated/ affine_transform - Apply an affine transformation geometric_transform - Apply an arbritrary geometric transform map_coordinates - Map input array to new coordinates by interpolation rotate - Rotate an array shift - Shift an array spline_filter spline_filter1d zoom - Zoom an array Measurements :mod:`scipy.ndimage.measurements` ============================================== .. module:: scipy.ndimage.measurements .. autosummary:: :toctree: generated/ center_of_mass - The center of mass of the values of an array at labels extrema - Min's and max's of an array at labels, with their positions find_objects - Find objects in a labeled array histogram - Histogram of the values of an array, optionally at labels label - Label features in an array labeled_comprehension maximum maximum_position mean - Mean of the values of an array at labels minimum minimum_position standard_deviation - Standard deviation of an n-D image array sum - Sum of the values of the array variance - Variance of the values of an n-D image array watershed_ift Morphology :mod:`scipy.ndimage.morphology` ========================================== .. module:: scipy.ndimage.morphology .. autosummary:: :toctree: generated/ binary_closing binary_dilation binary_erosion binary_fill_holes binary_hit_or_miss binary_opening binary_propagation black_tophat distance_transform_bf distance_transform_cdt distance_transform_edt generate_binary_structure grey_closing grey_dilation grey_erosion grey_opening iterate_structure morphological_gradient morphological_laplace white_tophat Utility ======= .. currentmodule:: scipy.ndimage .. autosummary:: :toctree: generated/ imread - Load an image from a file """ # Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import division, print_function, absolute_import from .filters import * from .fourier import * from .interpolation import * from .measurements import * from .morphology import * from .io import * __version__ = '2.0' __all__ = [s for s in dir() if not s.startswith('_')] from numpy.testing import Tester test = Tester().test
bsd-3-clause
-2,567,934,379,819,761,000
28.704918
74
0.702355
false
JackDandy/SickGear
lib/guessit/transfo/guess_weak_episodes_rexps.py
21
2127
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2012 Nicolas Wack <wackou@gmail.com> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # GuessIt 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 # Lesser GNU General Public License for more details. # # You should have received a copy of the Lesser GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from __future__ import unicode_literals from guessit import Guess from guessit.transfo import SingleNodeGuesser from guessit.patterns import weak_episode_rexps import re import logging log = logging.getLogger(__name__) def guess_weak_episodes_rexps(string, node): if 'episodeNumber' in node.root.info: return None, None for rexp, span_adjust in weak_episode_rexps: match = re.search(rexp, string, re.IGNORECASE) if match: metadata = match.groupdict() span = (match.start() + span_adjust[0], match.end() + span_adjust[1]) epnum = int(metadata['episodeNumber']) if epnum > 100: season, epnum = epnum // 100, epnum % 100 # episodes which have a season > 25 are most likely errors # (Simpsons is at 23!) if season > 25: continue return Guess({ 'season': season, 'episodeNumber': epnum }, confidence=0.6), span else: return Guess(metadata, confidence=0.3), span return None, None guess_weak_episodes_rexps.use_node = True def process(mtree): SingleNodeGuesser(guess_weak_episodes_rexps, 0.6, log).process(mtree)
gpl-3.0
7,319,974,327,149,637,000
33.306452
74
0.643159
false
hsu/chrono
src/demos/trackVehicle/validationPlots_test_M113.py
5
4229
# -*- coding: utf-8 -*- """ Created on Wed May 06 11:00:53 2015 @author: newJustin """ import ChronoTrack_pandas as CT import pylab as py if __name__ == '__main__': # logger import logging as lg lg.basicConfig(fileName = 'logFile.log', level=lg.WARN, format='%(message)s') # default font size import matplotlib font = {'size' : 14} matplotlib.rc('font', **font) # ********************************************************************** # =============== USER INPUT ======================================= # data dir, end w/ '/' # data_dir = 'D:/Chrono_github_Build/bin/outdata_M113/' data_dir = 'E:/Chrono_github_Build/bin/outdata_M113/' ''' # list of data files to plot chassis = 'M113_chassis.csv' gearSubsys = 'M113_Side0_gear.csv' idlerSubsys = 'M113_Side0_idler.csv' # ptrainSubsys = 'test_driveChain_ptrain.csv' shoe0 = 'M113_Side0_shoe0.csv' ''' chassis = 'M113_400_200__chassis.csv' gearSubsys = 'M113_400_200__Side0_gear.csv' idlerSubsys = 'M113_400_200__Side0_idler.csv' # ptrainSubsys = 'test_driveChain_ptrain.csv' shoe0 = 'M113_400_200__Side0_shoe0.csv' data_files = [data_dir + chassis, data_dir + gearSubsys, data_dir + idlerSubsys, data_dir + shoe0] handle_list = ['chassis','gear','idler','shoe0'] # handle_list = ['Gear','idler','ptrain','shoe0','gearCV','idlerCV','rollerCV','gearContact','shoeGearContact'] ''' gearCV = 'test_driveChain_GearCV.csv' idlerCV = 'test_driveChain_idler0CV.csv' rollerCV = 'test_driveChain_roller0CV.csv' gearContact = 'test_driveChain_gearContact.csv' shoeGearContact = 'test_driveChain_shoe0GearContact.csv' ''' # data_files = [data_dir + gearSubsys, data_dir + idlerSubsys, data_dir + ptrainSubsys, data_dir + shoe0, data_dir + gearCV, data_dir + idlerCV, data_dir + rollerCV, data_dir + gearContact, data_dir+shoeGearContact] # handle_list = ['Gear','idler','ptrain','shoe0','gearCV','idlerCV','rollerCV','gearContact','shoeGearContact'] # list of data files for gear/pin comparison plots # Primitive gear geometry ''' gear = 'driveChain_P_gear.csv' gearContact = 'driveChain_P_gearContact.csv' shoe = 'driveChain_P_shoe0.csv' shoeContact = 'driveChain_P_shoe0GearContact.csv' ptrain = 'driveChain_P_ptrain.csv' # Collision Callback gear geometry gear = 'driveChain_CC_gear.csv' gearContact = 'driveChain_CC_gearContact.csv' shoe = 'driveChain_CC_shoe0.csv' shoeContact = 'driveChain_CC_shoe0GearContact.csv' ptrain = 'driveChain_CC_ptrain.csv' data_files = [data_dir+gear, data_dir+gearContact, data_dir+shoe, data_dir+shoeContact, data_dir+ptrain] handle_list = ['Gear','gearContact','shoe0','shoeGearContact','ptrain'] ''' # construct the panda class for the DriveChain, file list and list of legend M113_Chain0 = CT.ChronoTrack_pandas(data_files, handle_list) # set the time limits. tmin = -1 will plot the entire time range tmin = 1.0 tmax = 8.0 #0) plot the chassis M113_Chain0.plot_chassis(tmin, tmax) # 1) plot the gear body info M113_Chain0.plot_gear(tmin, tmax) # 2) plot idler body info, tensioner force M113_Chain0.plot_idler(tmin,tmax) ''' # 3) plot powertrain info M113_Chain0.plot_ptrain() ''' # 4) plot shoe 0 body info, and pin 0 force/torque M113_Chain0.plot_shoe(tmin,tmax) ''' # 5) plot gear Constraint Violations M113_Chain0.plot_gearCV(tmin,tmax) # 6) plot idler Constraint Violations M113_Chain0.plot_idlerCV(tmin,tmax) # 7) plot roller Constraint Violations M113_Chain0.plot_rollerCV(tmin,tmax) # 8) from the contact report callback function, gear contact info M113_Chain0.plot_gearContactInfo(tmin,tmax) # 9) from shoe-gear report callback function, contact info M113_Chain0.plot_shoeGearContactInfo(tmin,tmax) ''' # 10) track shoe trajectory: rel-X vs. rel-Y M113_Chain0.plot_trajectory(tmin,tmax) py.show()
bsd-3-clause
-807,935,552,402,286,800
31.290076
219
0.616458
false
mrknow/filmkodi
plugin.video.fanfilm/resources/lib/resolvers/putstream.py
2
1131
# -*- coding: utf-8 -*- ''' FanFilm Add-on Copyright (C) 2015 lambda 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 from resources.lib.libraries import client def resolve(url): try: url = url.replace('/embed-', '/') url = re.compile('//.+?/([\w]+)').findall(url)[0] url = 'http://putstream.com/embed-%s.html' % url result = client.request(url) url = re.compile('file *: *"(http.+?)"').findall(result)[-1] return url except: return
apache-2.0
8,110,821,232,460,552,000
28.763158
73
0.654288
false
joewashear007/ScrappyDoo
copy.py
1
3382
import os import shutil import zipfile import fnmatch import uuid def main(): kits = findAll(".") for kit in kits: print("* ", kit, " -> ", kits[kit]) print() print() print("Starting extraction:") print("------------------------------------------") extractKits(kits) def findAll(dir): print() print("All zip files:") print("---------------------------") kits = {} files = os.listdir(".") for file in files: if file.endswith(".zip"): kits[file] = getType(file) return kits def getType(file): if "-pp" in file: return "paper" if "-ap" in file: return "alpha" if "-ep" in file: return "embellishment" options = {1: "embellishment", 2: "alpha", 3: "paper", 4:"other"} #DEBUG: return options[1]; goodInput = False while not goodInput: print() print("File: ", file) print(" 1) Embellishment") print(" 2) Alpha") print(" 3) Paper") print(" 4) Other") action = input("Please Enter the Number (default = 1):") if action is "": return options[1]; if action.isdigit(): actionNum = int(action) if actionNum > 0 and actionNum < len(options)+1: return options[actionNum] def extractKits(kits): tmpDir = "./tmp"; kitNames = {} x = 0 for kit in kits: # kit = next(iter(kits.keys())) x = x + 1 print() print() print() print("Extracting: ", kit, " ( ", x, " of ", len(kits), ")") kitStr = kit.rsplit("-", 1)[0] print("Kit Name: ", kitStr) if kitStr in kitNames: name = input("Please Enter Kit Name (default = "+kitNames[kitStr]+"): ") name = name or kitNames[kitStr] else: name = input("Please Enter Kit Name: ") kitNames[kitStr] =name if os.path.exists(tmpDir): shutil.rmtree(tmpDir) else: os.makedirs(tmpDir) if not os.path.exists("./" + name): os.makedirs("./" + name) kitzip = zipfile.ZipFile("./" + kit) kitzip.extractall(tmpDir) images = copyExtractedFiles("./" + name +"/") createManifest(kit, name, images, kits[kit]) def copyExtractedFiles(dest): matches = [] filenames = [".png", ".jpg"] for rootpath, subdirs, files in os.walk("./tmp"): for filename in files: if os.path.splitext(filename)[1].lower() in filenames: # print(os.path.join(rootpath, filename).replace('\\','/')) shutil.move(os.path.join(rootpath, filename).replace('\\','/'), dest+filename) matches.append(dest + filename) return matches def createManifest(kit, name, images, type): manifest = [] manifest.append('<Manifest vendorid="0" vendorpackageid="0" maintaincopyright="True" dpi="300">') manifest.append('<Groups />') manifest.append('<Entries>') for image in images: manifest.append('<Image ID="'+str(uuid.uuid4())+'" Name="'+image+'" Group="Embellishment" />') manifest.append('</Entries>') manifest.append('</Manifest>') with open('./'+name+'/package.manifestx', 'w') as f: for line in manifest: f.write(line + os.linesep) if __name__ == "__main__": main()
mit
7,577,268,462,791,354,000
27.905983
102
0.527794
false
sasukeh/neutron
neutron/api/rpc/callbacks/resource_manager.py
32
4710
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import abc import collections from oslo_log import log as logging import six from neutron.api.rpc.callbacks import exceptions as rpc_exc from neutron.api.rpc.callbacks import resources from neutron.callbacks import exceptions LOG = logging.getLogger(__name__) # TODO(QoS): split the registry/resources_rpc modules into two separate things: # one for pull and one for push APIs def _validate_resource_type(resource_type): if not resources.is_valid_resource_type(resource_type): raise exceptions.Invalid(element='resource', value=resource_type) @six.add_metaclass(abc.ABCMeta) class ResourceCallbacksManager(object): """A callback system that allows information providers in a loose manner. """ # This hook is to allow tests to get new objects for the class _singleton = True def __new__(cls, *args, **kwargs): if not cls._singleton: return super(ResourceCallbacksManager, cls).__new__(cls) if not hasattr(cls, '_instance'): cls._instance = super(ResourceCallbacksManager, cls).__new__(cls) return cls._instance @abc.abstractmethod def _add_callback(self, callback, resource_type): pass @abc.abstractmethod def _delete_callback(self, callback, resource_type): pass def register(self, callback, resource_type): """Register a callback for a resource type. :param callback: the callback. It must raise or return NeutronObject. :param resource_type: must be a valid resource type. """ LOG.debug("Registering callback for %s", resource_type) _validate_resource_type(resource_type) self._add_callback(callback, resource_type) def unregister(self, callback, resource_type): """Unregister callback from the registry. :param callback: the callback. :param resource_type: must be a valid resource type. """ LOG.debug("Unregistering callback for %s", resource_type) _validate_resource_type(resource_type) self._delete_callback(callback, resource_type) @abc.abstractmethod def clear(self): """Brings the manager to a clean state.""" def get_subscribed_types(self): return list(self._callbacks.keys()) class ProducerResourceCallbacksManager(ResourceCallbacksManager): _callbacks = dict() def _add_callback(self, callback, resource_type): if resource_type in self._callbacks: raise rpc_exc.CallbacksMaxLimitReached(resource_type=resource_type) self._callbacks[resource_type] = callback def _delete_callback(self, callback, resource_type): try: del self._callbacks[resource_type] except KeyError: raise rpc_exc.CallbackNotFound(resource_type=resource_type) def clear(self): self._callbacks = dict() def get_callback(self, resource_type): _validate_resource_type(resource_type) try: return self._callbacks[resource_type] except KeyError: raise rpc_exc.CallbackNotFound(resource_type=resource_type) class ConsumerResourceCallbacksManager(ResourceCallbacksManager): _callbacks = collections.defaultdict(set) def _add_callback(self, callback, resource_type): self._callbacks[resource_type].add(callback) def _delete_callback(self, callback, resource_type): try: self._callbacks[resource_type].remove(callback) if not self._callbacks[resource_type]: del self._callbacks[resource_type] except KeyError: raise rpc_exc.CallbackNotFound(resource_type=resource_type) def clear(self): self._callbacks = collections.defaultdict(set) def get_callbacks(self, resource_type): """Return the callback if found, None otherwise. :param resource_type: must be a valid resource type. """ _validate_resource_type(resource_type) callbacks = self._callbacks[resource_type] if not callbacks: raise rpc_exc.CallbackNotFound(resource_type=resource_type) return callbacks
apache-2.0
-3,525,136,190,414,913,000
32.884892
79
0.679193
false
listamilton/supermilton.repository
script.module.youtube.dl/lib/youtube_dl/extractor/moniker.py
66
3951
# coding: utf-8 from __future__ import unicode_literals import os.path import re from .common import InfoExtractor from ..utils import ( ExtractorError, remove_start, sanitized_Request, urlencode_postdata, ) class MonikerIE(InfoExtractor): IE_DESC = 'allmyvideos.net and vidspot.net' _VALID_URL = r'https?://(?:www\.)?(?:allmyvideos|vidspot)\.net/(?:(?:2|v)/v-)?(?P<id>[a-zA-Z0-9_-]+)' _TESTS = [{ 'url': 'http://allmyvideos.net/jih3nce3x6wn', 'md5': '710883dee1bfc370ecf9fa6a89307c88', 'info_dict': { 'id': 'jih3nce3x6wn', 'ext': 'mp4', 'title': 'youtube-dl test video', }, }, { 'url': 'http://allmyvideos.net/embed-jih3nce3x6wn', 'md5': '710883dee1bfc370ecf9fa6a89307c88', 'info_dict': { 'id': 'jih3nce3x6wn', 'ext': 'mp4', 'title': 'youtube-dl test video', }, }, { 'url': 'http://vidspot.net/l2ngsmhs8ci5', 'md5': '710883dee1bfc370ecf9fa6a89307c88', 'info_dict': { 'id': 'l2ngsmhs8ci5', 'ext': 'mp4', 'title': 'youtube-dl test video', }, }, { 'url': 'https://www.vidspot.net/l2ngsmhs8ci5', 'only_matching': True, }, { 'url': 'http://vidspot.net/2/v-ywDf99', 'md5': '5f8254ce12df30479428b0152fb8e7ba', 'info_dict': { 'id': 'ywDf99', 'ext': 'mp4', 'title': 'IL FAIT LE MALIN EN PORSHE CAYENNE ( mais pas pour longtemps)', 'description': 'IL FAIT LE MALIN EN PORSHE CAYENNE.', }, }, { 'url': 'http://allmyvideos.net/v/v-HXZm5t', 'only_matching': True, }] def _real_extract(self, url): orig_video_id = self._match_id(url) video_id = remove_start(orig_video_id, 'embed-') url = url.replace(orig_video_id, video_id) assert re.match(self._VALID_URL, url) is not None orig_webpage = self._download_webpage(url, video_id) if '>File Not Found<' in orig_webpage: raise ExtractorError('Video %s does not exist' % video_id, expected=True) error = self._search_regex( r'class="err">([^<]+)<', orig_webpage, 'error', default=None) if error: raise ExtractorError( '%s returned error: %s' % (self.IE_NAME, error), expected=True) builtin_url = self._search_regex( r'<iframe[^>]+src=(["\'])(?P<url>.+?/builtin-.+?)\1', orig_webpage, 'builtin URL', default=None, group='url') if builtin_url: req = sanitized_Request(builtin_url) req.add_header('Referer', url) webpage = self._download_webpage(req, video_id, 'Downloading builtin page') title = self._og_search_title(orig_webpage).strip() description = self._og_search_description(orig_webpage).strip() else: fields = re.findall(r'type="hidden" name="(.+?)"\s* value="?(.+?)">', orig_webpage) data = dict(fields) post = urlencode_postdata(data) headers = { b'Content-Type': b'application/x-www-form-urlencoded', } req = sanitized_Request(url, post, headers) webpage = self._download_webpage( req, video_id, note='Downloading video page ...') title = os.path.splitext(data['fname'])[0] description = None # Could be several links with different quality links = re.findall(r'"file" : "?(.+?)",', webpage) # Assume the links are ordered in quality formats = [{ 'url': l, 'quality': i, } for i, l in enumerate(links)] self._sort_formats(formats) return { 'id': video_id, 'title': title, 'description': description, 'formats': formats, }
gpl-2.0
2,729,320,049,983,951,400
33.060345
105
0.529486
false
gohin/django
django/contrib/auth/management/commands/createsuperuser.py
65
7695
""" Management utility to create superusers. """ from __future__ import unicode_literals import getpass import sys from django.contrib.auth import get_user_model from django.contrib.auth.management import get_default_username from django.core import exceptions from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS from django.utils.encoding import force_str from django.utils.six.moves import input from django.utils.text import capfirst class NotRunningInTTYException(Exception): pass class Command(BaseCommand): help = 'Used to create a superuser.' def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) self.UserModel = get_user_model() self.username_field = self.UserModel._meta.get_field(self.UserModel.USERNAME_FIELD) def add_arguments(self, parser): parser.add_argument('--%s' % self.UserModel.USERNAME_FIELD, dest=self.UserModel.USERNAME_FIELD, default=None, help='Specifies the login for the superuser.') parser.add_argument('--noinput', action='store_false', dest='interactive', default=True, help=('Tells Django to NOT prompt the user for input of any kind. ' 'You must use --%s with --noinput, along with an option for ' 'any other required field. Superusers created with --noinput will ' ' not be able to log in until they\'re given a valid password.' % self.UserModel.USERNAME_FIELD)) parser.add_argument('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Specifies the database to use. Default is "default".') for field in self.UserModel.REQUIRED_FIELDS: parser.add_argument('--%s' % field, dest=field, default=None, help='Specifies the %s for the superuser.' % field) def execute(self, *args, **options): self.stdin = options.get('stdin', sys.stdin) # Used for testing return super(Command, self).execute(*args, **options) def handle(self, *args, **options): username = options.get(self.UserModel.USERNAME_FIELD) database = options.get('database') # If not provided, create the user with an unusable password password = None user_data = {} # Do quick and dirty validation if --noinput if not options['interactive']: try: if not username: raise CommandError("You must use --%s with --noinput." % self.UserModel.USERNAME_FIELD) username = self.username_field.clean(username, None) for field_name in self.UserModel.REQUIRED_FIELDS: if options.get(field_name): field = self.UserModel._meta.get_field(field_name) user_data[field_name] = field.clean(options[field_name], None) else: raise CommandError("You must use --%s with --noinput." % field_name) except exceptions.ValidationError as e: raise CommandError('; '.join(e.messages)) else: # Prompt for username/password, and any other required fields. # Enclose this whole thing in a try/except to catch # KeyboardInterrupt and exit gracefully. default_username = get_default_username() try: if hasattr(self.stdin, 'isatty') and not self.stdin.isatty(): raise NotRunningInTTYException("Not running in a TTY") # Get a username verbose_field_name = self.username_field.verbose_name while username is None: input_msg = capfirst(verbose_field_name) if default_username: input_msg += " (leave blank to use '%s')" % default_username username_rel = self.username_field.remote_field input_msg = force_str('%s%s: ' % ( input_msg, ' (%s.%s)' % ( username_rel.model._meta.object_name, username_rel.field_name ) if username_rel else '') ) username = self.get_input_data(self.username_field, input_msg, default_username) if not username: continue if self.username_field.unique: try: self.UserModel._default_manager.db_manager(database).get_by_natural_key(username) except self.UserModel.DoesNotExist: pass else: self.stderr.write("Error: That %s is already taken." % verbose_field_name) username = None for field_name in self.UserModel.REQUIRED_FIELDS: field = self.UserModel._meta.get_field(field_name) user_data[field_name] = options.get(field_name) while user_data[field_name] is None: message = force_str('%s%s: ' % ( capfirst(field.verbose_name), ' (%s.%s)' % ( field.remote_field.model._meta.object_name, field.remote_field.field_name, ) if field.remote_field else '', )) user_data[field_name] = self.get_input_data(field, message) # Get a password while password is None: if not password: password = getpass.getpass() password2 = getpass.getpass(force_str('Password (again): ')) if password != password2: self.stderr.write("Error: Your passwords didn't match.") password = None continue if password.strip() == '': self.stderr.write("Error: Blank passwords aren't allowed.") password = None continue except KeyboardInterrupt: self.stderr.write("\nOperation cancelled.") sys.exit(1) except NotRunningInTTYException: self.stdout.write( "Superuser creation skipped due to not running in a TTY. " "You can run `manage.py createsuperuser` in your project " "to create one manually." ) if username: user_data[self.UserModel.USERNAME_FIELD] = username user_data['password'] = password self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) if options['verbosity'] >= 1: self.stdout.write("Superuser created successfully.") def get_input_data(self, field, message, default=None): """ Override this method if you want to customize data inputs or validation exceptions. """ raw_value = input(message) if default and raw_value == '': raw_value = default try: val = field.clean(raw_value, None) except exceptions.ValidationError as e: self.stderr.write("Error: %s" % '; '.join(e.messages)) val = None return val
bsd-3-clause
6,320,757,852,442,747,000
43.738372
109
0.538532
false
wwright2/dcim3-angstrom1
sources/openembedded-core/scripts/pybootchartgui/pybootchartgui/samples.py
7
5537
# This file is part of pybootchartgui. # pybootchartgui 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. # pybootchartgui 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 pybootchartgui. If not, see <http://www.gnu.org/licenses/>. class DiskStatSample: def __init__(self, time): self.time = time self.diskdata = [0, 0, 0] def add_diskdata(self, new_diskdata): self.diskdata = [ a + b for a, b in zip(self.diskdata, new_diskdata) ] class CPUSample: def __init__(self, time, user, sys, io = 0.0, swap = 0.0): self.time = time self.user = user self.sys = sys self.io = io self.swap = swap @property def cpu(self): return self.user + self.sys def __str__(self): return str(self.time) + "\t" + str(self.user) + "\t" + \ str(self.sys) + "\t" + str(self.io) + "\t" + str (self.swap) class MemSample: used_values = ('MemTotal', 'MemFree', 'Buffers', 'Cached', 'SwapTotal', 'SwapFree',) def __init__(self, time): self.time = time self.records = {} def add_value(self, name, value): if name in MemSample.used_values: self.records[name] = value def valid(self): keys = self.records.keys() # discard incomplete samples return [v for v in MemSample.used_values if v not in keys] == [] class ProcessSample: def __init__(self, time, state, cpu_sample): self.time = time self.state = state self.cpu_sample = cpu_sample def __str__(self): return str(self.time) + "\t" + str(self.state) + "\t" + str(self.cpu_sample) class ProcessStats: def __init__(self, writer, process_map, sample_count, sample_period, start_time, end_time): self.process_map = process_map self.sample_count = sample_count self.sample_period = sample_period self.start_time = start_time self.end_time = end_time writer.info ("%d samples, avg. sample length %f" % (self.sample_count, self.sample_period)) writer.info ("process list size: %d" % len (self.process_map.values())) class Process: def __init__(self, writer, pid, cmd, ppid, start_time): self.writer = writer self.pid = pid self.cmd = cmd self.exe = cmd self.args = [] self.ppid = ppid self.start_time = start_time self.duration = 0 self.samples = [] self.parent = None self.child_list = [] self.active = None self.last_user_cpu_time = None self.last_sys_cpu_time = None self.last_cpu_ns = 0 self.last_blkio_delay_ns = 0 self.last_swapin_delay_ns = 0 # split this process' run - triggered by a name change def split(self, writer, pid, cmd, ppid, start_time): split = Process (writer, pid, cmd, ppid, start_time) split.last_cpu_ns = self.last_cpu_ns split.last_blkio_delay_ns = self.last_blkio_delay_ns split.last_swapin_delay_ns = self.last_swapin_delay_ns return split def __str__(self): return " ".join([str(self.pid), self.cmd, str(self.ppid), '[ ' + str(len(self.samples)) + ' samples ]' ]) def calc_stats(self, samplePeriod): if self.samples: firstSample = self.samples[0] lastSample = self.samples[-1] self.start_time = min(firstSample.time, self.start_time) self.duration = lastSample.time - self.start_time + samplePeriod activeCount = sum( [1 for sample in self.samples if sample.cpu_sample and sample.cpu_sample.sys + sample.cpu_sample.user + sample.cpu_sample.io > 0.0] ) activeCount = activeCount + sum( [1 for sample in self.samples if sample.state == 'D'] ) self.active = (activeCount>2) def calc_load(self, userCpu, sysCpu, interval): userCpuLoad = float(userCpu - self.last_user_cpu_time) / interval sysCpuLoad = float(sysCpu - self.last_sys_cpu_time) / interval cpuLoad = userCpuLoad + sysCpuLoad # normalize if cpuLoad > 1.0: userCpuLoad = userCpuLoad / cpuLoad sysCpuLoad = sysCpuLoad / cpuLoad return (userCpuLoad, sysCpuLoad) def set_parent(self, processMap): if self.ppid != None: self.parent = processMap.get (self.ppid) if self.parent == None and self.pid // 1000 > 1 and \ not (self.ppid == 2000 or self.pid == 2000): # kernel threads: ppid=2 self.writer.warn("Missing CONFIG_PROC_EVENTS: no parent for pid '%i' ('%s') with ppid '%i'" \ % (self.pid,self.cmd,self.ppid)) def get_end_time(self): return self.start_time + self.duration class DiskSample: def __init__(self, time, read, write, util): self.time = time self.read = read self.write = write self.util = util self.tput = read + write def __str__(self): return "\t".join([str(self.time), str(self.read), str(self.write), str(self.util)])
mit
4,583,296,552,943,260,700
35.668874
160
0.601409
false
rickerc/neutron_audit
neutron/plugins/nec/ofc_manager.py
9
9461
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 NEC Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # @author: Ryota MIBU # @author: Akihiro MOTOKI import netaddr from neutron.common import utils from neutron.openstack.common import log as logging from neutron.plugins.nec.common import config from neutron.plugins.nec.common import exceptions as nexc from neutron.plugins.nec.db import api as ndb from neutron.plugins.nec import drivers LOG = logging.getLogger(__name__) class OFCManager(object): """This class manages an OpenFlow Controller and map resources. This class manage an OpenFlow Controller (OFC) with a driver specified in a configuration of this plugin. This keeps mappings between IDs on Neutron and OFC for various entities such as Tenant, Network and Filter. A Port on OFC is identified by a switch ID 'datapath_id' and a port number 'port_no' of the switch. An ID named as 'ofc_*' is used to identify resource on OFC. """ def __init__(self): self.driver = drivers.get_driver(config.OFC.driver)(config.OFC) def _get_ofc_id(self, context, resource, neutron_id): return ndb.get_ofc_id_lookup_both(context.session, resource, neutron_id) def _exists_ofc_item(self, context, resource, neutron_id): return ndb.exists_ofc_item_lookup_both(context.session, resource, neutron_id) def _add_ofc_item(self, context, resource, neutron_id, ofc_id): # Ensure a new item is added to the new mapping table ndb.add_ofc_item(context.session, resource, neutron_id, ofc_id) def _del_ofc_item(self, context, resource, neutron_id): ndb.del_ofc_item_lookup_both(context.session, resource, neutron_id) def ensure_ofc_tenant(self, context, tenant_id): if not self.exists_ofc_tenant(context, tenant_id): self.create_ofc_tenant(context, tenant_id) def create_ofc_tenant(self, context, tenant_id): desc = "ID=%s at OpenStack." % tenant_id ofc_tenant_id = self.driver.create_tenant(desc, tenant_id) self._add_ofc_item(context, "ofc_tenant", tenant_id, ofc_tenant_id) def exists_ofc_tenant(self, context, tenant_id): return self._exists_ofc_item(context, "ofc_tenant", tenant_id) def delete_ofc_tenant(self, context, tenant_id): ofc_tenant_id = self._get_ofc_id(context, "ofc_tenant", tenant_id) ofc_tenant_id = self.driver.convert_ofc_tenant_id( context, ofc_tenant_id) self.driver.delete_tenant(ofc_tenant_id) self._del_ofc_item(context, "ofc_tenant", tenant_id) def create_ofc_network(self, context, tenant_id, network_id, network_name=None): ofc_tenant_id = self._get_ofc_id(context, "ofc_tenant", tenant_id) ofc_tenant_id = self.driver.convert_ofc_tenant_id( context, ofc_tenant_id) desc = "ID=%s Name=%s at Neutron." % (network_id, network_name) ofc_net_id = self.driver.create_network(ofc_tenant_id, desc, network_id) self._add_ofc_item(context, "ofc_network", network_id, ofc_net_id) def exists_ofc_network(self, context, network_id): return self._exists_ofc_item(context, "ofc_network", network_id) def delete_ofc_network(self, context, network_id, network): ofc_net_id = self._get_ofc_id(context, "ofc_network", network_id) ofc_net_id = self.driver.convert_ofc_network_id( context, ofc_net_id, network['tenant_id']) self.driver.delete_network(ofc_net_id) self._del_ofc_item(context, "ofc_network", network_id) def create_ofc_port(self, context, port_id, port): ofc_net_id = self._get_ofc_id(context, "ofc_network", port['network_id']) ofc_net_id = self.driver.convert_ofc_network_id( context, ofc_net_id, port['tenant_id']) portinfo = ndb.get_portinfo(context.session, port_id) if not portinfo: raise nexc.PortInfoNotFound(id=port_id) ofc_port_id = self.driver.create_port(ofc_net_id, portinfo, port_id) self._add_ofc_item(context, "ofc_port", port_id, ofc_port_id) def exists_ofc_port(self, context, port_id): return self._exists_ofc_item(context, "ofc_port", port_id) def delete_ofc_port(self, context, port_id, port): ofc_port_id = self._get_ofc_id(context, "ofc_port", port_id) ofc_port_id = self.driver.convert_ofc_port_id( context, ofc_port_id, port['tenant_id'], port['network_id']) self.driver.delete_port(ofc_port_id) self._del_ofc_item(context, "ofc_port", port_id) def create_ofc_packet_filter(self, context, filter_id, filter_dict): ofc_net_id = self._get_ofc_id(context, "ofc_network", filter_dict['network_id']) ofc_net_id = self.driver.convert_ofc_network_id( context, ofc_net_id, filter_dict['tenant_id']) in_port_id = filter_dict.get('in_port') portinfo = None if in_port_id: portinfo = ndb.get_portinfo(context.session, in_port_id) if not portinfo: raise nexc.PortInfoNotFound(id=in_port_id) ofc_pf_id = self.driver.create_filter(ofc_net_id, filter_dict, portinfo, filter_id) self._add_ofc_item(context, "ofc_packet_filter", filter_id, ofc_pf_id) def exists_ofc_packet_filter(self, context, filter_id): return self._exists_ofc_item(context, "ofc_packet_filter", filter_id) def delete_ofc_packet_filter(self, context, filter_id): ofc_pf_id = self._get_ofc_id(context, "ofc_packet_filter", filter_id) ofc_pf_id = self.driver.convert_ofc_filter_id(context, ofc_pf_id) self.driver.delete_filter(ofc_pf_id) self._del_ofc_item(context, "ofc_packet_filter", filter_id) def create_ofc_router(self, context, tenant_id, router_id, name=None): ofc_tenant_id = self._get_ofc_id(context, "ofc_tenant", tenant_id) ofc_tenant_id = self.driver.convert_ofc_tenant_id( context, ofc_tenant_id) desc = "ID=%s Name=%s at Neutron." % (router_id, name) ofc_router_id = self.driver.create_router(ofc_tenant_id, router_id, desc) self._add_ofc_item(context, "ofc_router", router_id, ofc_router_id) def exists_ofc_router(self, context, router_id): return self._exists_ofc_item(context, "ofc_router", router_id) def delete_ofc_router(self, context, router_id, router): ofc_router_id = self._get_ofc_id(context, "ofc_router", router_id) self.driver.delete_router(ofc_router_id) self._del_ofc_item(context, "ofc_router", router_id) def add_ofc_router_interface(self, context, router_id, port_id, port): # port must have the following fields: # network_id, cidr, ip_address, mac_address ofc_router_id = self._get_ofc_id(context, "ofc_router", router_id) ofc_net_id = self._get_ofc_id(context, "ofc_network", port['network_id']) ip_address = '%s/%s' % (port['ip_address'], netaddr.IPNetwork(port['cidr']).prefixlen) mac_address = port['mac_address'] ofc_inf_id = self.driver.add_router_interface( ofc_router_id, ofc_net_id, ip_address, mac_address) # Use port mapping table to maintain an interface of OFC router self._add_ofc_item(context, "ofc_port", port_id, ofc_inf_id) def delete_ofc_router_interface(self, context, router_id, port_id): # Use port mapping table to maintain an interface of OFC router ofc_inf_id = self._get_ofc_id(context, "ofc_port", port_id) self.driver.delete_router_interface(ofc_inf_id) self._del_ofc_item(context, "ofc_port", port_id) def update_ofc_router_route(self, context, router_id, new_routes): ofc_router_id = self._get_ofc_id(context, "ofc_router", router_id) ofc_routes = self.driver.list_router_routes(ofc_router_id) route_dict = {} cur_routes = [] for r in ofc_routes: key = ','.join((r['destination'], r['nexthop'])) route_dict[key] = r['id'] del r['id'] cur_routes.append(r) added, removed = utils.diff_list_of_dict(cur_routes, new_routes) for r in removed: key = ','.join((r['destination'], r['nexthop'])) route_id = route_dict[key] self.driver.delete_router_route(route_id) for r in added: self.driver.add_router_route(ofc_router_id, r['destination'], r['nexthop'])
apache-2.0
-5,019,626,671,642,997,000
45.377451
79
0.621499
false
vmobi-gogh/android_kernel_samsung_gogh
Documentation/networking/cxacru-cf.py
14668
1626
#!/usr/bin/env python # Copyright 2009 Simon Arlott # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; either version 2 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 59 # Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Usage: cxacru-cf.py < cxacru-cf.bin # Output: values string suitable for the sysfs adsl_config attribute # # Warning: cxacru-cf.bin with MD5 hash cdbac2689969d5ed5d4850f117702110 # contains mis-aligned values which will stop the modem from being able # to make a connection. If the first and last two bytes are removed then # the values become valid, but the modulation will be forced to ANSI # T1.413 only which may not be appropriate. # # The original binary format is a packed list of le32 values. import sys import struct i = 0 while True: buf = sys.stdin.read(4) if len(buf) == 0: break elif len(buf) != 4: sys.stdout.write("\n") sys.stderr.write("Error: read {0} not 4 bytes\n".format(len(buf))) sys.exit(1) if i > 0: sys.stdout.write(" ") sys.stdout.write("{0:x}={1}".format(i, struct.unpack("<I", buf)[0])) i += 1 sys.stdout.write("\n")
gpl-2.0
1,200,256,328,089,234,400
32.875
78
0.730012
false
slockit/DAO
tests/scenarios/fuel/run.py
4
1429
import random from utils import constrained_sum_sample_pos, arr_str scenario_description = ( "During the fueling period of the DAO, send enough ether from all " "accounts to create tokens and then assert that the user's balance is " "indeed correct and that the minimum fueling goal has been reached" ) def run(ctx): ctx.assert_scenario_ran('deploy') creation_secs = ctx.remaining_time() ctx.total_supply = ( ctx.args.deploy_min_tokens_to_create + random.randint(1, 100) ) ctx.token_amounts = constrained_sum_sample_pos( len(ctx.accounts), ctx.total_supply ) ctx.create_js_file(substitutions={ "dao_abi": ctx.dao_abi, "dao_address": ctx.dao_address, "wait_ms": (creation_secs-3)*1000, "amounts": arr_str(ctx.token_amounts) } ) print( "Notice: Fueling period is {} seconds so the test will wait " "as much".format(creation_secs) ) adjusted_amounts = ( [x/1.5 for x in ctx.token_amounts] if ctx.scenario_uses_extrabalance() else ctx.token_amounts ) adjusted_supply = ( ctx.total_supply / 1.5 if ctx.scenario_uses_extrabalance() else ctx.total_supply ) ctx.execute(expected={ "dao_fueled": True, "total_supply": adjusted_supply, "balances": adjusted_amounts, "user0_after": adjusted_amounts[0] })
lgpl-3.0
-5,488,954,882,271,867,000
28.770833
75
0.621414
false
tarzan0820/odoo
openerp/tools/lru.py
237
3197
# -*- coding: utf-8 -*- # taken from http://code.activestate.com/recipes/252524-length-limited-o1-lru-cache-implementation/ import threading from func import synchronized __all__ = ['LRU'] class LRUNode(object): __slots__ = ['prev', 'next', 'me'] def __init__(self, prev, me): self.prev = prev self.me = me self.next = None class LRU(object): """ Implementation of a length-limited O(1) LRU queue. Built for and used by PyPE: http://pype.sourceforge.net Copyright 2003 Josiah Carlson. """ def __init__(self, count, pairs=[]): self._lock = threading.RLock() self.count = max(count, 1) self.d = {} self.first = None self.last = None for key, value in pairs: self[key] = value @synchronized() def __contains__(self, obj): return obj in self.d @synchronized() def __getitem__(self, obj): a = self.d[obj].me self[a[0]] = a[1] return a[1] @synchronized() def __setitem__(self, obj, val): if obj in self.d: del self[obj] nobj = LRUNode(self.last, (obj, val)) if self.first is None: self.first = nobj if self.last: self.last.next = nobj self.last = nobj self.d[obj] = nobj if len(self.d) > self.count: if self.first == self.last: self.first = None self.last = None return a = self.first a.next.prev = None self.first = a.next a.next = None del self.d[a.me[0]] del a @synchronized() def __delitem__(self, obj): nobj = self.d[obj] if nobj.prev: nobj.prev.next = nobj.next else: self.first = nobj.next if nobj.next: nobj.next.prev = nobj.prev else: self.last = nobj.prev del self.d[obj] @synchronized() def __iter__(self): cur = self.first while cur is not None: cur2 = cur.next yield cur.me[1] cur = cur2 @synchronized() def __len__(self): return len(self.d) @synchronized() def iteritems(self): cur = self.first while cur is not None: cur2 = cur.next yield cur.me cur = cur2 @synchronized() def iterkeys(self): return iter(self.d) @synchronized() def itervalues(self): for i,j in self.iteritems(): yield j @synchronized() def keys(self): return self.d.keys() @synchronized() def pop(self,key): v=self[key] del self[key] return v @synchronized() def clear(self): self.d = {} self.first = None self.last = None @synchronized() def clear_prefix(self, prefix): """ Remove from `self` all the items with the given `prefix`. """ n = len(prefix) for key in self.keys(): if key[:n] == prefix: del self[key] # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
7,655,114,437,631,426,000
23.592308
99
0.510166
false
Ircam-Web/mezzanine-organization
organization/projects/migrations/0085_auto_20190619_2023.py
1
1116
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-06-19 18:23 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('organization-projects', '0084_auto_20190304_2221'), ] operations = [ migrations.AlterModelOptions( name='projectpage', options={'permissions': (('user_edit', 'Mezzo - User can edit its own content'), ('user_delete', 'Mezzo - User can delete its own content'), ('team_edit', "Mezzo - User can edit his team's content"), ('team_delete', "Mezzo - User can delete his team's content"))}, ), migrations.AddField( model_name='projectpage', name='user', field=models.ForeignKey(default=4, on_delete=django.db.models.deletion.CASCADE, related_name='projectpages', to=settings.AUTH_USER_MODEL, verbose_name='Author'), preserve_default=False, ), ]
agpl-3.0
4,549,997,135,370,149,400
38.857143
276
0.650538
false
PXke/invenio
invenio/testsuite/test_bibauthority.py
4
1666
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2011, 2012, 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Unit Tests for BibAuthority""" from invenio.testsuite import InvenioTestCase from invenio.testsuite import make_test_suite, run_test_suite class TestBibAuthorityEngine(InvenioTestCase): """Unit tests for bibauthority_engine""" def test_split_name_parts(self): """bibauthority - test get_type_from_authority_id""" from invenio.legacy.bibauthority.config import CFG_BIBAUTHORITY_PREFIX_SEP from invenio.legacy.bibauthority.engine import get_type_from_control_no prefix = "JOURNAL" control_no = "(CERN)abcd1234" # must start with a '(' self.assertEqual(get_type_from_control_no( prefix + CFG_BIBAUTHORITY_PREFIX_SEP + control_no), prefix) TEST_SUITE = make_test_suite(TestBibAuthorityEngine) if __name__ == "__main__": run_test_suite(TEST_SUITE)
gpl-2.0
-1,313,488,848,769,739,800
39.634146
82
0.69928
false
caseyching/Impala
tests/benchmark/report_benchmark_results.py
13
43688
#!/usr/bin/env impala-python # Copyright (c) 2014 Cloudera, Inc. All rights reserved. # # This script provides help with parsing and reporting of perf results. It currently # provides three main capabilities: # 1) Printing perf results to console in 'pretty' format # 2) Comparing two perf result sets together and displaying comparison results to console # 3) Outputting the perf results in JUnit format which is useful for plugging in to # Jenkins perf reporting. # By default in Python if you divide an int by another int (5 / 2), the result will also # be an int (2). The following line changes this behavior so that float will be returned # if necessary (2.5). from __future__ import division import difflib import json import logging import os import prettytable import re from collections import defaultdict from datetime import date, datetime from optparse import OptionParser from tests.util.calculation_util import ( calculate_tval, calculate_avg, calculate_stddev, calculate_geomean) LOG = logging.getLogger(__name__) # String constants AVG = 'avg' AVG_TIME = 'avg_time' BASELINE_AVG = 'baseline_avg' BASELINE_MAX = 'baseline_max' CLIENT_NAME = 'client_name' COMPRESSION_CODEC = 'compression_codec' COMPRESSION_TYPE = 'compression_type' DELTA_AVG = 'delta_avg' DELTA_MAX = 'delta_max' DELTA_RSTD = 'delta_rstd' DETAIL = 'detail' EST_NUM_ROWS = 'est_num_rows' EST_PEAK_MEM = 'est_peak_mem' EXECUTOR_NAME = 'executor_name' EXEC_SUMMARY = 'exec_summary' FILE_FORMAT = 'file_format' GEOMEAN = 'geomean' ITERATIONS = 'iterations' MAX_TIME = 'max_time' NAME = 'name' NUM_CLIENTS = 'num_clients' NUM_HOSTS = 'num_hosts' NUM_ROWS = 'num_rows' OPERATOR = 'operator' PEAK_MEM = 'peak_mem' PERCENT_OF_QUERY = 'percent_of_query' PREFIX = 'prefix' QUERY = 'query' QUERY_STR = 'query_str' REF_RSTD = 'ref_rstd' RESULT_LIST = 'result_list' RSTD = 'rstd' RUNTIME_PROFILE = 'runtime_profile' SCALE_FACTOR = 'scale_factor' STDDEV = 'stddev' STDDEV_TIME = 'stddev_time' TEST_VECTOR = 'test_vector' TIME_TAKEN = 'time_taken' WORKLOAD_NAME = 'workload_name' parser = OptionParser() parser.add_option("--input_result_file", dest="result_file", default=os.environ['IMPALA_HOME'] + '/benchmark_results.json', help="The input JSON file with benchmark results") parser.add_option("--reference_result_file", dest="reference_result_file", default=os.environ['IMPALA_HOME'] + '/reference_benchmark_results.json', help="The input JSON file with reference benchmark results") parser.add_option("--junit_output_file", dest="junit_output_file", default='', help='If set, outputs results in Junit format to the specified file') parser.add_option("--no_output_table", dest="no_output_table", action="store_true", default= False, help='Outputs results in table format to the console') parser.add_option("--report_description", dest="report_description", default=None, help='Optional description for the report.') parser.add_option("--cluster_name", dest="cluster_name", default='UNKNOWN', help="Name of the cluster the results are from (ex. Bolt)") parser.add_option("--verbose", "-v", dest="verbose", action="store_true", default= False, help='Outputs to console with with increased verbosity') parser.add_option("--output_all_summary_nodes", dest="output_all_summary_nodes", action="store_true", default= False, help='Print all execution summary nodes') parser.add_option("--build_version", dest="build_version", default='UNKNOWN', help="Build/version info about the Impalad instance results are from.") parser.add_option("--lab_run_info", dest="lab_run_info", default='UNKNOWN', help="Information about the lab run (name/id) that published "\ "the results.") parser.add_option("--run_user_name", dest="run_user_name", default='anonymous', help="User name that this run is associated with in the perf database") parser.add_option("--tval_threshold", dest="tval_threshold", default=None, type="float", help="The ttest t-value at which a performance change "\ "will be flagged as sigificant.") parser.add_option("--min_percent_change_threshold", dest="min_percent_change_threshold", default=5.0, type="float", help="Any performance changes below this threshold" \ " will not be classified as significant. If the user specifies an" \ " empty value, the threshold will be set to 0") parser.add_option("--max_percent_change_threshold", dest="max_percent_change_threshold", default=20.0, type="float", help="Any performance changes above this threshold"\ " will be classified as significant. If the user specifies an" \ " empty value, the threshold will be set to the system's maxint") parser.add_option("--allowed_latency_diff_secs", dest="allowed_latency_diff_secs", default=0.0, type="float", help="If specified, only a timing change that differs by more than\ this value will be considered significant.") # These parameters are specific to recording results in a database. This is optional parser.add_option("--save_to_db", dest="save_to_db", action="store_true", default= False, help='Saves results to the specified database.') parser.add_option("--is_official", dest="is_official", action="store_true", default= False, help='Indicates this is an official perf run result') parser.add_option("--db_host", dest="db_host", default='localhost', help="Machine hosting the database") parser.add_option("--db_port", dest="db_port", default='21050', help="Port on the machine hosting the database") parser.add_option("--db_name", dest="db_name", default='impala_perf_results', help="Name of the perf database.") options, args = parser.parse_args() def get_dict_from_json(filename): """Given a JSON file, return a nested dictionary. Everything in this file is based on the nested dictionary data structure. The dictionary is structured as follows: Top level maps to workload. Each workload maps to file_format. Each file_format maps to queries. Each query contains a key "result_list" that maps to a list of QueryResult (look at query.py) dictionaries. The compute stats method add additional keys such as "avg" or "stddev" here. Here's how the keys are structred: To get a workload, the key looks like this: (('workload_name', 'tpch'), ('scale_factor', '300gb')) Each workload has a key that looks like this: (('file_format', 'text'), ('compression_codec', 'zip'), ('compression_type', 'block')) Each Query has a key like this: (('name', 'TPCH_Q10')) This is useful for finding queries in a certain category and computing stats Args: filename (str): path to the JSON file returns: dict: a nested dictionary with grouped queries """ def add_result(query_result): """Add query to the dictionary. Automatically finds the path in the nested dictionary and adds the result to the appropriate list. TODO: This method is hard to reason about, so it needs to be made more streamlined. """ def get_key(level_num): """Build a key for a particular nesting level. The key is built by extracting the appropriate values from query_result. """ level = list() # In the outer layer, we group by workload name and scale factor level.append([('query', 'workload_name'), ('query', 'scale_factor')]) # In the middle layer, we group by file format and compression type level.append([('query', 'test_vector', 'file_format'), ('query', 'test_vector', 'compression_codec'), ('query', 'test_vector', 'compression_type')]) # In the bottom layer, we group by query name level.append([('query', 'name')]) key = [] def get_nested_val(path): """given a path to a variable in query result, extract the value. For example, to extract compression_type from the query_result, we need to follow the this path in the nested dictionary: "query_result" -> "query" -> "test_vector" -> "compression_type" """ cur = query_result for step in path: cur = cur[step] return cur for path in level[level_num]: key.append((path[-1], get_nested_val(path))) return tuple(key) # grouped is the nested dictionary defined in the outer function get_dict_from_json. # It stores all the results grouped by query name and other parameters. cur = grouped # range(3) because there are 3 levels of nesting, as defined in get_key for level_num in range(3): cur = cur[get_key(level_num)] cur[RESULT_LIST].append(query_result) with open(filename, "r") as f: data = json.load(f) grouped = defaultdict( lambda: defaultdict( lambda: defaultdict(lambda: defaultdict(list)))) for workload_name, workload in data.items(): for query_result in workload: if query_result['success']: add_result(query_result) calculate_time_stats(grouped) return grouped def all_query_results(grouped): for workload_scale, workload in grouped.items(): for file_format, queries in workload.items(): for query_name, results in queries.items(): yield(results) def get_commit_date(commit_sha): import urllib2 url = 'https://api.github.com/repos/cloudera/Impala/commits/' + commit_sha try: request = urllib2.Request(url) response = urllib2.urlopen(request).read() data = json.loads(response.decode('utf8')) return data['commit']['committer']['date'][:10] except: return '' def get_impala_version(grouped): """Figure out Impala version by looking at query profile.""" first_result = all_query_results(grouped).next() profile = first_result['result_list'][0]['runtime_profile'] match = re.search('Impala Version:\s(.*)\s\(build\s(.*)\)', profile) version = match.group(1) commit_sha = match.group(2) commit_date = get_commit_date(commit_sha) return '{0} ({1})'.format(version, commit_date) def calculate_time_stats(grouped): """Adds statistics to the nested dictionary. We are calculating the average runtime and Standard Deviation for each query type. """ def remove_first_run(result_list): """We want to remove the first result because the performance is much worse on the first run. """ if len(result_list) > 1: # We want to remove the first result only if there is more that one result result_list.remove(min(result_list, key=lambda result: result['start_time'])) for workload_scale, workload in grouped.items(): for file_format, queries in workload.items(): for query_name, results in queries.items(): result_list = results[RESULT_LIST] remove_first_run(result_list) avg = calculate_avg( [query_results[TIME_TAKEN] for query_results in result_list]) dev = calculate_stddev( [query_results[TIME_TAKEN] for query_results in result_list]) num_clients = max( int(query_results[CLIENT_NAME]) for query_results in result_list) iterations = int((len(result_list) + 1) / num_clients) results[AVG] = avg results[STDDEV] = dev results[NUM_CLIENTS] = num_clients results[ITERATIONS] = iterations class Report(object): significant_perf_change = False class FileFormatComparisonRow(object): """Represents a row in the overview table, where queries are grouped together and average and geomean are calculated per workload and file format (first table in the report). """ def __init__(self, workload_scale, file_format, queries, ref_queries): time_list = [] ref_time_list = [] for query_name, results in queries.items(): if query_name in ref_queries: # We want to calculate the average and geomean of the query only if it is both # results and reference results for query_results in results[RESULT_LIST]: time_list.append(query_results[TIME_TAKEN]) ref_results = ref_queries[query_name] for ref_query_results in ref_results[RESULT_LIST]: ref_time_list.append(ref_query_results[TIME_TAKEN]) self.workload_name = '{0}({1})'.format( workload_scale[0][1].upper(), workload_scale[1][1]) self.file_format = '{0} / {1} / {2}'.format( file_format[0][1], file_format[1][1], file_format[2][1]) self.avg = calculate_avg(time_list) ref_avg = calculate_avg(ref_time_list) self.delta_avg = calculate_change(self.avg, ref_avg) self.geomean = calculate_geomean(time_list) ref_geomean = calculate_geomean(ref_time_list) self.delta_geomean = calculate_change(self.geomean, ref_geomean) class QueryComparisonRow(object): """Represents a row in the table where individual queries are shown (second table in the report). """ def __init__(self, results, ref_results): self.workload_name = '{0}({1})'.format( results[RESULT_LIST][0][QUERY][WORKLOAD_NAME].upper(), results[RESULT_LIST][0][QUERY][SCALE_FACTOR]) self.query_name = results[RESULT_LIST][0][QUERY][NAME] self.file_format = '{0} / {1} / {2}'.format( results[RESULT_LIST][0][QUERY][TEST_VECTOR][FILE_FORMAT], results[RESULT_LIST][0][QUERY][TEST_VECTOR][COMPRESSION_TYPE], results[RESULT_LIST][0][QUERY][TEST_VECTOR][COMPRESSION_TYPE]) self.avg = results[AVG] self.rsd = results[STDDEV] / self.avg if self.avg > 0 else 0.0 self.significant_variability = True if self.rsd > 0.1 else False self.num_clients = results[NUM_CLIENTS] self.iters = results[ITERATIONS] if ref_results is None: self.perf_change, self.is_regression = False, False # If reference results are not present, comparison columns will have inf in them self.base_avg = float('-inf') self.base_rsd = float('-inf') self.delta_avg = float('-inf') self.perf_change_str = '' else: self.perf_change, self.is_regression = self.__check_perf_change_significance( results, ref_results) self.base_avg = ref_results[AVG] self.base_rsd = ref_results[STDDEV] / self.base_avg if self.base_avg > 0 else 0.0 self.delta_avg = calculate_change(self.avg, self.base_avg) if self.perf_change: self.perf_change_str = self.__build_perf_change_str( results, ref_results, self.is_regression) Report.significant_perf_change = True else: self.perf_change_str = '' try: save_runtime_diffs(results, ref_results, self.perf_change, self.is_regression) except Exception as e: LOG.error('Could not generate an html diff: {0}'.format(e)) def __check_perf_change_significance(self, stat, ref_stat): absolute_difference = abs(ref_stat[AVG] - stat[AVG]) try: percent_difference = abs(ref_stat[AVG] - stat[AVG]) * 100 / ref_stat[AVG] except ZeroDivisionError: percent_difference = 0.0 stddevs_are_zero = (ref_stat[STDDEV] == 0) and (stat[STDDEV] == 0) if absolute_difference < options.allowed_latency_diff_secs: return False, False if percent_difference < options.min_percent_change_threshold: return False, False if percent_difference > options.max_percent_change_threshold: return True, ref_stat[AVG] < stat[AVG] if options.tval_threshold and not stddevs_are_zero: tval = calculate_tval(stat[AVG], stat[STDDEV], stat[ITERATIONS], ref_stat[AVG], ref_stat[STDDEV], ref_stat[ITERATIONS]) return abs(tval) > options.tval_threshold, tval > options.tval_threshold return False, False def __build_perf_change_str(self, result, ref_result, is_regression): """Build a performance change string. For example: Regression: TPCDS-Q52 [parquet/none/none] (1.390s -> 1.982s [+42.59%]) """ perf_change_type = "(R) Regression" if is_regression else "(I) Improvement" query = result[RESULT_LIST][0][QUERY] workload_name = '{0}({1})'.format( query[WORKLOAD_NAME].upper(), query[SCALE_FACTOR]) query_name = query[NAME] file_format = query[TEST_VECTOR][FILE_FORMAT] compression_codec = query[TEST_VECTOR][COMPRESSION_CODEC] compression_type = query[TEST_VECTOR][COMPRESSION_TYPE] template = ("{perf_change_type}: " "{workload_name} {query_name} " "[{file_format} / {compression_codec} / {compression_type}] " "({ref_avg:.2f}s -> {avg:.2f}s [{delta:+.2%}])\n") perf_change_str = template.format( perf_change_type = perf_change_type, workload_name = workload_name, query_name = query_name, file_format = file_format, compression_codec = compression_codec, compression_type = compression_type, ref_avg = ref_result[AVG], avg = result[AVG], delta = calculate_change(result[AVG], ref_result[AVG])) perf_change_str += build_exec_summary_str(result, ref_result) return perf_change_str + '\n' class QueryVariabilityRow(object): """Represents a row in the query variability table. """ def __init__(self, results, ref_results): if ref_results is None: self.base_rel_stddev = float('inf') else: self.base_rel_stddev = ref_results[STDDEV] / ref_results[AVG]\ if ref_results > 0 else 0.0 self.workload_name = '{0}({1})'.format( results[RESULT_LIST][0][QUERY][WORKLOAD_NAME].upper(), results[RESULT_LIST][0][QUERY][SCALE_FACTOR]) self.query_name = results[RESULT_LIST][0][QUERY][NAME] self.file_format = results[RESULT_LIST][0][QUERY][TEST_VECTOR][FILE_FORMAT] self.compression = results[RESULT_LIST][0][QUERY][TEST_VECTOR][COMPRESSION_CODEC]\ + ' / ' + results[RESULT_LIST][0][QUERY][TEST_VECTOR][COMPRESSION_TYPE] self.rel_stddev = results[STDDEV] / results[AVG] if results[AVG] > 0 else 0.0 self.significant_variability = self.rel_stddev > 0.1 variability_template = ("(V) Significant Variability: " "{workload_name} {query_name} [{file_format} / {compression}] " "({base_rel_stddev:.2%} -> {rel_stddev:.2%})\n") if self.significant_variability and ref_results: #If ref_results do not exist, variability analysis will not be conducted self.variability_str = variability_template.format( workload_name = self.workload_name, query_name = self.query_name, file_format = self.file_format, compression = self.compression, base_rel_stddev = self.base_rel_stddev, rel_stddev = self.rel_stddev) self.exec_summary_str = build_exec_summary_str( results, ref_results, for_variability = True) else: self.variability_str = str() self.exec_summary_str = str() def __str__(self): return self.variability_str + self.exec_summary_str def __init__(self, grouped, ref_grouped): self.grouped = grouped self.ref_grouped = ref_grouped self.query_comparison_rows = [] self.file_format_comparison_rows = [] self.query_variability_rows = [] self.__analyze() def __analyze(self): """Generates a comparison data that can be printed later""" for workload_scale, workload in self.grouped.items(): for file_format, queries in workload.items(): if self.ref_grouped is not None and workload_scale in self.ref_grouped and\ file_format in self.ref_grouped[ workload_scale]: ref_queries = self.ref_grouped[workload_scale][file_format] self.file_format_comparison_rows.append(Report.FileFormatComparisonRow( workload_scale, file_format, queries, ref_queries)) else: #If not present in reference results, set to None ref_queries = None for query_name, results in queries.items(): if self.ref_grouped is not None and workload_scale in self.ref_grouped and\ file_format in self.ref_grouped[workload_scale] and query_name in\ self.ref_grouped[workload_scale][file_format]: ref_results = self.ref_grouped[workload_scale][file_format][query_name] query_comparison_row = Report.QueryComparisonRow(results, ref_results) self.query_comparison_rows.append(query_comparison_row) query_variability_row = Report.QueryVariabilityRow(results, ref_results) self.query_variability_rows.append(query_variability_row) else: #If not present in reference results, set to None ref_results = None def __str__(self): output = str() #per file format analysis overview table table = prettytable.PrettyTable(['Workload', 'File Format', 'Avg (s)', 'Delta(Avg)', 'GeoMean(s)', 'Delta(GeoMean)']) table.float_format = '.2' table.align = 'l' self.file_format_comparison_rows.sort( key = lambda row: row.delta_geomean, reverse = True) for row in self.file_format_comparison_rows: table_row = [ row.workload_name, row.file_format, row.avg, '{0:+.2%}'.format(row.delta_avg), row.geomean, '{0:+.2%}'.format(row.delta_geomean)] table.add_row(table_row) output += str(table) + '\n\n' #main comparison table detailed_performance_change_analysis_str = str() table = prettytable.PrettyTable(['Workload', 'Query', 'File Format', 'Avg(s)', 'Base Avg(s)', 'Delta(Avg)', 'StdDev(%)', 'Base StdDev(%)', 'Num Clients', 'Iters']) table.float_format = '.2' table.align = 'l' #Sort table from worst to best regression self.query_comparison_rows.sort(key = lambda row: row.delta_avg, reverse = True) for row in self.query_comparison_rows: delta_avg_template = ' {0:+.2%}' if not row.perf_change else ( 'R {0:+.2%}' if row.is_regression else 'I {0:+.2%}') table_row = [ row.workload_name, row.query_name, row.file_format, row.avg, row.base_avg if row.base_avg != float('-inf') else 'N/A', ' N/A' if row.delta_avg == float('-inf') else delta_avg_template.format( row.delta_avg), ('* {0:.2%} *' if row.rsd > 0.1 else ' {0:.2%} ').format(row.rsd), ' N/A' if row.base_rsd == float('-inf') else ( '* {0:.2%} *' if row.base_rsd > 0.1 else ' {0:.2%} ').format(row.base_rsd), row.num_clients, row.iters] table.add_row(table_row) detailed_performance_change_analysis_str += row.perf_change_str output += str(table) + '\n\n' output += detailed_performance_change_analysis_str variability_analysis_str = str() self.query_variability_rows.sort(key = lambda row: row.rel_stddev, reverse = True) for row in self.query_variability_rows: variability_analysis_str += str(row) output += variability_analysis_str if Report.significant_perf_change: output += 'Significant perf change detected' return output class CombinedExecSummaries(object): """All execution summaries for each query are combined into this object. The overall average time is calculated for each node by averaging the average time from each execution summary. The max time time is calculated by getting the max time of max times. This object can be compared to another one and ExecSummaryComparison can be generated. Args: exec_summaries (list of list of dict): A list of exec summaries (list of dict is how it is received from the beeswax client. Attributes: rows (list of dict): each dict represents a row in the summary table. Each row in rows is a dictionary. Each dictionary has the following keys: prefix (str) operator (str) num_hosts (int) num_rows (int) est_num_rows (int) detail (str) avg_time (float): averge of average times in all the execution summaries stddev_time: standard deviation of times in all the execution summaries max_time: maximum of max times in all the execution summaries peak_mem (int) est_peak_mem (int) """ def __init__(self, exec_summaries): # We want to make sure that all execution summaries have the same structure before # we can combine them. If not, err_str will contain the reason why we can't combine # the exec summaries. ok, err_str = self.__check_exec_summary_schema(exec_summaries) self.error_str = err_str self.rows = [] if ok: self.__build_rows(exec_summaries) def __build_rows(self, exec_summaries): first_exec_summary = exec_summaries[0] for row_num, row in enumerate(first_exec_summary): combined_row = {} # Copy fixed values from the first exec summary for key in [PREFIX, OPERATOR, NUM_HOSTS, NUM_ROWS, EST_NUM_ROWS, DETAIL]: combined_row[key] = row[key] avg_times = [exec_summary[row_num][AVG_TIME] for exec_summary in exec_summaries] max_times = [exec_summary[row_num][MAX_TIME] for exec_summary in exec_summaries] peak_mems = [exec_summary[row_num][PEAK_MEM] for exec_summary in exec_summaries] est_peak_mems = [exec_summary[row_num][EST_PEAK_MEM] for exec_summary in exec_summaries] # Set the calculated values combined_row[AVG_TIME] = calculate_avg(avg_times) combined_row[STDDEV_TIME] = calculate_stddev(avg_times) combined_row[MAX_TIME] = max(max_times) combined_row[PEAK_MEM] = max(peak_mems) combined_row[EST_PEAK_MEM] = max(est_peak_mems) self.rows.append(combined_row) def is_same_schema(self, reference): """Check if the reference CombinedExecSummaries summary has the same schema as this one. (For example, the operator names are the same for each node). The purpose of this is to check if it makes sense to combine this object with a reference one to produce ExecSummaryComparison. Args: reference (CombinedExecSummaries): comparison Returns: bool: True if the schama's are similar enough to be compared, False otherwise. """ if len(self.rows) != len(reference.rows): return False for row_num, row in enumerate(self.rows): ref_row = reference.rows[row_num] if row[OPERATOR] != ref_row[OPERATOR]: return False return True def __str__(self): if self.error_str: return self.error_str table = prettytable.PrettyTable( ["Operator", "#Hosts", "Avg Time", "Std Dev", "Max Time", "#Rows", "Est #Rows"]) table.align = 'l' table.float_format = '.2' for row in self.rows: table_row = [ row[PREFIX] + row[OPERATOR], prettyprint_values(row[NUM_HOSTS]), prettyprint_time(row[AVG_TIME]), prettyprint_time(row[STDDEV_TIME]), prettyprint_time(row[MAX_TIME]), prettyprint_values(row[NUM_ROWS]), prettyprint_values(row[EST_NUM_ROWS])] table.add_row(table_row) return str(table) @property def total_runtime(self): return sum([row[AVG_TIME] for row in self.rows]) def __check_exec_summary_schema(self, exec_summaries): """Check if all given exec summaries have the same structure. This method is called to check if it is possible a single CombinedExecSummaries from the list of exec_summaries. (For example all exec summaries must have the same number of nodes.) This method is somewhat similar to is_same_schema. The difference is that is_same_schema() checks if two CombinedExecSummaries have the same structure and this method checks if all exec summaries in the list have the same structure. Args: exec_summaries (list of dict): each dict represents an exec_summary Returns: (bool, str): True if all exec summaries have the same structure, otherwise False followed by a string containing the explanation. """ err = 'Summaries cannot be combined: ' if len(exec_summaries) < 1: return False, err + 'no exec summaries Found' first_exec_summary = exec_summaries[0] if len(first_exec_summary) < 1: return False, err + 'exec summary contains no nodes' for exec_summary in exec_summaries: if len(exec_summary) != len(first_exec_summary): return False, err + 'different number of nodes in exec summaries' for row_num, row in enumerate(exec_summary): comp_row = first_exec_summary[row_num] if row[OPERATOR] != comp_row[OPERATOR]: return False, err + 'different operator' return True, str() class ExecSummaryComparison(object): """Represents a comparison between two CombinedExecSummaries. Args: combined_summary (CombinedExecSummaries): current summary. ref_combined_summary (CombinedExecSummaries): reference summaries. Attributes: rows (list of dict): Each dict represents a single row. Each dict has the following keys: prefix (str) operator (str) num_hosts (int) avg_time (float) stddev_time (float) avg_time_change (float): % change in avg time compared to reference avg_time_change_total (float): % change in avg time compared to total of the query max_time (float) max_time_change (float): % change in max time compared to reference peak_mem (int) peak_mem_change (float): % change compared to reference num_rows (int) est_num_rows (int) est_peak_mem (int) detail (str) combined_summary (CombinedExecSummaries): original combined summary ref_combined_summary (CombinedExecSummaries): original reference combined summary. If the comparison cannot be constructed, these summaries can be printed. Another possible way to implement this is to generate this object when we call CombinedExecSummaries.compare(reference). """ def __init__(self, combined_summary, ref_combined_summary, for_variability = False): # Store the original summaries, in case we can't build a comparison self.combined_summary = combined_summary self.ref_combined_summary = ref_combined_summary # If some error happened during calculations, store it here self.error_str = str() self.for_variability = for_variability self.rows = [] def __build_rows(self): if self.combined_summary.is_same_schema(self.ref_combined_summary): for i, row in enumerate(self.combined_summary.rows): ref_row = self.ref_combined_summary.rows[i] comparison_row = {} for key in [PREFIX, OPERATOR, NUM_HOSTS, AVG_TIME, STDDEV_TIME, MAX_TIME, PEAK_MEM, NUM_ROWS, EST_NUM_ROWS, EST_PEAK_MEM, DETAIL]: comparison_row[key] = row[key] comparison_row[PERCENT_OF_QUERY] = row[AVG_TIME] /\ self.combined_summary.total_runtime\ if self.combined_summary.total_runtime > 0 else 0.0 comparison_row[RSTD] = row[STDDEV_TIME] / row[AVG_TIME]\ if row[AVG_TIME] > 0 else 0.0 comparison_row[BASELINE_AVG] = ref_row[AVG_TIME] comparison_row[DELTA_AVG] = calculate_change( row[AVG_TIME], ref_row[AVG_TIME]) comparison_row[BASELINE_MAX] = ref_row[MAX_TIME] comparison_row[DELTA_MAX] = calculate_change( row[MAX_TIME], ref_row[MAX_TIME]) self.rows.append(comparison_row) else: self.error_str = 'Execution summary structures are different' def __str__(self): """Construct a PrettyTable containing the comparison""" if self.for_variability: return str(self.__build_table_variability()) else: return str(self.__build_table()) def __build_rows_variability(self): if self.ref_combined_summary and self.combined_summary.is_same_schema( self.ref_combined_summary): for i, row in enumerate(self.combined_summary.rows): ref_row = self.ref_combined_summary.rows[i] comparison_row = {} comparison_row[OPERATOR] = row[OPERATOR] comparison_row[PERCENT_OF_QUERY] = row[AVG_TIME] /\ self.combined_summary.total_runtime\ if self.combined_summary.total_runtime > 0 else 0.0 comparison_row[RSTD] = row[STDDEV_TIME] / row[AVG_TIME]\ if row[AVG_TIME] > 0 else 0.0 comparison_row[REF_RSTD] = ref_row[STDDEV_TIME] / ref_row[AVG_TIME]\ if ref_row[AVG_TIME] > 0 else 0.0 comparison_row[DELTA_RSTD] = calculate_change( comparison_row[RSTD], comparison_row[REF_RSTD]) comparison_row[NUM_HOSTS] = row[NUM_HOSTS] comparison_row[NUM_ROWS] = row[NUM_ROWS] comparison_row[EST_NUM_ROWS] = row[EST_NUM_ROWS] self.rows.append(comparison_row) else: self.error_str = 'Execution summary structures are different' def __build_table_variability(self): def is_significant(row): """Check if the performance change in the row was significant""" return options.output_all_summary_nodes or ( row[RSTD] > 0.1 and row[PERCENT_OF_QUERY] > 0.02) self.__build_rows_variability() if self.error_str: # If the summary comparison could not be constructed, output both summaries output = self.error_str + '\n' output += 'Execution Summary: \n' output += str(self.combined_summary) + '\n' output += 'Reference Execution Summary: \n' output += str(self.ref_combined_summary) return output table = prettytable.PrettyTable( ['Operator', '% of Query', 'StdDev(%)', 'Base StdDev(%)', 'Delta(StdDev(%))', '#Hosts', '#Rows', 'Est #Rows']) table.align = 'l' table.float_format = '.2' table_contains_at_least_one_row = False for row in filter(lambda row: is_significant(row), self.rows): table_row = [row[OPERATOR], '{0:.2%}'.format(row[PERCENT_OF_QUERY]), '{0:.2%}'.format(row[RSTD]), '{0:.2%}'.format(row[REF_RSTD]), '{0:+.2%}'.format(row[DELTA_RSTD]), prettyprint_values(row[NUM_HOSTS]), prettyprint_values(row[NUM_ROWS]), prettyprint_values(row[EST_NUM_ROWS]) ] table_contains_at_least_one_row = True table.add_row(table_row) if table_contains_at_least_one_row: return str(table) + '\n' else: return 'No Nodes with significant StdDev %\n' def __build_table(self): def is_significant(row): """Check if the performance change in the row was significant""" return options.output_all_summary_nodes or ( row[MAX_TIME] > 100000000 and row[PERCENT_OF_QUERY] > 0.02) self.__build_rows() if self.error_str: # If the summary comparison could not be constructed, output both summaries output = self.error_str + '\n' output += 'Execution Summary: \n' output += str(self.combined_summary) + '\n' output += 'Reference Execution Summary: \n' output += str(self.ref_combined_summary) return output table = prettytable.PrettyTable( ['Operator', '% of Query', 'Avg', 'Base Avg', 'Delta(Avg)', 'StdDev(%)', 'Max', 'Base Max', 'Delta(Max)', '#Hosts', '#Rows', 'Est #Rows']) table.align = 'l' table.float_format = '.2' for row in self.rows: if is_significant(row): table_row = [row[OPERATOR], '{0:.2%}'.format(row[PERCENT_OF_QUERY]), prettyprint_time(row[AVG_TIME]), prettyprint_time(row[BASELINE_AVG]), prettyprint_percent(row[DELTA_AVG]), ('* {0:.2%} *' if row[RSTD] > 0.1 else ' {0:.2%} ').format(row[RSTD]), prettyprint_time(row[MAX_TIME]), prettyprint_time(row[BASELINE_MAX]), prettyprint_percent(row[DELTA_MAX]), prettyprint_values(row[NUM_HOSTS]), prettyprint_values(row[NUM_ROWS]), prettyprint_values(row[EST_NUM_ROWS])] table.add_row(table_row) return str(table) def calculate_change(val, ref_val): """Calculate how big the change in val compared to ref_val is compared to total""" return (val - ref_val) / ref_val if ref_val != 0 else 0.0 def prettyprint(val, units, divisor): """ Print a value in human readable format along with it's unit. We start at the leftmost unit in the list and keep dividing the value by divisor until the value is less than divisor. The value is then printed along with the unit type. Args: val (int or float): Value to be printed. units (list of str): Unit names for different sizes. divisor (float): ratio between two consecutive units. """ for unit in units: if abs(val) < divisor: if unit == units[0]: return "%d%s" % (val, unit) else: return "%3.2f%s" % (val, unit) val /= divisor def prettyprint_bytes(byte_val): return prettyprint(byte_val, ['B', 'KB', 'MB', 'GB', 'TB'], 1024.0) def prettyprint_values(unit_val): return prettyprint(unit_val, ["", "K", "M", "B"], 1000.0) def prettyprint_time(time_val): return prettyprint(time_val, ["ns", "us", "ms", "s"], 1000.0) def prettyprint_percent(percent_val): return '{0:+.2%}'.format(percent_val) def save_runtime_diffs(results, ref_results, change_significant, is_regression): """Given results and reference results, generate and output an HTML file containing the Runtime Profile diff. """ diff = difflib.HtmlDiff(wrapcolumn=90, linejunk=difflib.IS_LINE_JUNK) # We are comparing last queries in each run because they should have the most # stable performance (unlike the first queries) runtime_profile = results[RESULT_LIST][-1][RUNTIME_PROFILE] ref_runtime_profile = ref_results[RESULT_LIST][-1][RUNTIME_PROFILE] template = ('{prefix}-{query_name}-{scale_factor}-{file_format}-{compression_codec}' '-{compression_type}-runtime_profile.html') query = results[RESULT_LIST][-1][QUERY] # Neutral - no improvement or regression prefix = 'neu' if change_significant: prefix = 'reg' if is_regression else 'imp' runtime_profile_file_name = template.format( prefix = prefix, query_name = query[NAME], scale_factor = query[SCALE_FACTOR], file_format = query[TEST_VECTOR][FILE_FORMAT], compression_codec = query[TEST_VECTOR][COMPRESSION_CODEC], compression_type = query[TEST_VECTOR][COMPRESSION_TYPE]) # Go into results dir dir_path = os.path.join(os.environ["IMPALA_HOME"], 'results') if not os.path.exists(dir_path): os.mkdir(dir_path) elif not os.path.isdir(dir_path): raise RuntimeError("Unable to create $IMPALA_HOME/results, results file exists") runtime_profile_file_path = os.path.join(dir_path, runtime_profile_file_name) runtime_profile_diff = diff.make_file( ref_runtime_profile.splitlines(), runtime_profile.splitlines(), fromdesc = "Baseline Runtime Profile", todesc = "Current Runtime Profile") with open(runtime_profile_file_path, 'w+') as f: f.write(runtime_profile_diff) def build_exec_summary_str(results, ref_results, for_variability = False): exec_summaries = [result[EXEC_SUMMARY] for result in results[RESULT_LIST]] combined_summary = CombinedExecSummaries(exec_summaries) if ref_results is None: ref_exec_summaries = None ref_combined_summary = None else: ref_exec_summaries = [result[EXEC_SUMMARY] for result in ref_results[RESULT_LIST]] ref_combined_summary = CombinedExecSummaries(ref_exec_summaries) comparison = ExecSummaryComparison( combined_summary, ref_combined_summary, for_variability) return str(comparison) + '\n' def build_summary_header(current_impala_version, ref_impala_version): summary = "Report Generated on {0}\n".format(date.today()) if options.report_description: summary += 'Run Description: {0}\n'.format(options.report_description) if options.cluster_name: summary += '\nCluster Name: {0}\n'.format(options.cluster_name) if options.lab_run_info: summary += 'Lab Run Info: {0}\n'.format(options.lab_run_info) summary += 'Impala Version: {0}\n'.format(current_impala_version) summary += 'Baseline Impala Version: {0}\n'.format(ref_impala_version) return summary def write_results_to_datastore(grouped): """ Saves results to a database """ from perf_result_datastore import PerfResultDataStore LOG.info('Saving perf results to database') run_date = str(datetime.now()) with PerfResultDataStore( host=options.db_host, port=options.db_port, database_name=options.db_name) as data_store: for results in all_query_results(grouped): for query_result in results[RESULT_LIST]: data_store.insert_execution_result( query_name=query_result[QUERY][NAME], query_string=query_result[QUERY][QUERY_STR], workload_name=query_result[QUERY][WORKLOAD_NAME], scale_factor=query_result[QUERY][SCALE_FACTOR], file_format=query_result[QUERY][TEST_VECTOR][FILE_FORMAT], compression_codec=query_result[QUERY][TEST_VECTOR][COMPRESSION_CODEC], compression_type=query_result[QUERY][TEST_VECTOR][COMPRESSION_TYPE], num_clients=results[NUM_CLIENTS], num_iterations=results[ITERATIONS], cluster_name=options.cluster_name, executor_name=query_result[EXECUTOR_NAME], exec_time=query_result[TIME_TAKEN], run_date=run_date, version=options.build_version, run_info=options.lab_run_info, user_name=options.run_user_name, runtime_profile=query_result[RUNTIME_PROFILE]) if __name__ == "__main__": """Workflow: 1. Build a nested dictionary for the current result JSON and reference result JSON. 2. Calculate runtime statistics for each query for both results and reference results. 5. Save performance statistics to the performance database. 3. Construct a string with a an overview of workload runtime and detailed performance comparison for queries with significant performance change. """ logging.basicConfig(level=logging.DEBUG if options.verbose else logging.INFO) # Generate a dictionary based on the JSON file grouped = get_dict_from_json(options.result_file) current_impala_version = get_impala_version(grouped) try: # Generate a dictionary based on the reference JSON file ref_grouped = get_dict_from_json(options.reference_result_file) except Exception as e: # If reference result file could not be read we can still continue. The result can # be saved to the performance database. LOG.error('Could not read reference result file: {0}'.format(e)) ref_grouped = None ref_impala_version = get_impala_version(ref_grouped) if ref_grouped else 'N/A' if options.save_to_db: write_results_to_datastore(grouped) report = Report(grouped, ref_grouped) print build_summary_header(current_impala_version, ref_impala_version) print report
apache-2.0
6,282,423,292,874,212,000
38.146953
90
0.649171
false
sdague/home-assistant
homeassistant/components/dyson/sensor.py
5
6457
"""Support for Dyson Pure Cool Link Sensors.""" import logging from libpurecool.dyson_pure_cool import DysonPureCool from libpurecool.dyson_pure_cool_link import DysonPureCoolLink from homeassistant.const import PERCENTAGE, STATE_OFF, TEMP_CELSIUS, TIME_HOURS from homeassistant.helpers.entity import Entity from . import DYSON_DEVICES SENSOR_UNITS = { "air_quality": None, "dust": None, "filter_life": TIME_HOURS, "humidity": PERCENTAGE, } SENSOR_ICONS = { "air_quality": "mdi:fan", "dust": "mdi:cloud", "filter_life": "mdi:filter-outline", "humidity": "mdi:water-percent", "temperature": "mdi:thermometer", } DYSON_SENSOR_DEVICES = "dyson_sensor_devices" _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Dyson Sensors.""" if discovery_info is None: return hass.data.setdefault(DYSON_SENSOR_DEVICES, []) unit = hass.config.units.temperature_unit devices = hass.data[DYSON_SENSOR_DEVICES] # Get Dyson Devices from parent component device_ids = [device.unique_id for device in hass.data[DYSON_SENSOR_DEVICES]] new_entities = [] for device in hass.data[DYSON_DEVICES]: if isinstance(device, DysonPureCool): if f"{device.serial}-temperature" not in device_ids: new_entities.append(DysonTemperatureSensor(device, unit)) if f"{device.serial}-humidity" not in device_ids: new_entities.append(DysonHumiditySensor(device)) elif isinstance(device, DysonPureCoolLink): new_entities.append(DysonFilterLifeSensor(device)) new_entities.append(DysonDustSensor(device)) new_entities.append(DysonHumiditySensor(device)) new_entities.append(DysonTemperatureSensor(device, unit)) new_entities.append(DysonAirQualitySensor(device)) if not new_entities: return devices.extend(new_entities) add_entities(devices) class DysonSensor(Entity): """Representation of a generic Dyson sensor.""" def __init__(self, device, sensor_type): """Create a new generic Dyson sensor.""" self._device = device self._old_value = None self._name = None self._sensor_type = sensor_type async def async_added_to_hass(self): """Call when entity is added to hass.""" self._device.add_message_listener(self.on_message) def on_message(self, message): """Handle new messages which are received from the fan.""" # Prevent refreshing if not needed if self._old_value is None or self._old_value != self.state: _LOGGER.debug("Message received for %s device: %s", self.name, message) self._old_value = self.state self.schedule_update_ha_state() @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the Dyson sensor name.""" return self._name @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return SENSOR_UNITS[self._sensor_type] @property def icon(self): """Return the icon for this sensor.""" return SENSOR_ICONS[self._sensor_type] @property def unique_id(self): """Return the sensor's unique id.""" return f"{self._device.serial}-{self._sensor_type}" class DysonFilterLifeSensor(DysonSensor): """Representation of Dyson Filter Life sensor (in hours).""" def __init__(self, device): """Create a new Dyson Filter Life sensor.""" super().__init__(device, "filter_life") self._name = f"{self._device.name} Filter Life" @property def state(self): """Return filter life in hours.""" if self._device.state: return int(self._device.state.filter_life) return None class DysonDustSensor(DysonSensor): """Representation of Dyson Dust sensor (lower is better).""" def __init__(self, device): """Create a new Dyson Dust sensor.""" super().__init__(device, "dust") self._name = f"{self._device.name} Dust" @property def state(self): """Return Dust value.""" if self._device.environmental_state: return self._device.environmental_state.dust return None class DysonHumiditySensor(DysonSensor): """Representation of Dyson Humidity sensor.""" def __init__(self, device): """Create a new Dyson Humidity sensor.""" super().__init__(device, "humidity") self._name = f"{self._device.name} Humidity" @property def state(self): """Return Humidity value.""" if self._device.environmental_state: if self._device.environmental_state.humidity == 0: return STATE_OFF return self._device.environmental_state.humidity return None class DysonTemperatureSensor(DysonSensor): """Representation of Dyson Temperature sensor.""" def __init__(self, device, unit): """Create a new Dyson Temperature sensor.""" super().__init__(device, "temperature") self._name = f"{self._device.name} Temperature" self._unit = unit @property def state(self): """Return Temperature value.""" if self._device.environmental_state: temperature_kelvin = self._device.environmental_state.temperature if temperature_kelvin == 0: return STATE_OFF if self._unit == TEMP_CELSIUS: return float(f"{(temperature_kelvin - 273.15):.1f}") return float(f"{(temperature_kelvin * 9 / 5 - 459.67):.1f}") return None @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._unit class DysonAirQualitySensor(DysonSensor): """Representation of Dyson Air Quality sensor (lower is better).""" def __init__(self, device): """Create a new Dyson Air Quality sensor.""" super().__init__(device, "air_quality") self._name = f"{self._device.name} AQI" @property def state(self): """Return Air Quality value.""" if self._device.environmental_state: return int(self._device.environmental_state.volatil_organic_compounds) return None
apache-2.0
5,239,885,266,624,850,000
30.807882
83
0.627536
false
douggeiger/gnuradio
gr-digital/python/digital/qa_digital.py
57
1084
#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital class test_digital(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None if __name__ == '__main__': gr_unittest.run(test_digital, "test_digital.xml")
gpl-3.0
-312,527,151,176,575,300
30.882353
70
0.717712
false
vegitron/django-template-preprocess
template_preprocess/test/extend_block.py
1
2106
from django.test import TestCase from django.test.utils import override_settings from template_preprocess.processor import process_template_content from template_preprocess.test import get_test_template_settings template_settings = get_test_template_settings() @override_settings(**template_settings) class TestExtendBlock(TestCase): def test_basic_block(self): content = '{% include "extends/sub_template1.html" %}' result = process_template_content(content) correct = ('Before {% block inserted_content %}The Block' '{%endblock inserted_content%} {% block block2 %}' 'Block 2{%endblock block2 %} {% block notreplaced %}' 'In wrapper{%endblock%} After ') self.assertEquals(result, correct) def test_extends_missing_template(self): content = '{% include "extends/parent_is_missing.html" %}' result = process_template_content(content) self.assertEquals(result, content) def test_recursive_extends(self): content = '{% include "extends/recursive.html" %}' result = process_template_content(content) self.assertEquals(result, content) def test_nested_blocks(self): content = '{% include "extends/nested.html" %}' result = process_template_content(content) self.assertEquals( result, '{% block a %}{% block b %}{% endblock b %}{% endblock %} ') def test_load_tag_outside_of_block(self): content = '{% include "extends/load_tag_out_of_block.html" %}' result = process_template_content(content) correct = ('{% load another more from app.templatetags %}' '{% load i18n %}Before {% block content %}' 'The content{% endblock %} After ') self.assertEquals(result, correct) def test_multiline_block(self): content = '{% include "extends/multiline.html" %}' result = process_template_content(content) correct = 'Before {%block ok%}Line 1 Line 2{%endblock%} ' self.assertEquals(result, correct)
apache-2.0
5,801,266,574,255,508,000
38
72
0.630579
false
grocsvs/grocsvs
src/grocsvs/main.py
1
5838
from __future__ import print_function import argparse import collections import json import logging import sys from grocsvs import options as svoptions from grocsvs import log from grocsvs import pipeline from grocsvs import utilities from grocsvs import stages as svstages logging.basicConfig(format='%(message)s', level=logging.DEBUG) def ready_output_dir(options): utilities.ensure_dir(options.working_dir) utilities.ensure_dir(options.results_dir) utilities.ensure_dir(options.log_dir) def run(options): """ 1. create output directories 2. collect args for each stage 3. check which stages need to run 4. iterate through stages and submit jobs 5. validate that we're done running """ svoptions.validate_options(options) ready_output_dir(options) stages = get_stages() runner = pipeline.Runner(options) for stage_name, stage in stages.items(): runner.run_stage(stage, stage_name) def clean(options, clean_stage_name): stages = get_stages() if not clean_stage_name in stages: print('*'*20, "ERROR", '*'*20) print('Error: unknown stage "{}". Stage must be one of the '.format(clean_stage_name)) print('following (remember to include surrounding quotation marks):') for i, stage_name in enumerate(stages): print('{:>3} - "{}"'.format(i+1, stage_name)) sys.exit(1) doclean = False for stage_name, stage in stages.items(): if doclean or stage_name == clean_stage_name: doclean = True stage.clean_all_steps(options) def get_stages(): stages = collections.OrderedDict() # Pre-processing stages["Preflight"] = svstages.preflight.PreflightStep stages["Constants"] = svstages.constants.ConstantsStep stages["Estimate Read Cloud Parameters"] = svstages.call_readclouds.EstimateReadCloudParamsStep stages["Call Read Clouds"] = svstages.call_readclouds.CallReadcloudsStep stages["Combine Read Clouds"] = svstages.call_readclouds.CombineReadcloudsStep # stages["Filter Fragments"] = svstages.filter_fragments.FilterFragmentsStep stages["Sample Info"] = svstages.sample_info.SampleInfoStep stages["QC"] = svstages.qc.QCStep # Find SV candidates stages["Window Barcodes"] = svstages.window_barcodes.WindowBarcodesStep stages["Barcode Overlaps"] = svstages.barcode_overlaps.BarcodeOverlapsStep stages["SV Candidate Regions"] = \ svstages.sv_candidate_regions.SVCandidateRegionsStep stages["SV Candidates From Regions"] = \ svstages.sv_candidates.SVCandidatesStep ### Initial clustering ### stages["Refine Breakpoints"] = \ svstages.refine_grid_search_breakpoints.RefineGridSearchBreakpointsStep stages["Combine Refined Breakpoints"] = \ svstages.refine_grid_search_breakpoints.CombineRefinedBreakpointsStep stages["Cluster SVs"] = svstages.cluster_svs.ClusterSVsStep ### Assembly ### stages["Barcodes From Graphs"] = \ svstages.barcodes_from_graphs.BarcodesFromGraphsStep stages["Collect Reads for Barcodes"] = \ svstages.collect_reads_for_barcodes.CollectReadsForBarcodesStep stages["Perform Assembly"] = svstages.assembly.AssemblyStep stages["Walk Assemblies"] = svstages.walk_assemblies.WalkAssembliesStep stages["Postassembly Merge"] = \ svstages.postassembly_merge.PostAssemblyMergeStep ### Final clustering ### stages["Supporting Barcodes"] = \ svstages.supporting_barcodes.SupportingBarcodesStep stages["Pair Evidence"] = svstages.pair_evidence.PairEvidenceStep stages["Final Refine"] = \ svstages.refine_breakpoints.RefineBreakpointsWithAssembliesStep stages["Final Cluster SVs"] = svstages.final_clustering.FinalClusterSVsStep ### Multi-sample genotyping and postprocessing ### stages["Genotyping"] = svstages.genotyping.GenotypingStep stages["Merge Genotypes"] = svstages.genotyping.MergeGenotypesStep stages["Postprocessing"] = svstages.postprocessing.PostprocessingStep stages["Visualize"] = svstages.visualize.VisualizeStep return stages def load_config(config_path): try: config = json.load(open(config_path)) except ValueError as err: print("Error parsing configuration file '{}': '{}'\n Check that this is a properly formatted JSON file!".format(config_path, err)) sys.exit(1) options = svoptions.Options.deserialize(config, config_path) return options def parse_arguments(args): parser = argparse.ArgumentParser(description="Genome-wide Reconstruction of Complex Structural Variants") parser.add_argument("config", help="Path to configuration.json file") parser.add_argument("--restart", metavar="FROM-STAGE", help="restart from this stage") parser.add_argument("--local", action="store_true", help="run locally in single processor mode") parser.add_argument("--multiprocessing", action="store_true", help="run locally using multiprocessing") parser.add_argument("--debug", action="store_true", help="run in debug mode") if len(args) < 1: parser.print_help() sys.exit(1) args = parser.parse_args(args) options = load_config(args.config) options.debug = args.debug print(options) if args.local: options.cluster_settings = svoptions.ClusterSettings() if args.multiprocessing: options.cluster_settings = svoptions.ClusterSettings() options.cluster_settings.cluster_type = "multiprocessing" if args.restart is not None: clean(options, args.restart) log.log_command(options, sys.argv) return options def main(): options = parse_arguments(sys.argv[1:]) run(options) if __name__ == '__main__': main()
mit
9,110,785,281,506,253,000
29.726316
139
0.70024
false
ColOfAbRiX/ansible
lib/ansible/modules/database/vertica/vertica_facts.py
28
9387
#!/usr/bin/python # -*- coding: utf-8 -*- # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = """ --- module: vertica_facts version_added: '2.0' short_description: Gathers Vertica database facts. description: - Gathers Vertica database facts. options: cluster: description: - Name of the cluster running the schema. required: false default: localhost port: description: Database port to connect to. required: false default: 5433 db: description: - Name of the database running the schema. required: false default: null login_user: description: - The username used to authenticate with. required: false default: dbadmin login_password: description: - The password used to authenticate with. required: false default: null notes: - The default authentication assumes that you are either logging in as or sudo'ing to the C(dbadmin) account on the host. - This module uses C(pyodbc), a Python ODBC database adapter. You must ensure that C(unixODBC) and C(pyodbc) is installed on the host and properly configured. - Configuring C(unixODBC) for Vertica requires C(Driver = /opt/vertica/lib64/libverticaodbc.so) to be added to the C(Vertica) section of either C(/etc/odbcinst.ini) or C($HOME/.odbcinst.ini) and both C(ErrorMessagesPath = /opt/vertica/lib64) and C(DriverManagerEncoding = UTF-16) to be added to the C(Driver) section of either C(/etc/vertica.ini) or C($HOME/.vertica.ini). requirements: [ 'unixODBC', 'pyodbc' ] author: "Dariusz Owczarek (@dareko)" """ EXAMPLES = """ - name: gathering vertica facts vertica_facts: db=db_name """ try: import pyodbc except ImportError: pyodbc_found = False else: pyodbc_found = True from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.pycompat24 import get_exception class NotSupportedError(Exception): pass # module specific functions def get_schema_facts(cursor, schema=''): facts = {} cursor.execute(""" select schema_name, schema_owner, create_time from schemata where not is_system_schema and schema_name not in ('public') and (? = '' or schema_name ilike ?) """, schema, schema) while True: rows = cursor.fetchmany(100) if not rows: break for row in rows: facts[row.schema_name.lower()] = { 'name': row.schema_name, 'owner': row.schema_owner, 'create_time': str(row.create_time), 'usage_roles': [], 'create_roles': []} cursor.execute(""" select g.object_name as schema_name, r.name as role_name, lower(g.privileges_description) privileges_description from roles r join grants g on g.grantee = r.name and g.object_type='SCHEMA' and g.privileges_description like '%USAGE%' and g.grantee not in ('public', 'dbadmin') and (? = '' or g.object_name ilike ?) """, schema, schema) while True: rows = cursor.fetchmany(100) if not rows: break for row in rows: schema_key = row.schema_name.lower() if 'create' in row.privileges_description: facts[schema_key]['create_roles'].append(row.role_name) else: facts[schema_key]['usage_roles'].append(row.role_name) return facts def get_user_facts(cursor, user=''): facts = {} cursor.execute(""" select u.user_name, u.is_locked, u.lock_time, p.password, p.acctexpired as is_expired, u.profile_name, u.resource_pool, u.all_roles, u.default_roles from users u join password_auditor p on p.user_id = u.user_id where not u.is_super_user and (? = '' or u.user_name ilike ?) """, user, user) while True: rows = cursor.fetchmany(100) if not rows: break for row in rows: user_key = row.user_name.lower() facts[user_key] = { 'name': row.user_name, 'locked': str(row.is_locked), 'password': row.password, 'expired': str(row.is_expired), 'profile': row.profile_name, 'resource_pool': row.resource_pool, 'roles': [], 'default_roles': []} if row.is_locked: facts[user_key]['locked_time'] = str(row.lock_time) if row.all_roles: facts[user_key]['roles'] = row.all_roles.replace(' ', '').split(',') if row.default_roles: facts[user_key]['default_roles'] = row.default_roles.replace(' ', '').split(',') return facts def get_role_facts(cursor, role=''): facts = {} cursor.execute(""" select r.name, r.assigned_roles from roles r where (? = '' or r.name ilike ?) """, role, role) while True: rows = cursor.fetchmany(100) if not rows: break for row in rows: role_key = row.name.lower() facts[role_key] = { 'name': row.name, 'assigned_roles': []} if row.assigned_roles: facts[role_key]['assigned_roles'] = row.assigned_roles.replace(' ', '').split(',') return facts def get_configuration_facts(cursor, parameter=''): facts = {} cursor.execute(""" select c.parameter_name, c.current_value, c.default_value from configuration_parameters c where c.node_name = 'ALL' and (? = '' or c.parameter_name ilike ?) """, parameter, parameter) while True: rows = cursor.fetchmany(100) if not rows: break for row in rows: facts[row.parameter_name.lower()] = { 'parameter_name': row.parameter_name, 'current_value': row.current_value, 'default_value': row.default_value} return facts def get_node_facts(cursor, schema=''): facts = {} cursor.execute(""" select node_name, node_address, export_address, node_state, node_type, catalog_path from nodes """) while True: rows = cursor.fetchmany(100) if not rows: break for row in rows: facts[row.node_address] = { 'node_name': row.node_name, 'export_address': row.export_address, 'node_state': row.node_state, 'node_type': row.node_type, 'catalog_path': row.catalog_path} return facts # module logic def main(): module = AnsibleModule( argument_spec=dict( cluster=dict(default='localhost'), port=dict(default='5433'), db=dict(default=None), login_user=dict(default='dbadmin'), login_password=dict(default=None), ), supports_check_mode = True) if not pyodbc_found: module.fail_json(msg="The python pyodbc module is required.") db = '' if module.params['db']: db = module.params['db'] try: dsn = ( "Driver=Vertica;" "Server=%s;" "Port=%s;" "Database=%s;" "User=%s;" "Password=%s;" "ConnectionLoadBalance=%s" ) % (module.params['cluster'], module.params['port'], db, module.params['login_user'], module.params['login_password'], 'true') db_conn = pyodbc.connect(dsn, autocommit=True) cursor = db_conn.cursor() except Exception: e = get_exception() module.fail_json(msg="Unable to connect to database: %s." % str(e)) try: schema_facts = get_schema_facts(cursor) user_facts = get_user_facts(cursor) role_facts = get_role_facts(cursor) configuration_facts = get_configuration_facts(cursor) node_facts = get_node_facts(cursor) module.exit_json(changed=False, ansible_facts={'vertica_schemas': schema_facts, 'vertica_users': user_facts, 'vertica_roles': role_facts, 'vertica_configuration': configuration_facts, 'vertica_nodes': node_facts}) except NotSupportedError: e = get_exception() module.fail_json(msg=str(e)) except SystemExit: # avoid catching this on python 2.4 raise except Exception: e = get_exception() module.fail_json(msg=e) if __name__ == '__main__': main()
gpl-3.0
-8,531,791,704,919,773,000
32.052817
98
0.579844
false
suninsky/ReceiptOCR
Python/server/lib/python2.7/site-packages/markupsafe/__init__.py
144
10697
# -*- coding: utf-8 -*- """ markupsafe ~~~~~~~~~~ Implements a Markup string. :copyright: (c) 2010 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import re import string from collections import Mapping from markupsafe._compat import text_type, string_types, int_types, \ unichr, iteritems, PY2 __version__ = "1.0" __all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent'] _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)') _entity_re = re.compile(r'&([^& ;]+);') class Markup(text_type): r"""Marks a string as being safe for inclusion in HTML/XML output without needing to be escaped. This implements the `__html__` interface a couple of frameworks and web applications use. :class:`Markup` is a direct subclass of `unicode` and provides all the methods of `unicode` just that it escapes arguments passed and always returns `Markup`. The `escape` function returns markup objects so that double escaping can't happen. The constructor of the :class:`Markup` class can be used for three different things: When passed an unicode object it's assumed to be safe, when passed an object with an HTML representation (has an `__html__` method) that representation is used, otherwise the object passed is converted into a unicode string and then assumed to be safe: >>> Markup("Hello <em>World</em>!") Markup(u'Hello <em>World</em>!') >>> class Foo(object): ... def __html__(self): ... return '<a href="#">foo</a>' ... >>> Markup(Foo()) Markup(u'<a href="#">foo</a>') If you want object passed being always treated as unsafe you can use the :meth:`escape` classmethod to create a :class:`Markup` object: >>> Markup.escape("Hello <em>World</em>!") Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!') Operations on a markup string are markup aware which means that all arguments are passed through the :func:`escape` function: >>> em = Markup("<em>%s</em>") >>> em % "foo & bar" Markup(u'<em>foo &amp; bar</em>') >>> strong = Markup("<strong>%(text)s</strong>") >>> strong % {'text': '<blink>hacker here</blink>'} Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>') >>> Markup("<em>Hello</em> ") + "<foo>" Markup(u'<em>Hello</em> &lt;foo&gt;') """ __slots__ = () def __new__(cls, base=u'', encoding=None, errors='strict'): if hasattr(base, '__html__'): base = base.__html__() if encoding is None: return text_type.__new__(cls, base) return text_type.__new__(cls, base, encoding, errors) def __html__(self): return self def __add__(self, other): if isinstance(other, string_types) or hasattr(other, '__html__'): return self.__class__(super(Markup, self).__add__(self.escape(other))) return NotImplemented def __radd__(self, other): if hasattr(other, '__html__') or isinstance(other, string_types): return self.escape(other).__add__(self) return NotImplemented def __mul__(self, num): if isinstance(num, int_types): return self.__class__(text_type.__mul__(self, num)) return NotImplemented __rmul__ = __mul__ def __mod__(self, arg): if isinstance(arg, tuple): arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg) else: arg = _MarkupEscapeHelper(arg, self.escape) return self.__class__(text_type.__mod__(self, arg)) def __repr__(self): return '%s(%s)' % ( self.__class__.__name__, text_type.__repr__(self) ) def join(self, seq): return self.__class__(text_type.join(self, map(self.escape, seq))) join.__doc__ = text_type.join.__doc__ def split(self, *args, **kwargs): return list(map(self.__class__, text_type.split(self, *args, **kwargs))) split.__doc__ = text_type.split.__doc__ def rsplit(self, *args, **kwargs): return list(map(self.__class__, text_type.rsplit(self, *args, **kwargs))) rsplit.__doc__ = text_type.rsplit.__doc__ def splitlines(self, *args, **kwargs): return list(map(self.__class__, text_type.splitlines( self, *args, **kwargs))) splitlines.__doc__ = text_type.splitlines.__doc__ def unescape(self): r"""Unescape markup again into an text_type string. This also resolves known HTML4 and XHTML entities: >>> Markup("Main &raquo; <em>About</em>").unescape() u'Main \xbb <em>About</em>' """ from markupsafe._constants import HTML_ENTITIES def handle_match(m): name = m.group(1) if name in HTML_ENTITIES: return unichr(HTML_ENTITIES[name]) try: if name[:2] in ('#x', '#X'): return unichr(int(name[2:], 16)) elif name.startswith('#'): return unichr(int(name[1:])) except ValueError: pass # Don't modify unexpected input. return m.group() return _entity_re.sub(handle_match, text_type(self)) def striptags(self): r"""Unescape markup into an text_type string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u'Main \xbb About' """ stripped = u' '.join(_striptags_re.sub('', self).split()) return Markup(stripped).unescape() @classmethod def escape(cls, s): """Escape the string. Works like :func:`escape` with the difference that for subclasses of :class:`Markup` this function would return the correct subclass. """ rv = escape(s) if rv.__class__ is not cls: return cls(rv) return rv def make_simple_escaping_wrapper(name): orig = getattr(text_type, name) def func(self, *args, **kwargs): args = _escape_argspec(list(args), enumerate(args), self.escape) _escape_argspec(kwargs, iteritems(kwargs), self.escape) return self.__class__(orig(self, *args, **kwargs)) func.__name__ = orig.__name__ func.__doc__ = orig.__doc__ return func for method in '__getitem__', 'capitalize', \ 'title', 'lower', 'upper', 'replace', 'ljust', \ 'rjust', 'lstrip', 'rstrip', 'center', 'strip', \ 'translate', 'expandtabs', 'swapcase', 'zfill': locals()[method] = make_simple_escaping_wrapper(method) # new in python 2.5 if hasattr(text_type, 'partition'): def partition(self, sep): return tuple(map(self.__class__, text_type.partition(self, self.escape(sep)))) def rpartition(self, sep): return tuple(map(self.__class__, text_type.rpartition(self, self.escape(sep)))) # new in python 2.6 if hasattr(text_type, 'format'): def format(*args, **kwargs): self, args = args[0], args[1:] formatter = EscapeFormatter(self.escape) kwargs = _MagicFormatMapping(args, kwargs) return self.__class__(formatter.vformat(self, args, kwargs)) def __html_format__(self, format_spec): if format_spec: raise ValueError('Unsupported format specification ' 'for Markup.') return self # not in python 3 if hasattr(text_type, '__getslice__'): __getslice__ = make_simple_escaping_wrapper('__getslice__') del method, make_simple_escaping_wrapper class _MagicFormatMapping(Mapping): """This class implements a dummy wrapper to fix a bug in the Python standard library for string formatting. See http://bugs.python.org/issue13598 for information about why this is necessary. """ def __init__(self, args, kwargs): self._args = args self._kwargs = kwargs self._last_index = 0 def __getitem__(self, key): if key == '': idx = self._last_index self._last_index += 1 try: return self._args[idx] except LookupError: pass key = str(idx) return self._kwargs[key] def __iter__(self): return iter(self._kwargs) def __len__(self): return len(self._kwargs) if hasattr(text_type, 'format'): class EscapeFormatter(string.Formatter): def __init__(self, escape): self.escape = escape def format_field(self, value, format_spec): if hasattr(value, '__html_format__'): rv = value.__html_format__(format_spec) elif hasattr(value, '__html__'): if format_spec: raise ValueError('No format specification allowed ' 'when formatting an object with ' 'its __html__ method.') rv = value.__html__() else: # We need to make sure the format spec is unicode here as # otherwise the wrong callback methods are invoked. For # instance a byte string there would invoke __str__ and # not __unicode__. rv = string.Formatter.format_field( self, value, text_type(format_spec)) return text_type(self.escape(rv)) def _escape_argspec(obj, iterable, escape): """Helper for various string-wrapped functions.""" for key, value in iterable: if hasattr(value, '__html__') or isinstance(value, string_types): obj[key] = escape(value) return obj class _MarkupEscapeHelper(object): """Helper for Markup.__mod__""" def __init__(self, obj, escape): self.obj = obj self.escape = escape __getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x], s.escape) __unicode__ = __str__ = lambda s: text_type(s.escape(s.obj)) __repr__ = lambda s: str(s.escape(repr(s.obj))) __int__ = lambda s: int(s.obj) __float__ = lambda s: float(s.obj) # we have to import it down here as the speedups and native # modules imports the markup type which is define above. try: from markupsafe._speedups import escape, escape_silent, soft_unicode except ImportError: from markupsafe._native import escape, escape_silent, soft_unicode if not PY2: soft_str = soft_unicode __all__.append('soft_str')
mit
2,225,617,646,636,672,500
34.072131
82
0.567355
false